From bokr at oz.net Sun Sep 7 15:18:52 2003 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2003 19:18:52 GMT Subject: negative indices for sequence types References: Message-ID: On 7 Sep 2003 11:26:28 -0700, danbmil99 at yahoo.com (dan) wrote: >I was recently surprised, and quite shocked in fact, to find that >Python treats negative indices into sequence types as if they were >mod(length-of-sequence), at least up to -len(seq). > >This fact is *deeply* buried in the docs, and is not at all intuitive. > One of the big advantages of a high-level language such as Python is >the ability to provide run-time bounds checking on array-type >constructs. To achieve this I will now have to subclass my objects >and add it myself, which seems silly and will add significant >overhead. If you want this behavior, how hard is it to say a = b[x % >len(b)] ?? That isn't really the exact behavior. E.g., >>> range(5) [0, 1, 2, 3, 4] >>> range(5)[-4] 1 >>> range(5)[-5] 0 >>> range(5)[-6] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range >>> range(5)[4] 4 >>> range(5)[5] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range >Can anyone explain why this anomaly exists, and why it should continue >to exist? It has apparently proven more useful to have it so than not, though I sympathize with your frustration in for your use. Perhaps a .no_negative_indexing attribute or something could be added to the C implementation, so that you could specify your desired checking without a performance hit. Meanwhile, maybe an assert i>=0 in the index-supplier side of the contract might work too? Regards, Bengt Richter From mickel at csc.fi Tue Sep 23 03:05:04 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Tue, 23 Sep 2003 10:05:04 +0300 (EEST) Subject: Checking if the computer is online In-Reply-To: References: Message-ID: On Thu, 18 Sep 2003, Thomas Bellman wrote: > Mickel Gr?nroos wrote: > > > Hi all, > > > I have a silly question. Is there are simple way to check if the computer > > is connected to the Internet? It seems this should be a pretty > > straight-forward thing to do, but as I am totally unfamiliar with sockets > > and such, I ask for your help before getting my hands dirty. > > First of all you need to define what "being online" means... [...] > Or perhaps you should tell us *why* you believe you need to check > if the computer is connected to the Internet or not. Then we can > go directly to telling you that it is a bad idea, and suggest what > you should do instead. <0.5 wink> OK, here's what I want to do: When the Tkinter application I am writing starts up, it checks if certain files on the web exists and if so, it downloads them to a local directory replacing possible earlier copies of these files. So, what I mean by checking if the computer is online is that I want to check if I can access these certain remote files with urllib.urlretrieve(). If I can, then I download them. If I can't, I assume the computer is not connected to the Internet and I skip the update phase. The problem with just running urllib.urlretrieve() is that the execution of the script halts as there is no timeout available for Python 2.2.2. (I tried timeoutsocket.py to get this done, but that only worked on Windows 2000, not Redhat Linux 7.0. I also tried upgrading to Python 2.3, but that caused some other problems, especially with the gettext module and with the fact that my ISO-8859-1 encoded files needed a "coding" line.) So that's that. Anybody still got a few lines of code that would get this done on Python 2.2.2 on Windows _and_ Linux? Cheers, /Mickel G. -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From robin at jessikat.fsnet.co.uk Sun Sep 7 17:31:29 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 7 Sep 2003 22:31:29 +0100 Subject: Redesign of Python site References: Message-ID: In article , rt lange writes >came across this page searching feedster. >dont know whether this is the official resdesign or just a proposal; >but the mockups look very nice. > >http://www.pollenation.net/journal/index.php?p=37&c=1 > >main page mockup: >http://www.pollenation.net/assets/public/python-main.html > >interior page: >http://www.pollenation.net/assets/public/python-interior.html It looks nice, but is really slow or is that just the demo site? Using those big images really slows things down for me at least. -- Robin Becker From dek at compbio.berkeley.edu Tue Sep 9 19:40:12 2003 From: dek at compbio.berkeley.edu (David Konerding) Date: Tue, 9 Sep 2003 23:40:12 +0000 (UTC) Subject: logging module: log method with keyword arguments Message-ID: Hi, I am trying to write my own Logging Handler object, to work within an existing logging system that I use. However, when I try to dispatch log calls to the logger, I get an error in an internal logging call. Here's an example code: logger = logging.getLogger('test') logger_handler = logging.StreamHandler(sys.stdout) logger_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') logger_handler.setFormatter(logger_formatter) logger.addHandler(logger_handler) logger.setLevel(logging.DEBUG) logger.debug("Message: %(msg2)", msg2="foo") The message I get is: File "/home/portnoy/d5/dek/sw/rh9/Python-2.3/lib/python2.3/logging/__init__.py", line 879, in debug apply(self._log, (DEBUG, msg, args), kwargs) TypeError: _log() got an unexpected keyword argument 'msg2' Now, I can kind of understand this because the documentation for the debug() method says: The only keyword argument in kwargs which is inspected is exc_info which, if it does not evaluate as false, causes exception information (via a call to sys.exc_info()) to be added to the logging message. My only problem is that the documentation doesn't say anything about not accepting kwargs which aren't "exc_info" (I recognize the syntax I used above doesn't actually do what I wanted anyway). Dave From netvegetable at fastmail.fm Sun Sep 21 02:42:35 2003 From: netvegetable at fastmail.fm (netvegetable) Date: Sun, 21 Sep 2003 15:42:35 +0900 Subject: OT: Re: python script as an emergency mailbox cleaner References: Message-ID: On Sat, 20 Sep 2003 14:37:45 +0000, Phil Weldon wrote: > It's a worm. Worm.Automat.AGH. This is going to be a bad one. The worm > installs, among other things, an SMPT engine, searches an infected system > for email address, and sends two types of e-mail: the first is HTML and > is a fake "security patch" supposedly from Microsoft. It looks very > official, but the attachment, 104 KBytes long, is infectious. Norton > Antivirus definitions only began to identify it with the 18SEP03 manual > definition update. The worm also posts to usenet newsgroups. The other > type of e-mail is a fake notification of undeliverable e-mail. This one > is a real bear. There seem to be hundreds variations in the body content > and thousands of variations in the header. The infectious package is also > about 104 KBytes. I'm getting nearly 100 of the two types per hour. > Norton Antivirus does not detect the worm in usnet posts read by Outlook > Express Newsreader or Outlook Newsreader. Only when you attempt to open > the attachment or save the attachment to disk will Norton identify it. > Norton will NOT detect the virus in the newsgroup posts folder NOR will it > detect the newsgroup folder in a full system scan. It will not remove the > infected file from the newsgroup folder, but it will prevent execution of > the vermal payload. > > Microsoft Outlook with the SP3 security update when used as your e-mail > reader protects against infection. Prior to 18SEP03 Norton did not. > > The worm is also retrieving additional variations, so you can expect the > payload size to begin changing soon. The HTML message is easy to > identify; it is always the same (so far), and includes the phrase 'Run > attached file'. The bogus 'Undeliverable e-mail' variations have no > commonality but the payload attachment (that purports to be your bounced > e-mail.) This will likley change soon. > > My guess is that the internet will not open on Monday. The worm uses newsgroup info from Outlook Express as well. What's to stop a worm from retrieving header file info, and using the NNTP posting header to actually hack people's computers? -- to email me remove underscore _ death to spammers From geoff at gerrietts.net Fri Sep 19 19:30:03 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 19 Sep 2003 16:30:03 -0700 Subject: os.environ and os.path.chdir In-Reply-To: References: Message-ID: <20030919233003.GB2478@thoth.homegain.com> Quoting Yun Mao (maoy at cis.upenn.edu): > Hi, > How to make changes to os.environ and os.path.chdir still effective after > I run the script? Currently, the changes are only good within my script. I > would like the shell who called python myprog.py also gets the change.. > Thank you! To the best of my knowledge, this can't be done. Depending on the specific application, you might have several workarounds. One is to exit into a new shell, using os.execve instead of sys.exit. That creates "nested" shells, unless the user exec's your program also. Another is to exit by printing a list of commands, and expect that the user will run your program like "eval `myprog.py`" to execute those commands. As far as I know, though, there's no way to actually hijack the user's shell process. The user needs to explicitly give you that control. --G. -- Geoff Gerrietts "There is no fate that cannot be surmounted by scorn." --Albert Camus From dyoo at hkn.eecs.berkeley.edu Mon Sep 8 14:44:10 2003 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 8 Sep 2003 18:44:10 +0000 (UTC) Subject: ANN: [DATE CHANGE] Baypiggies User Group Meeting, September 10, 2003 References: Message-ID: Hi everyone, Sorry for repeating the post, but I mistyped the date! The meeting will be held this Wednesday, not Thursday. Here is a repost of the announcement: ---------------- BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: Wednesday, September 10, 2003 @ 7:30pm Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: Wavelets for SciPy Speaker: Chad Netzer Abstract: This talk will demonstrate an implementation of a wavelets package for SciPy, and present some applications with signal processing and image classification. There will be discussion of the benefits of doing scientific computation with Python, unit testing with statistical methods, and using SciPy with PythonCard as a learning tool. (Knowledge of wavelets is not a requirement, and the math will be kept to a minimum) For driving directions, please visit: http://baypiggies.net We hope to see you there! From glingl at aon.at Mon Sep 8 07:51:28 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon, 08 Sep 2003 13:51:28 +0200 Subject: GIFs Using Tkinter Message-ID: <3F5C6D40.6070309@aon.at> I'm trying to use recipe 9.5 from Python Cookbook, which suggests to read gifs from files using base64.encodestring in order to embed those images into my sourcecode. I've prepared some 20 gifs with Photoshop which are all merely rotated versions of some "master"-gif. (They all are produced in exactly the same way and have (255,255,255) as transparent color.) They all can be used as Tkinter PhotoImages with the file-option perfectly well. However, if I try to use the data-option with strings constructed from those same gifs according to the recipe mentioned above, I observe, that among those gif-images (1) some can be displayed correctly (more than 50%) (2) some are corrupted and are displayed with stripes or other artefacts. (3) and some result in strings only a few characters long which cannot be interpreted as image-data at all. What could be the reason for this annoying behaviour and how can I avoid it. Thanks in advance Gregor From none at none.net Wed Sep 24 07:38:14 2003 From: none at none.net (Sami Viitanen) Date: Wed, 24 Sep 2003 11:38:14 GMT Subject: command exit status on windows Message-ID: Hello, Is there a way to check if a command executed in ms-dos returns 0 (success) or greater than 0 (fail) ? In Unix the module commands.getstatusoutput returns exit status.. Thanks in advance. -SV From reply.in.the.newsgroup at my.address.is.invalid Wed Sep 24 09:54:06 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 24 Sep 2003 15:54:06 +0200 Subject: Python <-> C via sockets References: <8ad2cfb3.0309240113.19d9198a@posting.google.com> <8ad2cfb3.0309240530.19029a98@posting.google.com> Message-ID: <6f83nv47k9m7qm4pace4lvfdfaqmof47ei@4ax.com> Nick Keighley: > sin.sin_port = PORT; "serv_addr.sin_port = htons(portno); The second field of serv_addr is unsigned short sin_port , which contain the port number. However, instead of simply copying the port number to this field, it is necessary to convert this to network byte order using the function htons() which converts a port number in host byte order to a port number in network byte order." http://www.cs.rpi.edu/courses/sysprog/sockets/sock.html -- Ren? Pijlman From CousinStanley at hotmail.com Wed Sep 3 22:24:39 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 3 Sep 2003 19:24:39 -0700 Subject: How to accelerate python application GUI speed References: <43e3984e.0309030532.3fe88bbc@posting.google.com> <87n0dmj82w.fsf@flibuste.net> <877k4q6jj1.fsf@pobox.com> <87ekyxinsx.fsf@flibuste.net> <877k4pfmy3.fsf@pobox.com> Message-ID: | But you can use Python just as easily. | | John .... I did that example HTA using VBScript about 3 years ago before I even knew that Python existed and just posted it as a handy example to illustrate basically what a local HTA could do .... It would be WAY cooler to do it in Python, and now that I know it's possible I'll try it .... -- Cousin Stanley Human Being Phoenix, Arizona From Jim.Vickroy at noaa.gov Wed Sep 17 12:59:54 2003 From: Jim.Vickroy at noaa.gov (Jim Vickroy) Date: Wed, 17 Sep 2003 10:59:54 -0600 Subject: [egenix-users] mx.DateTime bogus warning: "float where int expected" References: <33436.199.169.240.132.1063814659.squirrel@svr1.turboweb.net> Message-ID: <3F68930A.CD2E4C63@noaa.gov> I do not have an explanation, but the statement: dt = self.firstdate + self.mm * int(i) appears to be the source of this warning. The warning only appears the first time the statement is executed; thereafter, no warning is issued. python at sarcastic-horse.com wrote: > Hi- > > I'm getting a "DeprecationWarning: integer argument expected, got float" > warning with mx.DateTime and I can't figure out why. Can anyone help me > out? > > This code: > > import mx.DateTime > > class xLabeller: > def __init__(self, firstdate,fmt='%B, %Y'): > self.firstdate = firstdate > self.fmt = fmt > self.mm = mx.DateTime.RelativeDateTime(months=1) > def __call__(self, i): > dt = self.firstdate + self.mm * int(i) > return dt.Format(self.fmt) > > nov99 = mx.DateTime.Date(int(1999), int(11)) > > xl = xLabeller(nov99) > print "xl2:" > print xl(int(3)) > > Produces this warning: > > >>> ================================ RESTART =========== > >>> > xl2: > C:\Python23\lib\site-packages\mx\DateTime\DateTime.py:585: > DeprecationWarning: integer argument expected, got float > return DateTime(year, month, 1) + \ > February, 2000 > > What is the story? I've wrapped every number in my program with int(). I > can't figure out what's triggering the warning. > > And, even stranger, the whole thing works fine at the python shell: > > >>> import mx.DateTime > >>> mm = mx.DateTime.RelativeDateTime(months=1) > >>> nov99 > > >>> dt = nov99 + mm * 3 > >>> dt.Format('%b, %y') > 'Feb, 00' > >>> > > What am I doing wrong? > > Thanks for the help. > > _______________________________________________________________________ > eGenix.com User Mailing List http://www.egenix.com/ > http://lists.egenix.com/mailman/listinfo/egenix-users From skchim0 at engr.uky.edu Fri Sep 19 18:16:11 2003 From: skchim0 at engr.uky.edu (satish) Date: Fri, 19 Sep 2003 18:16:11 -0400 Subject: Custom Execution from Python Message-ID: <200309191816.11721.skchim0@engr.uky.edu> Hello all, I have a shared object executable viz. *cable* which I execute as follows : $ ansyscust71 -custom cable -p ANSYSRF **ansyscust71 is a shell script and is a part of a software called ANSYS** Now, I have generated a python module using a *fortran-python interface generator called F2PY* using the same *make rules* which were used to make *cable* when not using F2PY I got a Python extension module named *cable_f2py* again. From the python environment when I tried to execute *cable_f2py* ( this is python module due to F2PY), I got a segmentation error just like how I would get this error when I execute *cable* as follows when not using F2PY: $ ./cable Segmentation Fault However, when I execute it as follows, it works $ansyscust71 -custom cable -p ANSYSRF --> This is required for succesful execution Now, I dont understand how I can mimic the above way of execution from within Python to execute *cable_f2py* which as I mentioned earlier is the result of making and linking all the same libraries which were used while making and linking cable I am really confused Can someone help me ?? Thanks in advance, Best Regards, Satish -- SATISH KUMAR CHIMAKURTHI Graduate Teaching Assistant CFD GROUP UNIVERSITY OF KENTUCKY LEXINGTON KENTUCKY - 40508 Email: skchim0 at engr.uky.edu Mobile: 859-312-8425 Vice-President American Institute Of Aeronautics and Astronautics Student Chapter University Of Kentucky From jjl at pobox.com Thu Sep 11 19:06:08 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Sep 2003 00:06:08 +0100 Subject: mixing for x in file: and file.readline References: Message-ID: <87wucf53j3.fsf@pobox.com> "Russell E. Owen" writes: > At one time, mixing for x in file and readline was dangerous. For > example: > > for line in file: > # read some lines from a file, then break > nextline = readline() # bad > > would not do what a naive user might expect because the file iterator > buffered data and readline did not read from that buffer. Hence the call > to readline might unexpectedly skip some lines. > > I stumbled across this the hard way, but am wondering if it's still > present in Python 2.3. I thought I'd seen it documented recently, but > looking through the description of the file object in the Python Library > Reference, I didn't see it. There was a thread-fragment about this a while back. See the message from Steven Taschuk a few messages past this one: http://www.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=87llukrdow.fsf%40pobox.com&rnum=1&prev=/groups%3Fas_q%3D%2522for%2520line%2520in%2520file%253A%2522%2520group%253Acomp.lang.python%26safe%3Dimages%26ie%3DISO-8859-1%26as_uauthors%3Djjl%40pobox.com%26lr%3D%26num%3D30%26hl%3Den http://tinyurl.com/n2cc > Anyone know if it's still an issue? If so, anyone have any idea how hard [...] Was fixed in 2.3, maybe in 2.2.3 also (not sure). John From mertz at gnosis.cx Tue Sep 30 13:28:36 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 30 Sep 2003 13:28:36 -0400 Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> Message-ID: bokr at oz.net (Bengt Richter) wrote previously: |just make a bit map of the 10**8 on disk, which would only be | >>> 10**8/8000000. | 12.5 |megabytes. I had been thinking about this also, but Bengt beat me to posting something. I think that we could pick up Emile van Sebille's suggestion about gaps only needing to store even numbers here; the equivalent being that we only store a bit array of ODD numbers, getting us down to 6.25 mB of storage space (special casing of the prime '2' needs to be handled, seems manageable :-)). Doing this does not necessarily produce a smaller storage format than a zip'd bitmap of all the numbers. But the in-memory image doesn't require a decompression step (and the stored version can still be compressed). I guess the test is something like: prime_bits = open('bitarray.primes','rb').read() # only odd nums def isPrime(N): if N < 2: return False elif N==2: return True else: byte, bit = divmod(N, 16) bit = bit//2 return ord(prime_bits[byte]) & 2**bit You could also use a memory-mapped file or the like, of course. |Nth-prime and how-many-below-N would need some other representations. |You could translate the bit map to a sequence of prime counts for 8 or 16-bit |chunks with a simple 2*8 or 2**16 byte table mapping bytes or 16-bit chunks to |the counts of bits within them, then sum and only fiddle with one bit chunk to |make an nth-prime table... The ancillary data structure would indeed speed the "how-many-below" calculation enormously, while not taking too much space. Along those lines, what's the quickest way to count bits in Python? Maybe someone has a clever idea... something that would run a whole bunch faster than my bit mask style above for counting all the "1"s in a multibyte string. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From p at ulmcnett.com Mon Sep 8 18:20:57 2003 From: p at ulmcnett.com (Paul McNett) Date: Mon, 8 Sep 2003 15:20:57 -0700 Subject: Eureka! (Re: Comments on Python Redesign) In-Reply-To: <87u17nne1a.fsf@pobox.com> References: <87u17nne1a.fsf@pobox.com> Message-ID: <200309081520.57743.p@ulmcnett.com> John J. Lee writes: > > * There's no guarantee tiny urls will remain unique or even > > available for long periods of time. Their current practice > > of using four lower-case letters suggests they have space > > for about 450,000 unique URLs before extending to a fifth > > letter. > > Good practice to give both URLs, I suppose -- easier to > cut-n-paste the tinyurl, but the original one has a better > chance of still working later. Just what is the problem with posting long url's anyway? Just turn off wordwrap, and send. Example of a long url (I have wordwrap off): http://www.amazon.com/exec/obidos/tg/detail/-/0321112547/qid=1063059237/sr=1-4/ref=sr_1_4/002-8213749-9028058?v=glance&s=books TinyURL is perhaps a cute idea though... -- Paul McNett From gillet at scripps.edu Mon Sep 29 19:39:54 2003 From: gillet at scripps.edu (Alexandre Gillet) Date: Mon, 29 Sep 2003 16:39:54 -0700 Subject: build a static python executable on linux? In-Reply-To: References: Message-ID: I am able to compile a static interpreter (using -static -static-libgcc) but I can not build the extensions correctly. When I import an extensions (ie Tkinter, readline) I get undefine symbol error. It seems the symbol should be define in glibc but the extensions can't seems to find it. Any ideas how I should built the extensions Thanks Alex Christos TZOTZIOY Georgiou wrote: > On Mon, 29 Sep 2003 15:42:34 -0700, rumours say that Alexandre Gillet > might have written: > > >>I am trying to build a python interpreter that is static link. >>My python interpreter was build on RedHat 8.0 using gcc 2.3 and GLIBC 2.3 >>When running on other linux flavor that still have GLIBC 2.2, the >>interpreter won't start. (error message: /lib/libc.so.6: version >>`GLIBC_2.3' not found (required by /mgl/python/i86Linux2/bin/python2.3) > > > I believe you should install the glibc-static-devel package and then > find the approprate options for gcc (my noisy linux computer is turned > off now so I can't man gcc, but IIRC is -static :) in order to build a > static python. From dave at 3dex.com Thu Sep 11 14:48:56 2003 From: dave at 3dex.com (Dave Benjamin) Date: Thu, 11 Sep 2003 18:48:56 GMT Subject: mod_python installation References: Message-ID: "Patrick Useldinger" wrote in message news:kue1mv4fer2lncl8r17q2vmhi30drvme2k at 4ax.com... > I have added the loadModule command for mod_python: "LoadModule > python_module modules/mod_python.so", and the file is there. > > Apache won't start anymore. No error message is in Apache's log file. > Uncommenting the loadModule command makes apache start correctly. This might be a dumb question, but did you check the error log or the access log? What happens when you try to start apache from the command line? (is that possible in Windows? I've never tried...) Good luck, Dave From gh at ghaering.de Mon Sep 15 07:32:43 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 15 Sep 2003 13:32:43 +0200 Subject: caching the sql queries In-Reply-To: References: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> Message-ID: <3F65A35B.4080003@ghaering.de> "JZ" wrote: > On Mon, 15 Sep 2003 12:55:15 +0200, "Luca Calderano" > >>>Is there any equivalent of caching sql queries for Python like ADOdb >>>for PHP? (For those who did not hear about ADODb and its feature : >>>http://phplens.com/adodb/caching.of.recordsets.html) >> >>The Only way is using Com > > What do you mean? Luca was mistaking the ADODB from Microsoft's ActiveX Data Objects (ADO) with the PHP API of the same name. -- Gerhard From news at exultants.org Tue Sep 2 23:01:14 2003 From: news at exultants.org (Van Gale) Date: Wed, 03 Sep 2003 03:01:14 GMT Subject: Python REST framework? References: Message-ID: On Tue, 02 Sep 2003 14:50:19 -0400, Jeremy Jones wrote: > > Does anyone know if there exists a Python REST (web services) framework? > I've googled and come up short. I don't think it should be that hard to > do if one doesn't exist (famous last words). I guess one could subclass > BaseHTTPServer and have specified things to do depending on the path and > the method? > > > Jeremy Jones Here's a nice little REST writeup with some sample Python code by Ken MacLeod: Otherwise, as Dave Kuhlman mentions it's not that hard to build REST on top of some of the existing frameworks like Quixote. Van Gale From chris.gonnerman at newcenturycomputers.net Sun Sep 14 00:57:28 2003 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sat, 13 Sep 2003 23:57:28 -0500 Subject: [Python] gdmodule true type font size References: Message-ID: <000b01c37a7c$b31d96a0$1f00000a@Belkin> ----- Original Message ----- From: "John Hunter" > When using gdmodule to draw text using true > type fonts > > im.string_ttf(font, fontsize, angle, (x,y), s, color) > > the docs say 'draw string s at (x,y) using the > TrueType font at the given pointsize and > angle.' It is not clear to me how gd handles > point size. A fontsize of 12 should be 12/72 = > 1/6 inches tall but how does gd decide what an > inch is? 72 pixels? Is there some scale > parameter or constant that allows gd to make > the conversion from pixels to points? No. The underlying GD library assumes 1 point is exactly 1 pixel. Font metrics are pretty fuzzy, so your mileage may vary slightly especially with script fonts. > I want my text to scale with image resolution > which is determined by a dpi parameter, and I > tried doing > > scale = dpi/72.0 > > im.string_ttf(font, scale*fontsize, angle, (x,y), s, color) > > but the fonts are larger than they should be, > at least according to my calculations. You've got me here. Perhaps if I knew what you were trying to accomplish at a bit higher level, I might be able to make a suggestion. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From bogus at invalid.tld Sat Sep 6 06:28:11 2003 From: bogus at invalid.tld (Jules Dubois) Date: Sat, 6 Sep 2003 04:28:11 -0600 Subject: Writing solid code book References: <3f566751.342339448@news.blueyonder.co.uk> Message-ID: On 4 Sep 2003 02:40:50 -0700, post400 wrote: So maybe you (experienced python guys ) [...] I'm not experienced with Python. I wrote my first forty (or so) lines of code Thursday morning. > [...] could make some > suggestions from time to time about the must-read books , not > necessarily on python but also on stuff about design , project > management , OOP , etc. be it new stuff or old stuff. Books I particularly liked: _Object Oriented Software Construction, 1E_. Meyer. (OOP) _Design Patterns_. Gamma, Helm, Johnson, Vlissides. _Refactoring_. Fowler. For OOP stuff, you might look at the comp.object newsgroup. There are some Wars of Religion there, but also some good information; Robert Martin (Uncle Bob) and Martin Fowler post there. > But I really wonder > how a non-programmer could get into python as a first programming > language since there's not much publicity and not many people around > to lure you to it. Publicity and lure are not the most important things to consider when choosing a first language. For education, as opposed to training, I maintain the first two languages a beginner should learn are Smalltalk and then Common Lisp. Even though they're not the most widely-used languages, these two will do more to teach the fundamentals of programming than will Java, Python, Ruby, C++, Perl, PHP, C#, or (especially) VBA. From koen_van_herck at yahoo.com Fri Sep 19 04:35:52 2003 From: koen_van_herck at yahoo.com (Koen Van Herck) Date: 19 Sep 2003 01:35:52 -0700 Subject: Retrieve class name of caller Message-ID: <6512ed42.0309190035.303ba9f1@posting.google.com> For debugging/logging purposes, I have a function def Log(msg): print '%s.%s: %s' % (cls, method, msg) I call this function from a class method, and I would like to retrieve the name of the caller method and its class. I already came up with method = sys._getframe(1).f_code.co_name cls = sys._getframe(1).f_locals['self'].__class__ I wonder if there are better ways to retrieve this info. In particular, my implementation assumes that the instance parameter of the method is called 'self', which it usually is, of course. Regards, Koen. From M.Boeren at guidance.nl Wed Sep 17 04:45:05 2003 From: M.Boeren at guidance.nl (Marc Boeren) Date: Wed, 17 Sep 2003 10:45:05 +0200 Subject: replace %(word) in a string Message-ID: <7BE0F4A5D7AED2119B7500A0C94C58AC3D6D5D@DELLSERVER> Hi, > For example with the string: "hello, %(word1) %(word2) !" and the > dictionary: {"word1" : "python", "word2" : "lovers"} the final string > would be: "hello python lovers" You mean base_string % dictionary >>> "hello, %(word1)s %(word2)s !" % {"word1" : "python", "word2" : "lovers"} 'hello, python lovers !' Notice the trailing s in %(word)s! Cheerio, Marc. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Sep 26 14:23:12 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 19:23:12 +0100 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> Message-ID: On Fri, 26 Sep 2003 09:18:18 -0700, David Eppstein wrote: >In article , > "Sean Ross" wrote: > >> How about >> >> from itertools import ireverse >> for i in ireverse(xrange(n)): >> # suite >> >> ireverse(), like imap(), izip(), etc., suggests that the operation is >> iterative, and that no modification of the original sequence will be >> performed. Others have suggested riter() (right iteration), in order to form >> an association with the iter() builtin. As a matter of taste, I prefer >> ireverse(). > >ireverse, like imap(), izip(), etc., suggests that the operation happens >without the memory overhead of copying the whole sequence into a list >before reversing it. Do you have some plan for how to do that e.g. with >simple generators? Or easy to understand explanation for which things >can be ireversed and which can't? How about this - only support ireverse for sequences (identified using len, and perhaps with a check for the keys method in case of mapping types) - not for iterators at all. Add an xrange_backward function to complement xrange rather than trying to modify the result of xrange, and where an object can logically support reverse iteration have a method or property that returns an alternative generator/iterator. At its simplest, something like... class newlist (list) : def ibackward (self) : i = len(self) while i > 0 : i -= 1 yield i ...is no great burden for most built-in sequence types, and would define a protocol for other types to follow where appropriate. It doesn't need a big memory overhead. Rather than define a separate xrange_backwards, it is worth noticing that the built-in 'functions' xrange and enumerate actually seem to be classes. We could add factory methods, set up to effectively give alternate constructors, to allow syntax such as... for i in xrange.backward (10) : ... for i, j in enumerate.backward (seq) : ... -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From fuerte at sci.fi Mon Sep 15 15:39:24 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Mon, 15 Sep 2003 22:39:24 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: References: <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911162016.02027750@telecommunity.com> <3F632226.2010607@earthlink.net> Message-ID: Paul Winkler wrote: > Harri Pesonen wrote in message news:... > >>A.M. Kuchling wrote: >> >>>On Sat, 13 Sep 2003 13:55:59 GMT, >>> Mitch Chapman wrote: >> >>It's not useless, but it is not optimal. That's a fact. If you have a >>multiprocessor machine, you just waste it because Python can't run two >>threads at the same time. So if you want to create a high performance >>web site, then Python is out of the question for the scripting language. > > You're making an awful lot of assumptions there. I'm going to > concentrate on one of them. > > First, you assume that this hypothetical high-performance website > really is CPU-bound. I've never had one of those to deal with, but I > won't argue. > > Second, I'll assume that SMP really is the most cost-effective way > available to scale up your CPU power. Probably depends on the rack > space you have available and maybe somebody already provided an SMP > box for the job. > > Third, I'll assume that cacheing is already being used to the extent > that it's applicable. Every website I've worked on is much more > read-intensive than write-intensive. For these sort of sites, > appropriate cacheing buys you a LOT. > Disk space and RAM are cheap. But maybe you have an app where this > isn't the case and you really can't avoid heavy CPU useage. > > Fourth, you seem to think that threading is the only / best-practice > way to handle a lot of requests. This is the point I'm going to argue > against. > > I'll give one counter-example because it's the one I'm most familiar > with. > In the Zope world, it's common to run a load balancer in front of one > or more ZEO clients (processes) per processor, all connected to a > single ZEO server. This is a matter of very simple configuration. It's > *completely* transparent to the application, which has no idea whether > you're running ZEO or have a direct connection to a dedicated ZODB > database. ZEO has the added benefit of being equally applicable > whether the CPUs are on one box or not. You can't say that about > threading. This approach could certainly be used outside the zope > world. ZEO is not rocket science, it's about 6500 lines of code plus > 3100 lines of unit tests. Note also that ZEO's primary purpose is to > remove one of the single points of failure; handling more requests is > almost a side effect. Free threading won't help you with the > point-of-failure issue. > > I will also mention that it's quite possible to handle a lot of > requests without using threads *at all*, and the resulting code can > look very nice. See twistedmatrix.com. > > Sure, it would be nice if a single python process could take advantage > of SMP, but it's demonstrably false that python is currently "out of > the question" for "high performance" web use. In fact python performs > very well on the web. To say otherwise is nothing but FUD. > > I think the primary problem with the GIL is the bad publicity that > results from faulty assumptions like this. Okay, so it's not out of the question, but it is still not optimal! :-) The point I was trying to make (not in this message but in general) is that it would be simple (trivial but tedious) to create a version of Python that is thread-safe, and the only reason it is not done is because it would break old code. So we are in this GIL world just because of that old code... it's a shame. It's like Visual Basic 6, it can't multitask properly either (but for other reasons). All other modern languages are free-threaded. Before I learned Python I assumed that it is as well. From the response I got from python-dev it seems that the GIL is here to stay forever, unless someone does something to it. I only wish I could spend a few weeks full time with Python C API, and make a free-threading version. "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 100 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." Yuck. But then: "The Python interpreter needs to keep some bookkeeping information separate per thread -- for this it uses a data structure called PyThreadState . This is new in Python 1.5; in earlier versions, such state was stored in global variables, and switching threads could cause problems. In particular, exception handling is now thread safe, when the application uses sys.exc_info() to access the exception last raised in the current thread. There's one global variable left, however: the pointer to the current PyThreadState structure. While most thread packages have a way to store ``per-thread global data,'' Python's internal platform independent thread abstraction doesn't support this yet. Therefore, the current thread state must be manipulated explicitly." Only one global variable left (in fact there is Py_None as well). Why not get rid of it, then?? Harri From bignose-hates-spam at and-benfinney-does-too.id.au Sat Sep 27 21:33:26 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 28 Sep 2003 11:23:26 +0950 Subject: Meta programming question References: Message-ID: On Sat, 27 Sep 2003 19:18:15 -0600, Bruce Dickey wrote: > I've read a number of the meta progamming articles. I have not found > what I am looking for. I want to override assignments to variables > which are in the module namespace (not object members -- no classes > involved). Can this be done? AFAIK, no. If it were possible, it would be very confusing. What is it you're trying to achieve? Perhaps a better alternative can be suggested that doesn't break expected behaviour. -- \ "Cross country skiing is great if you live in a small country." | `\ -- Steven Wright | _o__) | Ben Finney From skip at pobox.com Fri Sep 12 15:46:55 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 12 Sep 2003 14:46:55 -0500 Subject: Trouble with source-code encoding In-Reply-To: <9u63mvoij7b8h2fh6tmj2e9af1akqjl3de@4ax.com> References: <9u63mvoij7b8h2fh6tmj2e9af1akqjl3de@4ax.com> Message-ID: <16226.8879.100998.932787@montanaro.dyndns.org> Fernando> I just upgraded to Python2.3 and I'm getting a weird warning complaining about Fernando> the encoding and asking me to read a pep. OK, I read the Pep and know what Fernando> syntax to specify the enconding: Fernando> # -*- coding: -*- Fernando> However, th epep doesn't list the name of valid encodings. Fernando> What's the name for west european encoding? That would be # -*- coding: latin1 -*- or # -*- coding: iso8859-1 -*- I believe. Skip From rdsteph at earthlink.net Thu Sep 11 22:17:18 2003 From: rdsteph at earthlink.net (Ron Stephens) Date: 11 Sep 2003 19:17:18 -0700 Subject: Python 2.3 and Mac OS X Message-ID: <8e6e8e5d.0309111817.2628819a@posting.google.com> I am most pleased with Python 2.3 on Mac OS X! A lot of stuff just plain works, "right out of the box", so to speak, that I had to struggle with a bit in order to install and get working properly, before. WxPython is notable in that category, and this helps PythonCard installation and use quite nicely. Thanks to Guido and all who contributed to Python 2.3! Also, I am pleased that Python 2.3 will be an integral part of the real-soon-now to be released Mac OS X 10.3, aka Panther. Python will soon be as mature on Mac OS X as it has already been on Linux and Windows. Lastly, I also want to thank the contributors to PyObjC, the "bridge" to allow easier use of the Mac's Aqua gui-interface using Python. Although I am only beginning to play around with PyObjC, it is nice to have it to play around with and it seems to be a very useful tool. From panbru at comcast.net Tue Sep 2 09:11:13 2003 From: panbru at comcast.net (T. Panbru) Date: Tue, 02 Sep 2003 07:11:13 -0600 Subject: Simple question: How to pass a C++ class reference to a callback? In-Reply-To: <17fbc98a.0309020423.11ac7b8d@posting.google.com> References: <17fbc98a.0309020423.11ac7b8d@posting.google.com> Message-ID: Try encapsulating your C++ class reference in a CObject, using: PyObject* PyCObject_FromVoidPtr( void* cobj, void (*destr)(void *)) void* PyCObject_AsVoidPtr( PyObject* self) and so forth, to go back and forth between the C++ and Python realms. Check out the Python docs at: http://www.python.org/doc/2.3/api/cObjects.html Tim > Harri Pesonen wrote: > How do I pass the calling C++ class reference (or anything) to a callback? > My code is: > > static PyObject* > emb_Set(PyObject *self, PyObject *args) > { > char *key, *value; > if(!PyArg_ParseTuple(args, "ss", &key, &value)) > return NULL; > // do something with the C++ class here > // how the get the class instance pointer? > Py_INCREF(Py_None); > return Py_None; > } > > static PyMethodDef EmbMethods[] = { > {"Set", emb_Set, METH_VARARGS, "Sets the given variable."}, > {NULL, NULL, 0, NULL} > }; > > in C++ class: > > Py_Initialize(); > Py_InitModule("test", EmbMethods); > PyRun_SimpleString(script); > Py_Finalize(); > > Harri From tim.hochberg at ieee.org Tue Sep 30 15:21:35 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Tue, 30 Sep 2003 12:21:35 -0700 Subject: Prime number module In-Reply-To: References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> Message-ID: <3Jkeb.9316$gi2.2518@fed1read01> Alex Martelli wrote: > Tim Hochberg wrote: > ... > >>I believe you could implement a hybrid scheme that would be quite fast >>and still maintain nearly the same level of compression that you >>describe above. In addition to the above compressed data, also store, >>uncompressed, every Nth prime. A binary search will get you within N >>primes of your answer, to find the exact value, recreate those N-primes. >>For a N of, for instance, 64 the level of compression would be minimally >>affected but should make finding the number of primes less than a given >>number number much faster than the basic compressed scheme. > > > Still thinking of gmpy's primitives, I came up with a variant of this...: > [Nice compact version using gmpy snipped] Just to keep my hand in, I'm attaching a version based on the idea above which is in turn based on Emile's and Lulu's ideas for compression. This produces data files that total just over 6 GB for all primes up to 1E8. The initial run is quite slow, but after that it can determine the nth prime, or the number of primes below some number in about 0.5 ms on my box. > The first run, building the file primes.dat (just 23048 bytes), took > almost 7 minutes elapsed time on my machine (250 CPU seconds). But > any successive run is extremely fast: > > [alex at lancelot perex]$ time python -O prio.py > 5762 primes stored (1 every 1000), highest is 99991609 > 55555th prime is 686671 > Up to 555555, there are 45741 primes > 0.06user 0.00system 0:00.14elapsed 41%CPU (0avgtext+0avgdata 0maxresident)k > 0inputs+0outputs (494major+297minor)pagefaults 0swaps > [alex at lancelot perex]$ > > I've coded this rapidly and sloppily, so I wouldn't be surprised if > there were off-by-one errors here and there (needs to be checked against > some other, independent way to generate/check primes!), but I think the > fundamental ideas are sound. Well one of us is off by one as I get 45740 primes below 55555. However, I get 686671 as the 55555th prime, so we agree there. I would not be at all suprised if it is mine that is off by one. -tim > > Alex > -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: packedprimes.py URL: From dario at fga-software.com Fri Sep 5 05:22:27 2003 From: dario at fga-software.com (ProgDario) Date: 5 Sep 2003 02:22:27 -0700 Subject: Executing a Jython function from Java Message-ID: <67a857cc.0309050122.644ea7ee@posting.google.com> Hello, in the site I found a lot of complicated examples, but I can't find the simple one I'm looking for. The problem is: I have 1 jython file (script1.py) with a function named 'calculate', and a java file (run.java). I'd like to call the jython function from the java class recursively. <<====<< I think it can be possible to get a PyFunction object that rapresents the function, and then call the function from the already evaluated object, so I don't need to re-evaluate it every loop. My code is something like this: PythonInterpreter interp = new PythonInterpreter(); interp.execfile('script1.py'); for (int i = 0; i < 1000; i++) { interp.eval("calculate(8)"); } Thanks in advance, Dario From NO-MAIL at hotmail.com Tue Sep 16 16:01:36 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 20:01:36 GMT Subject: why pass statement? References: Message-ID: A good idea! Thanks! "John Roth" wrote in message news:vmeq2go7e7fq62 at news.supernews.com... > > You don't actally need Pass. A docstring is sufficient: > > class C: > "this is a class" > > while True: > "loop de loop de loop" > > John Roth From lupan at zamek.gda.pl Fri Sep 5 10:29:56 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Fri, 05 Sep 2003 16:29:56 +0200 Subject: Why the 'self' argument? References: Message-ID: <87ptifmhp7.fsf@psi.lupan.zamek.gda.pl> Hi, the answer is in python FAQ: http://python.org/doc/faq/general.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls -- =*= Lukasz Pankowski =*= From roberto at dealmeida.net Tue Sep 23 10:22:08 2003 From: roberto at dealmeida.net (Roberto A. F. De Almeida) Date: 23 Sep 2003 07:22:08 -0700 Subject: Playing with dictionaries References: <10c662fe.0309220907.a84bea5@posting.google.com> Message-ID: <10c662fe.0309230622.72798957@posting.google.com> Hi, guys. Thanks for the all the answers and the valuable insights. I mixed them all and got what I want. :) Roberto From DSmorey at UnConundrum.com Mon Sep 1 01:16:13 2003 From: DSmorey at UnConundrum.com (Daniel Smorey) Date: Mon, 1 Sep 2003 01:16:13 -0400 Subject: Python Documentation? Message-ID: Thanks for the reply, I'll have to try pydoc. It definitely takes some getting used to. Perl is like this to a degree also, especially since so many people have re-invented the wheel when it comes to modules. But, it's still a lot more straight forward than searching for python documentation. lol Thanks again... Dan S. > -----Original Message----- > From: Nick Welch [mailto:mack at incise.org] > Sent: Monday, September 01, 2003 1:09 AM > To: Daniel R. Smorey Jr. > Cc: python-list at python.org > Subject: Re: Python Documentation? > > > pydoc is pretty nice, try "pydoc str", and then use / to search for > "split". > > As far as searching the online docs, it takes a little adaptation. To > look for str.split, I'd do a google "site:www.python.org built-in > types", and then look for str, and then look at split. > > And doing just that, and clicking once or twice, brought me to: > > http://www.python.org/doc/current/lib/string-methods.html > > Although I agree, it would be cool if the online > documentation supported > such direct search methods as e.g. www.php.net/split. > > -- > Nick Welch aka mackstann | mack @ incise.org | http://incise.org > What is the difference between a Turing machine and the modern > computer? It's the same as that between Hillary's ascent of Everest > and the establishment of a Hilton on its peak. > From Juha.Autero at iki.fi Tue Sep 9 14:46:55 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Tue, 09 Sep 2003 21:46:55 +0300 Subject: method post References: Message-ID: <87llsx7qao.fsf@jautero.no-ip.org> "franck" writes: > Hi, > > how to do a post with python? import nntplib server = NNTP(nntpserver) server.post(newsarticle) server.quit() Note that newsarticle should be a file object. Sorry, couldn't resist. ;) -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From skip at pobox.com Mon Sep 8 14:39:07 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 8 Sep 2003 13:39:07 -0500 Subject: Eureka! (Re: Comments on Python Redesign) In-Reply-To: References: Message-ID: <16220.52427.975719.335010@montanaro.dyndns.org> >> http://tinyurl.com/mlcv aahz> Many people, me included, won't follow tinyurl links; Why? Skip From Juha.Autero at iki.fi Fri Sep 5 15:07:08 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Fri, 05 Sep 2003 22:07:08 +0300 Subject: OT: best book in years References: Message-ID: <87iso76omb.fsf@jautero.no-ip.org> Patrick Useldinger writes: > I would like to know what *you* consider to be the best book you > have read in the last few years, about Python or IT in general. G?del, Escher, Bach: an Eternal Golden Braid. It may not be the best book I read and not very useful, but I'd recomend reading it anyway. -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From syed_saqib_ali at yahoo.com Fri Sep 12 06:16:32 2003 From: syed_saqib_ali at yahoo.com (Saqib Ali) Date: 12 Sep 2003 03:16:32 -0700 Subject: Test message. Please ignore Message-ID: Testing. From stephan.diehl at gmx.net Tue Sep 9 08:38:32 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Tue, 09 Sep 2003 14:38:32 +0200 Subject: Slight metaclass confusion References: Message-ID: Ben Young wrote: > [snip] >> >> The problem is perhaps the terminology (Unfortunatelly,I don't know a >> better one). >> >> The metaclass initializes a class. Just imagine, that the textual class >> definition comes fresh from the parser, so you have information about >> possible base classes, methods, attributes. These information can be >> changed within the metaclass __new__ method. >> Think of the metaclass as a factory that turns a class definition into a >> class instance. >> Other than that, they don't interact. >> >> What a metaclass can do, is to change that information, before the class >> is made into a class object. >> >> Basicly, the metaclass concept is orthogonal to the inheritence concept >> of OOP. >> > > So the way it is implemented in python a class is NOT an instance of a > metaclass the same way that an instance is an instance of a class. This is > slightly confusing as this is not the way it is described in all the > places I can find that talk about python metaclasses. For all I know, a class is the instance of its metaclass, but this doesn't mean that an object a of class A can access methods of A' (the metaclass of A). (Please note that this is probably totally wrong. Other people might shed light on this more theoretical question) > > In this case, what is the point of using a class when a simple function > can do the job? Well, actually, there is probably nothing you can do with metaclasses that you couldn't do in other ways. The point (if you are not a language lawyer) is that the resulting code is (at least in some cases) better readable when using metaclasses. The Python cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python) has a couple of recipies about metaclasses. Please have a look there if you are interested in practical things you can do with metaclasses. > >> Hope that helps >> >> Stephan >> >> > > Thanks for the reply > > Ben > --- From ceiesa at excite.com Sat Sep 27 14:59:02 2003 From: ceiesa at excite.com (Bruce Dickey) Date: Sat, 27 Sep 2003 12:59:02 -0600 Subject: Any tool to translate PHP to Python? Message-ID: Hi, I have some PHP scripts I'm moving from my web server to the local PC. They just do file manipulation. Anybody know of a tool for translating PHP to Python? A partial translation would be hwlpful. Also, any tips or pritfalls to look out for? I'm mostly a Python / C / C++ programmer and do not have much experience with PHP. Thanks, Bruce From max at alcyone.com Sat Sep 20 04:45:26 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 20 Sep 2003 01:45:26 -0700 Subject: ANN: EmPy 3.1.1 -- A powerful and robust templating system for Python Message-ID: <3F6C13A6.50F605B4@alcyone.com> Summary A powerful and robust templating system for Python. Overview EmPy is a system for embedding Python expressions and statements in template text; it takes an EmPy source file, processes it, and produces output. This is accomplished via expansions, which are special signals to the EmPy system and are set off by a special prefix (by default the at sign, '@'). EmPy can expand arbitrary Python expressions and statements in this way, as well as a variety of special forms. Textual data not explicitly delimited in this way is sent unaffected to the output, allowing Python to be used in effect as a markup language. Also supported are callbacks via hooks, recording and playback via diversions, and dynamic, chainable filters. The system is highly configurable via command line options and embedded commands. Expressions are embedded in text with the '@(...)' notation; variations include conditional expressions with '@(...?...!...)' and the ability to handle thrown exceptions with '@(...$...)'. As a shortcut, simple variables and expressions can be abbreviated as '@variable', '@object.attribute', '@function(arguments)', '@sequence[index]', and combinations. Full-fledged statements are embedded with '@{...}'. Control flow in terms of conditional or repeated expansion is available with '@[...]'. A '@' followed by a whitespace character (including a newline) expands to nothing, allowing string concatenations and line continuations. Comments are indicated with '@#' and consume the rest of the line, up to and including the trailing newline. '@%' indicate "significators," which are special forms of variable assignment intended to specify per-file identification information in a format which is easy to parse externally. Context name and line number changes can be done with '@?' and '@!' respectively. Escape sequences analogous to those in C can be specified with '@\...', and finally a '@@' sequence expands to a single literal at sign. Getting the software The current version of empy is 3.1.1. The latest version of the software is available in a tarball here: http://www.alcyone.com/software/empy/empy-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/software/empy/. Requirements EmPy should work with any version of Python from 1.5.2 onward. It has been tested with all major versions of CPython from 1.5 up, and Jython from 2.0 up (using Java runtimes 1.3 and 1.4). The included test script is intended to run on Unix-like systems with a Bourne shell. License This code is released under the GPL. ... Release history (since 3.1) - 3.1.1; 2003 Sep 20. Added literal '@"..."' markup; added --pause-at-end command line option; fixed improper globals collision error via the 'sys.stdout' proxy. From skip at pobox.com Mon Sep 8 12:28:13 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 8 Sep 2003 11:28:13 -0500 Subject: Ternary operator In-Reply-To: <4qznp862.fsf@yahoo.co.uk> References: <3F5B6404.BD1A9709@engcorp.com> <4qznp862.fsf@yahoo.co.uk> Message-ID: <16220.44573.537315.750473@montanaro.dyndns.org> Paul> Maybe it's a shame that Guido's original PEP wasn't preserved Paul> unaltered. What's there now doesn't capture the flavour of the Paul> original. You can pick any version you like out of CVS, even if you don't have it installed on your system. For the PEPs, start here: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/nondist/peps/ Skip From Mike at DeleteThis.Geary.com Thu Sep 25 21:59:54 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 25 Sep 2003 18:59:54 -0700 Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: Stephen Ferg wrote: > When did Windows start accepting the forward slash as a path separator > character? > > At one time, it was accepted as a truism that Windows (like MS-DOS) > was different from Unix because Windows used the backslash as the path > separator character, whereas Unix used the forward slash. > > But now, among a small group of cognoscenti, it is a truism that this > is a myth, and that Windows will allow you to use either the forward > or the backward slash as a pathname separator. > > I hypothesize that originally Windows accepted only the backslash, and > then at some time it changed to accept the forward slash as well. > Does anyone know when that change occurred? Was it with the > introduction of support for long filenames in NT and Win95? Hi Steve, Every version of Windows has accepted "/" as a path separator. So has every version of MS-DOS beginning with DOS 2.0 (the first version that had subdirectories). It's only been in command lines that "/" was not allowed, because it had already been used as a switch delimiter in MS-DOS 1.0. -Mike From fawcett at teksavvy.com Mon Sep 8 19:47:28 2003 From: fawcett at teksavvy.com (Graham Fawcett) Date: Mon, 08 Sep 2003 19:47:28 -0400 Subject: os.listdir In-Reply-To: <2ce42702.0309081441.5c73a772@posting.google.com> References: <2ce42702.0309081441.5c73a772@posting.google.com> Message-ID: <3F5D1510.8040205@teksavvy.com> Hari wrote: >Hi, > >I have question regarding os.listdir() > > >I wanted to know if this is a reliable way to check for files added to >a directory?? > >files = os.lisdir(path) > >currentlen = len(files) > >// directory modified > >files = os.listdor(path) > >newlen = len(files) > >then the files in the range (currentlen -1) to (newlen -1) are all the >files added to the directory. > >What I wanted to know was, is it guaranteed that between 2 calls >os.listdir any files added to the directory are appended and the >earlier order is maintained? > > Unless the documentation for os.listdir specifies such behaviour explicitly, you should assume the answer is /no/. There are many Pythons, running on many platforms; don't assume that they all share identical unspecified behaviour. There's no need for such sequence guarantees, though. It's probably not the most efficient but here's a way to do it: import os import time somedir = '/tmp' snapshot1 = os.listdir(somedir) time.sleep(...) snapshot2 = os.listdir(somedir) newfiles = [f for f in snapshot2 if not f in snapshot1] Pretty efficient, really: that's an O(n) comparison if I remember my Python internals correctly. Which I don't, so don't trust my word for it. ;-) >thanks, > >Hari > > -- Graham From soundinmotiondj at yahoo.com Tue Sep 2 12:14:41 2003 From: soundinmotiondj at yahoo.com (Stan Graves) Date: 2 Sep 2003 09:14:41 -0700 Subject: Advice to a Junior in High School? References: <3d6c6fc3.0308261246.32db39d5@posting.google.com> Message-ID: <3d6c6fc3.0309020814.544db215@posting.google.com> Jeremy Bowers wrote in message news:... > On Tue, 26 Aug 2003 13:46:27 -0700, Stan Graves wrote: > > Study literature - I have yet to see a single computer scientist who can > > manipulate symbols as well as Shakespeare. > > class Rose: > "A Rose is a Rose is a Rose.""" > def sweetness(self): > return "very" > > rose = Rose() > otherName = rose > assert rose.sweetness() == otherName.sweetness() > > Would you *notice* if a computer scientist matched Shakespeare? Yes. I have had the mis-fortune of being a maintenance programmer for far too much of my life. I have read reams of documentation, and hundreds of thousands of lines of code. I have attempted to make sense of code written to do one thing, but extended and tortured into doing another. This may not be the computer scientists fault - but the fact remains that the resulting system of code has little, if any, coherence across itself, let alone a deliberate connection from it's elements to anything that resembles the real world problem that the code was written to give greater insight. Then again, if an army of editors attempted to re-write Shakespeare, I doubt seriously if anythign worth reading would have survived. > How can you compare the two at all? I can compare the two because they relate to the same larger idea. Literature, on its surface may simply be pretty prose. But literature is also meant to provide us with some greater insight into the human condition. Literature can be a stand-in for actual experience. When you read the report of Lewis and Clarke to President Jefferson, you can get a sense of what their journey was like. That is a journey that can never be redone - the face of the land has changed since that time...yet the words of the report provide a greater sense of understanding about the men, the journey, the land, and the times. In general, code is written to solve a greater problem than the creation of that code. As such, code, or its results, should provide a greater understanding into a non-code related problem. As such, I can say that no computer program has provided me with a greater sense of understanding into the problem it was meant to solve, than Shakespeare has provided me with an understand of the human conditions that he wrote about. Even with the precise language of mathematics, code is generally a poor stand in for actual understanding of a problem. > Statements like that sound all profound but are really the exact opposite; > meaningless. I stand by my original statement. Perhaps with the clarification that I have provided above, you may find some greater meaning in what I originally said. If not, I hope we can simply agree to disagree. --Stan Graves From newsgroups at jhrothjr.com Tue Sep 30 13:38:09 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Sep 2003 13:38:09 -0400 Subject: Inconsistent behavior of descriptors References: Message-ID: "Denis S. Otkidach" wrote in message news:mailman.1064938610.30070.python-list at python.org... > > I've noticed that the order of attribute lookup is inconsistent > when descriptor is used. property instance takes precedence of > instance attributes: > > >>> class A(object): > ... def _get_attr(self): > ... return self._attr > ... attr = property(_get_attr) > ... > >>> a=A() > >>> a.__dict__ > {} > >>> a.__dict__['attr']=1 > >>> a.__dict__ > {'attr': 1} > >>> a.attr > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in _get_attr > AttributeError: 'A' object has no attribute '_attr' > > But it doesn't when I use custom class of descriptor: > > >>> class descr(object): > ... def __get__(self, inst, cls): > ... return inst._attr > ... > >>> class B(object): > ... attr = descr() > ... > >>> b=B() > >>> b.__dict__ > {} > >>> b.__dict__['attr']=1 > >>> b.__dict__ > {'attr': 1} > >>> b.attr > 1 > > Subclasses of property behave like property itself: > > >>> class descr2(property): > ... def __get__(self, inst, cls): > ... return inst._attr > ... > >>> class C(object): > ... attr = descr2() > ... > >>> c=C() > >>> c.__dict__ > {} > >>> c.__dict__['attr']=1 > >>> c.__dict__ > {'attr': 1} > >>> c.attr > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in __get__ > AttributeError: 'C' object has no attribute '_attr' > > Is it an undocumented feature or I have to submit a bug report? I'm not entirely sure what you're describing, however, I notice that your descriptor object has a __get__ method, but no __set__ or __del__ methods. The lookup chain is quite different for descriptors with only __get__ methods than it is for descriptors for all three. In particular, it's intended that instance attributes should be ignored if there is a data descriptor (that is, a descriptor with both__get__ and __set__ methods.) I'm not sure if this applies to your problem. John Roth > > -- > Denis S. Otkidach > http://www.python.ru/ [ru] > > From mwilson at sarcastic-horse.com Sat Sep 20 13:59:31 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Sat, 20 Sep 2003 13:59:31 -0400 Subject: Insert into text field? In-Reply-To: <3394585.1064074283@dbforums.com> References: <3394585.1064074283@dbforums.com> Message-ID: <20030920135931.58707cd3.mwilson@sarcastic-horse.com> On Sat, 20 Sep 2003 12:11:23 -0400 Baltor wrote: > > How do I enter weapondescription with a space before it at the end of > line 3. I tried this, but it is not working: > > self.text.insert(3.0, END, " ", weapondescription) If you're trying to pass a string that has the value ' weapondescription' you should put quotes around the string, or make weapondescription a variable that has the value ' weapondescription'. Some more background about the project you're working on might help. From fawcett at teksavvy.com Mon Sep 8 14:57:15 2003 From: fawcett at teksavvy.com (Graham Fawcett) Date: Mon, 08 Sep 2003 14:57:15 -0400 Subject: Eureka! (Re: Comments on Python Redesign) In-Reply-To: References: Message-ID: <3F5CD10B.2020709@teksavvy.com> Aahz wrote: >In article , >Graham Fawcett wrote: > > >>Rather than throw stones, I have created a *brand new design* design for >>Python.org. I am certain that will satisfy both the technical users and >>the suit-wearing investigators. It borrows the time-honoured stylings of >>the old Python site, and blends them with some upscale business moxy. >> >>Take a look: >> >>http://tinyurl.com/mlcv >> >> > >Many people, me included, won't follow tinyurl links; please provide a >standard URL, too. > > Okay. But please understand that my design is a *joke*... should have added a in there somewhere. Do *not* send comments to anyone, esp. the marketing list! I've made my apologies there already. http://fawcett.medialab.uwindsor.ca/python_org_redesign/ Thanks for the heads-up re: tinyurl. I realize that some unfriendly folk may enjoy sending people to goatse or some similarly unsavoury site; I guess I haven't been burned and have enjoyed the brevity of those URLs. it-all-seemed-funnier-at-two-in-the-morning'ly yours, -- Graham From skip at pobox.com Wed Sep 3 17:00:55 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Sep 2003 16:00:55 -0500 Subject: quick and smart way for parsing a CSV file? In-Reply-To: <731fc603.0309031242.4e5493ce@posting.google.com> References: <731fc603.0309031242.4e5493ce@posting.google.com> Message-ID: <16214.22151.788993.342181@montanaro.dyndns.org> soundwave56> I have a CSV file from excel that looks like this soundwave56> (simplified): soundwave56> name,description,type1,type2,name,filename soundwave56> test1,this is a test,0.000,1.000,, soundwave56> test2,another test,1.000,0.000,newname,filename soundwave56> test3,this is a test,0.000,1.000,, soundwave56> test4,this is a test,0.000,1.000,, soundwave56> test5,this is a test,0.000,1.000,, soundwave56> test6,this is a test,0.000,1.000,, Take a look at the csv module delivered with Python 2.3. Skip From tzot at sil-tec.gr Mon Sep 29 21:11:02 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 04:11:02 +0300 Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: On 27 Sep 2003 17:20:44 GMT, rumours say that bokr at oz.net (Bengt Richter) might have written: >Do you mean windows exploder will not even delete it with right-click, delete? >Or doesn't it show up at all? (how do you know it exists? dos dir?) I have 110MB (or so they seem) worth of files (2893 files) in my W2k SP4 laptop's c:\recycler\nprotect folder that can't be accessed or deleted. Norton Protect is long uninstalled, but operating on the files gives (example): C:\RECYCLER\NPROTECT\00041753. The system cannot find the file specified. The disk shows as healthy in Disk Manager, and scandisk or what's-its-name runs successfully. Go figure. Ils sont fous ces Redmontains! (index finger running wild circles) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From newsgroups at jhrothjr.com Mon Sep 29 18:18:40 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 29 Sep 2003 18:18:40 -0400 Subject: isNumber? check References: Message-ID: "Rob Hunter" wrote in message news:mailman.1064867377.30354.python-list at python.org... > > On Monday, September 29, 2003, at 10:20 AM, Gerrit Holl wrote: > > > Rob Hunter wrote: > >> How do I check if a value is a number in Python? > >> > >> One way is (x == type(1)) and (x == type(1.2)) and (x == > >> type(2387482734274)) and ... > >> > >> but this seems kludgy. Any better way? > > > > Why do you want to do so? > > > I am writing an interpreter, and my parser has to decide if an > expression is a number or not. You can always use eval() and see what it returns. John Roth From mertz at gnosis.cx Sun Sep 7 00:10:16 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sun, 07 Sep 2003 00:10:16 -0400 Subject: OT: best book in years References: <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <3F5868BA.85F506B4@engcorp.com> <87oexyls54.fsf@pobox.com> Message-ID: Martin Maney wrote previously: |Thinking of and fetching those titles made me think of Dennett's |_Consciousness Explained_ and _Darwin's Dangerous Idea_ Yuck! Dennett puts the "naive" back in "naive reductionism." He was a little bit clever back in the 1980s when he was writing cute, and slightly clever, analytic philosophy essays. But then he thinks he discovered Darwin (who was himself NEVER so naive or poorly nuanced as Dennet), and wrote the subsequent drivel.... plus take a look for his advocacy of the word "bright" as a weird neologistic synonym for "secular"... well, some of you may have seen my post joking about the word "disingenuous." You just cannot believe how awful Dennett's notion is to you see it yourself. That said... if Darwin and biology are interesting to you, I can highly recommend reading some Steven Jay Gould. Anything, really, but the more technical stuff includes _Ontogeny and Phylogeny_ and his masterpiece _The Structure of Evolutionary Theory_. Slightly ligher than those, but a bit more than his essay collections, try _Wonderful Life_, which is quite a nice reflection on evolution and "deep time." Now if you want really wild, try the fairly slim _Acquiring Genomes_ by Lynn Margulis (who brought you the procaryotic symbiosis of mitocondrial organelles) and Dorion Sagan (her son, my acquaintance). You need a slight grain of salt for this book, but between a few flights of fancy is some remarkably compelling stuff that almost no one else is doing. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From oystein at gnubg.org Sun Sep 28 11:34:42 2003 From: oystein at gnubg.org (=?ISO-8859-1?Q?=D8ystein_Johansen?=) Date: Sun, 28 Sep 2003 17:34:42 +0200 Subject: fetching a cvs repository directory from a cgi script Message-ID: Hi, This may be a FAQ, but I can't find the answer. I want a cgi script to fetch a directory from out projects cvs repositoy. (the /doc/ directory) How can I fetch the files in this directory when cvs is not installed on the server? -?ystein From geoff at gerrietts.net Tue Sep 2 18:27:57 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Tue, 2 Sep 2003 15:27:57 -0700 Subject: Open Source leader? (was Re: Celebrity advice) In-Reply-To: <87y8x6x2op.fsf@pobox.com> References: <23891c90.0308280317.ac68b38@posting.google.com> <87y8x6x2op.fsf@pobox.com> Message-ID: <20030902222756.GF30625@thoth.homegain.com> Quoting John J. Lee (jjl at pobox.com): > aahz at pythoncraft.com (Aahz) writes: > > > In article , > [...] > > OTOH, Perens is also (like me ;-) a self-described asshole. When I saw > > him at the Waterside Conference earlier this year, he basically claimed > > that only assholes could make significant progress in the Open Source > > community. > [...] > > Why? I think the sentiment is just a variant on the "politicians always lie" theme. Open source is socio-political, and so it's the charismatics that succeed. "Asshole" is one manifestation of a strong personality. --G. -- Geoff Gerrietts http://www.gerrietts.net/ "Politics, as a practice, whatever its professions, has always been the systematic organization of hatreds." --Henry Adams From jjl at pobox.com Fri Sep 5 19:51:36 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Sep 2003 00:51:36 +0100 Subject: OT: best book in years References: Message-ID: <87k78mlrp3.fsf@pobox.com> "Michael Peuser" writes: > "Juha Autero" > > > > G?del, Escher, Bach: an Eternal Golden Braid. It may not be the best > > book I read and not very useful, but I'd recomend reading it anyway. > > > > I made the same recommendation some minutes ago, but without your > reservation. In fact I might even come to the conclusion it *is* the best > book I have read ;-) > > Why do you think it is not very useful? What do you think of Shakespeare by > the way? [not directed at me, but I'll answer anyway...] Well, it dazzles you with all sorts of fascinating stuff, and succeeds at being something wonderful purely in its own right, but it fails to actually solve any problems. Of course, nobody can really tell him off for that, since his subject matter revolves around what appears to be the biggest unsolved mystery in human knowledge. John From jwdillworth at yahoo.com Wed Sep 3 09:10:39 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Wed, 3 Sep 2003 06:10:39 -0700 (PDT) Subject: Fwd: Re: Writing solid code book Message-ID: <20030903131039.97598.qmail@web41108.mail.yahoo.com> --- "John J. Lee" wrote: > post400 at prontomail.com (post400) writes: > > > there is another famous book 'Writing solid code' but does it apply to > > Python ? Or it's usable only by Microsoft C programmers ? The author > > seems to be an ex-Microsoft guy ! > > Never read it, but from the blurb about and extract from it in my copy > of Code Complete it certainly sounds pretty focused on C. > > The Python Cookbook is the first book I'd have on my list if I were > learning Python now (O'Reilly, eds. Martelli & Ascher). > > > John > -- > http://mail.python.org/mailman/listinfo/python-list I agree! Python cookbook is a must-have for any [aspiring] Python programmer. Writing solid code is more about avoiding errors though, I don't see that covered in the cookbook. Unless I missed some recipes... Perhaps something like Kent Beck's _Test Driven Development_ would be more easily applicable to Python than Writing Solid code. (self.disclaimer = "Have not read it personally") From jarrodhroberson at yahoo.com Mon Sep 8 00:24:32 2003 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 7 Sep 2003 21:24:32 -0700 Subject: Comments on Python Redesign References: Message-ID: "Tim Parkin" wrote in message news:... > 2) The site is designed to reflect the expectations of commercial > customers who are used to the likes of peoplesoft and atg, etc. all of those sites are completely useless brochure ware fluff. A programming language web site does not NEED any graphics whatsoever! It needs clean plain readable text that is logically and rationally laid out with obvious textual links, also it needs to be MULTI-LINGUAL . . . which pictures and icons are NOT multi-lingual by nature. > also > it's designed to project an image to set Python alongside existing > enterprise programming langagues (apologies for using the e word) try picking a web site that is useable over the graphical corporate fluff for the home page. then put a big obvious link that says, NON-TECHNICAL PEOPLE THAT WANT PYTHIN INFORMATION CLICK THIS! or some such thing. Making the default home page corporate contentless brochure-ware fluff is defiantly the quickest way to drive away the technical people, without whom Python would not be as popular. A completely separate brochure-ware Python for non-technical managers site would be usefull, but making the entire site and the main page have that function would be counter productive. here are good useable technical sites http://www.cetus-links.org/ http://sourceforge.net/ http://firebird.sourceforge.net/ http://www.mozilla.org/ there are many others, but they all have ONE thing in common, CLEAN UNCLUTTERED CONSISTENT layout of information, and very very very very few graphics and very very very little fluff. Anything that does NOT directly convey useful infomration is FLUFF. > 3) it's an image. Images don't stretch. If I make it any bigger > it would not fit in 800 wide browsers. A lot of designers make a choice > between fixed width and fluid. I would probably choose fluid for all > but the home page however I'm looking at fluid techniques for that too. then post the HTML that generated the image, learn from your lesson, don't post screen shots in the future. > Tim From opstad at batnet.com Thu Sep 18 18:53:17 2003 From: opstad at batnet.com (David Opstad) Date: Thu, 18 Sep 2003 15:53:17 -0700 Subject: Unicode 4.0 updates to unicodedata? Message-ID: Hi, all! I'm relatively new to Python, but have definitely fallen in love with it. It reminds me of Mesa (old Xerox development language) and LISP a bit. Anyway, on to the question. Now that Unicode 4.0 has been released (just got my copy today), any guesses on how long before the unicodedata module will be updated to include all the new names? How do things like that work, anyway; is there somebody whose task it is to update that, or are they awaiting volunteers to help out? And once the module is updated, is it generally usable on earlier Python releases (I'm running the 2.2 that came with the OS X developer package for Jaguar)? Cheers! Dave Opstad From mcfletch at rogers.com Mon Sep 29 15:39:12 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 29 Sep 2003 15:39:12 -0400 Subject: A startup puzzle In-Reply-To: References: Message-ID: <3F788A60.6070402@rogers.com> Edward K. Ream wrote: >I've just about convinced myself there is no good, clean solution to the >following puzzle. I wonder if you agree. > >1. My app has a module called leoGlobals that contains often-used global >functions. All of Leo's source files start with: > >from leoGlobals import * > >I don't want to discuss whether this is good style: it is simple and it >works well for me :-) > > Okay, we'll take that as a given then. >2. All code accesses the singleton application object using the app() >method in leoGlobals. > > Sure, implements late-binding via indirection. >3. To make the code cleaner looking, I would really like the code to be >able to access an app global instead of the app() function. This has >nothing to do with speed: it's simply that there are lots of references to >app() in the code, and there is soon going to be a lot more references to >app.gui.x() and app.gui.y() etc. > >As a workaround, many methods and functions assign a = app(), but I would >like to avoid this step. > > This can be done by creating a built-in variable e.g. APPLICATION, which is an application-wide variable, like so: def __install( self ): """Install self into the builtin module""" __builtin__.APPLICATION = self note that this *doesn't* help if there really are hidden dependencies in your modules on having the APPLICATION object defined, but given your description of the architecture, that doesn't appear to be the case. >4. Alas, it does not seem possible to initialize an app global in >leoGlobals. The reason is simple: > >from leoGlobals import * > >caches the value of app at the time the import is done. But the startup >code that creates the app "global" (really an attribute of the leoGlobals >module) must do _other_ imports. > >For example, doing the following at the top of leoGlobals doesn't work: > >import leoApp >app = leoApp.leoApp() # construct the app instance. > >Indeed, the leoApp module will be imported before the assignment of app. >Moreover, the leoApp module does other imports, and all the app variables in >those modules will be uninitialized. > >It would be horrible style to place detailed constraints on the order in >which modules get imported, and I'm not sure even that would work. > > Such constraints will exist. Any module which relies on the existence of an initialised APPLICATION variable must be imported after the creation of that variable. You construct the app so that the APPLICATION is created ASAP and that becomes a minimal restriction, since your code is working, it's already passed that level of restriction :) . The alternatives to such restrictions are pretty grotty; defered execution of suites of code that would likely require Stackless Python and a decent masters thesis working out the calculus of dependency resolution (what with needing to defer or speculatively execute each path in the code dependant on the app object's operation). Luckily that's all just academic for your project :) . >Any ideas for a clean solution? Thanks. > > Cleanliness is in the eye of the beholder. I don't really like the APPLICATION-object "pattern", but it is very convenient in many simple cases. Just about everything else I've seen either requires something exotic (e.g. proxy objects implementing the late-binding indirection by pretending to be the app object (raising errors if anything attempts to use the object before it's bound)), or the solution you started with, i.e. using function's built-in late-binding to implement it. HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From adalke at mindspring.com Tue Sep 23 00:44:35 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 23 Sep 2003 04:44:35 GMT Subject: Passing data out of a Sax parser References: <878yohajyc.fsf@pobox.com> <87vfrlt7iy.fsf@pobox.com> Message-ID: John J. Lee: > It was just a nit: you said (indirectly) that integers are mutable: > > > | Either that or have startDocument create the mutable object, as > [...] > | self.count = 0 Indeed I did. In my head I was thinking "the things which change when events come in" and that got converted to "mutable" when I wrote it out. Andrew dalke at dalkescientific.com From bokr at oz.net Mon Sep 8 19:27:46 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Sep 2003 23:27:46 GMT Subject: minidom sample code References: <59e5b87.0309081251.32b31261@posting.google.com> Message-ID: On 8 Sep 2003 13:51:06 -0700, mirandacascade at yahoo.com (Miranda Evans) wrote: >Seeking sample python script that makes use of of xml.dom.minidom. >Specifically, would like to see code where xml.dom.minidom is used to >create an output file the contents of which is an XML document. > >Ideally, the output file would a simple XML document such as the one >below. > > >TrivialContents > >Workstation O/S is Win2K; version of Python is 2.2. > >Can anyone point me to a documentation/link/whatever that provides >such sample code? Thank you. Did you look at the xml.dom.minidom docs at http://www.python.org/doc/current/lib/module-xml.dom.minidom.html Taken from the first page verbatim: >>> from xml.dom.minidom import getDOMImplementation >>> impl = getDOMImplementation() >>> newdoc = impl.createDocument(None, "some_tag", None) >>> top_element = newdoc.documentElement >>> text = newdoc.createTextNode('Some textual content.') >>> top_element.appendChild(text) Using the methods described on the second page: >>> newdoc.toxml() '\nSome textual content.' or: >>> newdoc.toprettyxml() '\n\n\tSome textual content.\n\n' and showing what that looks like printed: >>> print newdoc.toprettyxml() Some textual content. I'll leave it to you to change the spelling to match your example ;-) Regards, Bengt Richter From member37516 at dbforums.com Sat Sep 20 12:11:23 2003 From: member37516 at dbforums.com (Baltor) Date: Sat, 20 Sep 2003 12:11:23 -0400 Subject: Insert into text field? Message-ID: <3394585.1064074283@dbforums.com> How do I enter weapondescription with a space before it at the end of line 3. I tried this, but it is not working: self.text.insert(3.0, END, " ", weapondescription) Anyone? Thanks. -- Posted via http://dbforums.com From jason at tishler.net Sat Sep 6 19:14:39 2003 From: jason at tishler.net (Jason Tishler) Date: Sat, 6 Sep 2003 19:14:39 -0400 Subject: cygwin python with Tkinter and pexpect module In-Reply-To: References: Message-ID: <20030906231439.GP1852@tishler.net> J?rg, On Sat, Sep 06, 2003 at 07:16:39PM +0200, J?rg Maier wrote: > it works in cygwin-python from command-line, but invoked in an > Tkinter-Program i got the strange Exception: > E:\cygwin\bin\python2.3.exe: *** unable to remap E:\cygwin\bin\tk84.dll to > same address as parent(0x710000) != 0xC20000 28 > > [snip] > > Is this a bug in cygwin tcltk? No, you have been bitten by the Cygwin fork() issue: http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=unable+remap+same+address+parent&btnG=Google+Search The solution is to install the rebase package via Cygwin's setup.exe and rebase your system. Please read the README: http://www.tishler.net/jason/software/rebase/rebase-2.2.README Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From indigomoon at bonbonBLINDERS.net Tue Sep 16 14:44:21 2003 From: indigomoon at bonbonBLINDERS.net (Indigo Moon Man) Date: Tue, 16 Sep 2003 12:44:21 -0600 Subject: None, False, True References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> Message-ID: M-a-S spake thusly: > Can anybody explain this: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 Type "help", "copyright", "credits" or "license" for more > information. >>>> >>>> None = 3 > :1: SyntaxWarning: assignment to None >>>> False = 4 >>>> True = 5 >>>> >>>> None, False, True > (3, 4, 5) http://www.ibiblio.org/obp/thinkCSpy/chap05.htm In section 5.9 (Glossary) near the bottom of the link above I found this entry for None... None A special Python value returned by functions that have no return statement, or a return statement without an argument. Maybe that has something to do with it. -- Remove BLINDERS to email me. Audio Bible Online: http://www.audio-bible.com/ From mertz at gnosis.cx Wed Sep 24 21:15:30 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 24 Sep 2003 21:15:30 -0400 Subject: Pre-PEP: reverse iteration methods References: Message-ID: |> >As infinite iterators are rare, it would not be too cumbersome to |> >let them identify themselves as such. David Eppstein wrote previously: |It would be quite cumbersome to have to identify simple generators as |infinite or finite manually, and impossible (halting problem) to do so |reliably automatically. Humans cannot solve the halting problem either, FWIW. Just because a programmer THINKS an iterator is finite, it don't mean it is! Actually, to my mind, infinite iterators are the RULE not the exception. Or if not actually infinite, iterators tend to be *indefinitely* large. That is, I use an iterator because I want to deal with something at runtime whose size is unbounded at programming time (e.g. an external file, or data from a socket). Overall, this makes me -1 on the whole idea of reverse iteration. Moreover, even iterators that are known to be finite and even of reasonable size will often be SLOW. For example, I might naturally write a simple generator to get data from a socket. Each time a block of data comes in, I take some action based on it. I want those actions to happen as soon as the relevant chunk of data is available, even though the socket is probably much slower than the CPU. If my GUI needs to wait for ALL the data in order to play the event in reverse, that might cause very uncomfortable pauses in the interface. On the other hand, if the widget updates every second (even for a couple minutes total), that seems reasonable enough. Yours, Lulu... -- _/_/_/ 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 jwdillworth at yahoo.com Fri Sep 12 11:55:18 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Fri, 12 Sep 2003 08:55:18 -0700 (PDT) Subject: Copying latest version of the file In-Reply-To: Message-ID: <20030912155518.83250.qmail@web41113.mail.yahoo.com> I've seen RPM's named that way, I think the convention is something like this: packagename-majorver.minorver.bugfixver-rpmver.rpm Here's how I would do it: import re rpm_name_parser = re.compile(r'^(.*)-(\d+)\.(\d+)\.(\d+)-(\d+)\.rpm$') # a dictionary of packages and versions available packages = {} # ... read names of RPM's in dirA # for example, we'll just use a list of 2 of the same package for rpm_name in ['mypackage-1.1.0-37.rpm', 'mypackage-1.2.0-10.rpm']: match = rpm_name_parser.search(rpm_name) # panic, the name isn't right! if not match: raise ValueError() package_name, majorv, minorv, bugv, rpmv = match.groups() majorv, minorv, bugv, rpmv = map(int, [majorv, minorv, bugv, rpmv]) package_info = packages.setdefault(package_name, []) version = (rpm_name, majorv, minorv, bugv, rpmv) if version not in package_info: package_info.append(version) # order all packages by version for p in packages: packages[p].sort() # ... to get the filenames of latest versions of all packages latest = [packages[p][-1][0] for p in packages] for pkgfile in latest: print pkgfile --- Kali K E wrote: > Hi, > I am new to Python and excuse me if this problem is very trivial. The > problem is like this. > There is a directory (dirA) that contains files like > mypacakge-2.2.5-15.rpm, mypacakge-2.2.5-90.rpm, > anotherpackage-3.4.25.rpm etc.. As can be seen, some of the files are > new versions of same rpm (mypacakge-2.2.5-15.rpm, > mypacakge-2.2.5-90.rpm in this example). It is also true that their > timestamps are different. The program has to check for latest version > of each package and copy them to another directory (dirB). That means > in this case, it has to copy mypacakge-2.2.90.rpm to another > directory. > The directory dirA would be containing more than 500 files. Out of > these many, about 100 files may be having new version. > Another point is the number of files of same package is NOT limited to > 2. So we may have mypacakge-2.2.5-15.rpm, mypacakge-2.2.5-90.rpm, > mypacakge-2.2.5-100.rpm, mypacakge-2.2.5-227.rpm in dirA and only > mypacakge-2.2.5-227.rpm has to be copied to dirB. > The same thing has to be repeated in other directories at the same > level as dirA. > Please let me know how to do this. > Thanks, > Kali > -- > http://mail.python.org/mailman/listinfo/python-list From Mike at DeleteThis.Geary.com Tue Sep 16 12:48:45 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 16 Sep 2003 09:48:45 -0700 Subject: object.attribute vs. object.getAttribute() References: Message-ID: Aurelio Martin Massoni wrote: > Read this nice article "Why getter and setter methods are evil: Make > your code more maintainable by avoiding accessors" > > http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html That's an interesting article. Be sure to read the comments at the end of page 3--the real fun starts there! -Mike From vze4rx4y at verizon.net Tue Sep 23 23:32:31 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 24 Sep 2003 03:32:31 GMT Subject: Pre-PEP: reverse iteration methods References: Message-ID: [Raymond Hettinger] > > Reverse iteration is much less common than forward iteration, but it > > does arise regularly in practice. [John Roth] > Absolutely. Because the question will arise, I did a quick use case analysis from the standard library. I'll attach the following to the PEP. Feel free to comment or add other use cases. Raymond Hettinger -------------------------------------------------------------------------- Use Case Analysis ================= Here are some instances of reverse iteration taken from the standard library and comments on why reverse iteration was necessary: * atexit.exit_handlers() uses:: while _exithandlers: func, targs, kargs = _exithandlers.pop() . . . The application dictates the need to run exit handlers in the reverse order they were built. The "while alist: alist.pop()" form is readable and clean; however, it would be slightly faster and clearer with: for func, target, kargs in _exithandlers.iter_backwards(): . . . del _exithandlers * difflib.get_close_matches() uses:: result.sort() # Retain only the best n. result = result[-n:] # Move best-scorer to head of list. result.reverse() # Strip scores. return [x for score, x in result] The need for reverse iteration arises from a requirement to return a portion of a sort in an order opposite of the sort criterion. The list comprehension is incidental (the third step of a Schwartzian transform). This particular use case can met with extended slicing, but the code is somewhat unattractive and hard to visually verify:: result.sort() return result[:-n-1:-1] * heapq.heapify() uses "for i in xrange(n//2 - 1, -1, -1)" because higher-level orderings are more easily formed from pairs of lower-level orderings. A forward version of this algorithm is possible; however, that would complicate the rest of the heap code which iterates over the underlying list in the opposite direction. * mhlib.test() uses:: testfolders.reverse(); for t in testfolders: do('mh.deletefolder(%s)' % `t`) The need for reverse iteration arises because the tail of the underlying list is altered during iteration. * platform._dist_try_harder() uses "for n in range(len(verfiles)-1, -1, -1)" because the loop deletes selected elements from "verfiles" but needs to leave the rest of the list intact for further iteration. This use case could be more efficiently met with itertools.ifilter but the lambda condition and functional style would render it less readable. * random.shuffle uses "for i in xrange(len(x)-1, 0, -1)" because the algorithm is most easily understood as randomly selecting elements from an ever diminishing pool. In fact, the algorithm can be run in a forward direction but is less intuitive and rarely presented that way in literature. * rfc822.Message.__delitem__() uses: list.reverse() for i in list: del self.headers[i] The need for reverse iteration arises because the tail of the underlying list is altered during iteration. From jwdillworth at yahoo.com Thu Sep 11 14:26:19 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Thu, 11 Sep 2003 11:26:19 -0700 (PDT) Subject: Newbie-question: Fetching web-address from the browser! In-Reply-To: Message-ID: <20030911182619.57324.qmail@web41104.mail.yahoo.com> os.environ is available, I've used it in CGI scripts on WinNT and Win2k. Do you mean you literally tried os.environ[''] (i.e. a blank key)? Anyway, creating a file with the following code should help: ---- snip import cgi cgi.test() ---- snip then punch the address of the script into your browser and you'll find the CGI module prints a nice report about what's available in the environment. Also, there is a reference to standard CGI environment variables at: http://hoohoo.ncsa.uiuc.edu/cgi/env.html (these should apply whether you're running IIS/Apache/etc) --- dermoon wrote: > I want to fetch the address from the web-browser when it > visits a page on my web-server. > > I use win2k on this server. > > On linux I used os.environ[''], but it seemes it's not available on > win2k, is this correct? > > However, how do I get the address-string? > > Any help would be greatfully appreciated! > > -Chris > -- > http://mail.python.org/mailman/listinfo/python-list From user at domain.invalid Mon Sep 15 16:20:19 2003 From: user at domain.invalid (user at domain.invalid) Date: Mon, 15 Sep 2003 20:20:19 GMT Subject: calling objects parents' __init__? Message-ID: Normally, when I inherit from a class that I have written, I want instances of the new class to call the __init__ of the old (actually, starting from the top of the tree, and moving on down). What is the preferred way to do this? Thanks, Tobiah From PeterAbel at gmx.net Mon Sep 29 16:25:15 2003 From: PeterAbel at gmx.net (Peter Abel) Date: 29 Sep 2003 13:25:15 -0700 Subject: Threading and Windows. References: Message-ID: <21064255.0309291225.259555ec@posting.google.com> Jorge Godoy wrote in message news:... > Hi! > > > I must have been searching in the wrong places or with the wrong > keywords but I couldn't find out how to implement something such as > what is done by the threading module on Windows (95, 98 and XP are the > ones used by my clients). My preference is for something available in > the standard library if possible. > > I have a simple task where I want my GUI to be able to open several > applications simultaneously. Using the threading module everything > works perfectly on Linux but the program won't run on Windows. > > > Any hints on what should I do? > > The working code is really simple and is all what I need on both > platforms (pseudo-code follows): > > > import threading > (...) > > class MyApplication(...): > (...) > def someMethod(...): > (...) > def temporaryFunction(): > os.spawnv('P_NOWAIT', 'another.py', ['another.py', parameters]) > thread = threading.Thread(target = temporaryFunction) > thread.start() > > > def anotherMethod(...): > (...) > def temporaryFunction(): > os.spawnv('P_NOWAIT', 'yetanother.py', ['yetanother.py', parameters]) > thread = threading.Thread(target = temporaryFunction) > thread.start() > > > and so on. > > (Yes, I could factor 'temporaryFunction' and reduce 5 lines of code in > my application, but I still don't know what will be necessary to do to > make it work on Windows, so I left it as is and factor it later.) > > > Any hints on how to accomplish that in a portable way? Or what > additional code will I have to use to make it work in Windows? > > > Thanks in advance, http://www.python.org/doc/current/lib/os-process.html says ... ... ... spawnl(mode, path, ...) spawnle(mode, path, ..., env) spawnlp(mode, file, ...) spawnlpe(mode, file, ..., env) spawnv(mode, path, args) spawnve(mode, path, args, env) spawnvp(mode, file, args) spawnvpe(mode, file, args, env) ... ... ... Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and spawnvpe() are not available on Windows. New in version 1.6. ... ... ... Regards Peter From davecook at nowhere.net Fri Sep 5 09:28:30 2003 From: davecook at nowhere.net (David M. Cook) Date: Fri, 05 Sep 2003 13:28:30 GMT Subject: OT: best book in years References: Message-ID: <2c06b.63986$0u4.8363@news1.central.cox.net> In article , Patrick Useldinger wrote: > I am going to stay in hospital for a week or so (nothing serious), and am > trying to find a book or two to read there. As I have not come across > anything spectacular recently (except Python in a Nutshell), I would like > to know what *you* consider to be the best book you have read in the last > few years, about Python or IT in general. Neil Stephenson, _Cryptonomicon_ Dave Cook From stephan.delete-schaumann at online.de Fri Sep 5 10:33:17 2003 From: stephan.delete-schaumann at online.de (Stephan Schaumann) Date: Fri, 5 Sep 2003 16:33:17 +0200 Subject: Massive unit test vs MySQL References: Message-ID: "Richard Wesley" schrieb: > I don't know if this is really a Python question of a MySQL question, > but i am hopen that there is enough overlap that someone can help me ;-) > > I have a unit test suite for our server that loads a clean database > image for many of the tests. I use > > p = os.popen('mysql -u uid -ppassword mydatabase', 'w') > p.write(sql_commands) Do you p.close() when you are finished? Otherwise the connection opend by mysql will stay open. > to load the database. > > While the tests are running, I find that mysql has a growing number of > "Sleeping" threads in the 'show processlist' table. Towards the end of > the test suite, the database loads start to fail with a MySQL error of > "ERROR 1040: Too many connections". > > So my question would be, is there any way to shut down the child process > so that MySQL notices and cleans up after itself before it runs out of > threads? From graham__fawcett at hotmail.com Tue Sep 9 13:11:45 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 9 Sep 2003 10:11:45 -0700 Subject: Comments on Python Redesign References: Message-ID: Nick Vargish wrote in message news:... > I really like the idea of the PSF selling boxed python distros for > around $300. People who make the business decisions _like_ spending > money on a product -- it's somehow comforting to them. Include bound > copies of the Tutorial and Library Reference, to give the box some > weight and make it clear that they are paying for something more than > a CD of "free software". (Spiral bound documents, please!) > > I'm hoping that my boss will be shelling out for some Komodo Pro > licenses, partly for the above reason. The other part of the reason is > that once money is spent on something, it becomes more entrenched in > an organization. This will serve to counter the PHB attitude that "if > it costs nothing to bring in, it will cost nothing to throw out." We bought Komodo licences for the same reason. ActiveState has been a great friend to us, though we've never been introduced; they certainly deserve a few bucks. And yes, I'd get our dept. to purchase PSF distros as well for the same reason. Lulu, if you're reading this: if you manage to sell any Gnosis boxed sets, would you mind sending me a little share, in thanks for coming up with the idea? I need a new canoe myself. ;-) -- Graham From dave at boost-consulting.com Wed Sep 3 09:22:36 2003 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 03 Sep 2003 09:22:36 -0400 Subject: Simple question: How to pass a C++ class reference to a callback? References: <17fbc98a.0309020423.11ac7b8d@posting.google.com> Message-ID: Harri Pesonen writes: > David Abrahams wrote: >> "T. Panbru" writes: >> >>>Try encapsulating your C++ class reference in a CObject, using: >>> >>> PyObject* PyCObject_FromVoidPtr( void* cobj, void (*destr)(void *)) >>> void* PyCObject_AsVoidPtr( PyObject* self) >>> >>>and so forth, to go back and forth between the C++ and Python realms. >>> >>>Check out the Python docs at: >>> >>> http://www.python.org/doc/2.3/api/cObjects.html >>> >> Or use one of the high-level wrapping tools such as Boost.Python >> (http://www.boost.org/libs/python) which make this stuff much easier >> and safer. > > Boost.Python is not 2.3 compatible yet, but it seems very good. The CVS version is 2.3 compatible; you can download a snapshot from http://www.boost-consulting.com/boost.tar.bz2 or you can access our anonymous CVS or a mirror (about a day behind). -- Dave Abrahams Boost Consulting www.boost-consulting.com From gerrit at nl.linux.org Mon Sep 29 10:33:03 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 29 Sep 2003 16:33:03 +0200 Subject: Google newsgroup "Unable to find thread" message? In-Reply-To: References: Message-ID: <20030929143303.GB6750@nl.linux.org> Stephen Ferg wrote: > Subject: Google newsgroup "Unable to find thread" message? > I use the newsgroup mainly via my Web browser and Google. > > Over the last few days, when I click on a link to a thread, I've been > frequently getting the message "Unable to find thread." > > Does anybody know what's going on? It seems to be a Google problem. It is not limited to c.l.py... Gerrit. -- 238. If a sailor wreck any one's ship, but saves it, he shall pay the half of its value in money. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From alanmk at hotmail.com Fri Sep 5 09:38:16 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 05 Sep 2003 14:38:16 +0100 Subject: OT: best book in years References: Message-ID: <3F5891C8.A7DD1A20@hotmail.com> Patrick Useldinger wrote: > I am going to stay in hospital for a week or so (nothing serious), and am > trying to find a book or two to read there. .. I would like > to know what *you* consider to be the best book you have read in the last > few years, about Python or IT in general. I had a few weeks in hospital last Christmas/New Year, and bought myself "Mastering Regular Expressions", by Friedl, before I went in, thinking it was an ideal opportunity to catch up on some reading. http://regex.info/ However, once I was in there, I never even opened the book. I was too busy focussing on getting healthy again. If you've got to spend a couple of weeks in hospital, spend it wisely: focus primarily on your health! The days and weeks after a medical/surgical procedure are the crucial healing period that will determine whether or not you'll remain healthy or be back for the same procedure again next year. All that work stuff, and related stuff, should wait until you're ready for it again. On a lighter note, a fantastic book that I really enjoyed reading (for leisure) was Kil'n People, by David Brin. http://www.amazon.co.uk/exec/obidos/tg/used/-/1841491381/ It's nothing less than a masterpiece of modern sci-fi. IMHO :-) Best wishes for good health! -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From spatel at landrum-brown.com Tue Sep 30 09:54:41 2003 From: spatel at landrum-brown.com (Samir Patel) Date: Tue, 30 Sep 2003 08:54:41 -0500 Subject: Is this is bug or something change in Python 2.3 Message-ID: <200309300854.42105.spatel@landrum-brown.com> I am calling __import__. It works fine with python 2.1 to 2.2.3, but does not work for python 2.3 and 2.3.1. I have 2 files x.py in current directory and mytest.py file in subfolder 'subdir' as follows: bash-2.05b# ls -lR .: total 5 drwxrwxrwx 2 root root 112 Sep 30 08:19 subdir -rw-rw-rw- 1 root root 107 Sep 30 08:19 x.py ./subdir: total 8 -rw-r--r-- 1 root root 28 Sep 30 08:13 mytest.py -rw-r--r-- 1 root root 135 Sep 30 08:19 mytest.pyc bash-2.05b# cat x.py import os os.chdir (os.getcwd() + '/subdir') itemText = 'mytest' moodule = __import__(itemText, globals()) bash-2.05b# cat subdir/mytest.py import os print os.getcwd() bash-2.05b# bash-2.05b# /usr/bin/python2.2 x.py /tmp/test/subdir bash-2.05b# /usr/bin/python2.1 x.py /tmp/test/subdir bash-2.05b# /usr/bin/python2.3.1 x.py Traceback (most recent call last): File "/tmp/test/x.py", line 4, in ? moodule = __import__(itemText, globals()) ImportError: No module named mytest -------------- next part -------------- A non-text attachment was scrubbed... Name: test.tgz Type: application/x-tgz Size: 425 bytes Desc: not available URL: From llafba at gmx.net Tue Sep 16 04:09:48 2003 From: llafba at gmx.net (Tom) Date: Tue, 16 Sep 2003 10:09:48 +0200 Subject: list of lists In-Reply-To: References: Message-ID: Hi guys, thanks to everyone. My mistake was that I had no idea that writing [][] NEXT to each other goes into depth. I always tried different varieties of [[]] to get into the deeper lists! Thanks again. CU Tom From graham__fawcett at hotmail.com Tue Sep 9 13:30:00 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 9 Sep 2003 10:30:00 -0700 Subject: Comments on Python Redesign References: Message-ID: "Richard Brodie" wrote in message news:... > "Graham Fawcett" wrote in message > news:mailman.1062993191.23216.python-list at python.org... > > > Developers will always be first-class Python users; it's a programming > > language, after all. Whether they should be first-class users of > > www.python.org, in my humble opinion, is questionable. > > I don't think so. They *are* the primary users of www.python.org > If you're suggesting that to give a professional feel, we should be like > Microsoft by moving around content so nobody can find it any more, > I strongly disagree. So would I! > I exaggerate, of course. However, although, I am not a complete > purist about it, keeping deep links (like say the PEPs) from breaking > should be part of the aim of the redesign. I'm sure it is. I agree. All I'm really saying (and I think you'll mostly agree) is that -- we developers are not the only Python audience -- the other audiences are interested in different facets of Python, i.e. not the docs and downloads -- therefore it makes sense to give each group different messages/content -- we are technically sophisticated (at least I hope we are) -- some (many?) members of other audiences are not -- technically-minded people know how to find sites, no matter where they are "hidden", through instinct, reading skills, and Google. -- giving the easiest-to-find site to the less technically sophisiticated is a just course of action -- we are a just organization (if there's a flaw in my argument, this is probably it! ;-) -- therefore, give the www.python.org site to the less technically-minded audiences. That's all pretty rational. I'd add the following, purely an opinion: -- a Python marketing group, well-rounded and well-informed, ought to determine what goes on the 'non-developer' portal, bearing in mind that developers are an important audience, but not the primary audience, of the 'non-developer' portal (www.python.org). -- developers who are incensed by this arrangement should either a) boycott the www.python.org site, spending all their time at dev.python.org or b) be rounded up, restrained and forced to view the new www.python.org site with eyelids sewn open, until they come to appreciate how wonderful a job the marketing team has done. Whether it's (a) or (b) I'll leave up to our Dictator for Life, and we'll see just how Benevolent he really is. ;-) -- Graham From guettli at thomas-guettler.de Fri Sep 5 06:48:11 2003 From: guettli at thomas-guettler.de (Thomas Guetttler) Date: Fri, 05 Sep 2003 12:48:11 +0200 Subject: OT: best book in years References: Message-ID: Am Thu, 04 Sep 2003 20:16:59 +0200 schrieb Patrick Useldinger: > Hi All, > > I am going to stay in hospital for a week or so (nothing serious), and am > trying to find a book or two to read there. As I have not come across > anything spectacular recently (except Python in a Nutshell), I would like > to know what *you* consider to be the best book you have read in the last > few years, about Python or IT in general. Hi Patrick, I suggest the Python Cookbook. thomas From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 03:21:30 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 08:21:30 +0100 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <1NFcb.62896$gV.2762@news2.central.cox.net> Message-ID: <2rdanvoouhnq5gqj2lrmjr3uci3leu9ua0@4ax.com> On Sat, 27 Sep 2003 00:08:22 -0700, David Eppstein wrote: >Speaking of which: str, int, etc., used to be functions, but they got >changed to be the initializers of types having those names. Why is >xrange still a function rather than the initializer of the xrange type? """ Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> xrange """ Looks like a type rather than a function to me, and the help appears to be very good. Enumerate also seems to be a type with an initialiser. Are you using an earlier version? -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From cpl.19.ghum at spamgourmet.com Tue Sep 16 00:27:29 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Tue, 16 Sep 2003 06:27:29 +0200 Subject: how can I use Berkeley DB XML 1.1.0 from Python 2.3 (on Windows) ? Message-ID: I found Berkeley DB XML while searching for XML-Databases. I want to use it from PYHTON - and I found examples.py in the distribution. But... examples.py tries to import from dbxml import * from bsddb3.db import * I do not have dbxml or bsddb3 on my computer ... using Python 2.3, I think bsddb3 is superceeded by bsddb but where do I get dbxml? Googling gave me a some hits, but they all appeared to be other dbxml modules than being connected to berkeley db xml reading the FAQs pointed me to installation-instructions on MAC OS, they were still dealing with installing bsddb3 ... as much I understand from "python 2.3 what's new" - bsddb3 ist integrated. No word about Module / package dbxml there, either. Tnx Harald From tim.parkin at pollenationinternet.com Sun Sep 7 07:46:48 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 12:46:48 +0100 Subject: Comments on Python Redesign In-Reply-To: <001b01c37535$38848030$0a00a8c0@JASPER> Message-ID: <001c01c37535$be4fc080$0a00a8c0@JASPER> Apologies for multiple posts From david.bear at asu.edu Tue Sep 16 23:53:28 2003 From: david.bear at asu.edu (David Bear) Date: 16 Sep 2003 20:53:28 -0700 Subject: testing the data-type of a stream Message-ID: I'm writing a filter and would like to be able to do what the Linux 'file' command does, i.e. look at a couple of bytes to see what kind of data I'm dealing with, the branch based on the type. I scanned the python library and couldn't find anything that seemed to approximate this. I know I could do os.popen and call the file command then parse the output, but would rather not if there is a regular python module that can do it for me. any recommendations? -- David Bear phone: 480-965-8257 fax: 480-965-9189 College of Public Programs/ASU Wilson Hall 232 Tempe, AZ 85287-0803 "Beware the IP portfolio, everyone will be suspect of trespassing" From stuart at bmsi.com Wed Sep 10 18:20:45 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Wed, 10 Sep 2003 18:20:45 -0400 Subject: getrusage Message-ID: When I call resource.getrusage on Linux, I don't get any memory stats: Python 2.2.2 (#1, Jan 30 2003, 21:26:22) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from resource import getrusage,RUSAGE_SELF >>> print getrusage(RUSAGE_SELF) (0.019531, 0.0078119999999999995, 0, 0, 0, 0, 178, 387, 0, 0, 0, 0, 0, 0, 0, 0) >>> On AIX, I get the correct numbers. What is the goal? I need to find a memory leak in an extension module. For starters, I was going to find extension method calls that produce unexpected memory use (and I found some on AIX - but our 12 year old AIX system is *so* slow). Suggestions are welcome. From anton at vredegoor.doge.nl Fri Sep 5 05:08:48 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 05 Sep 2003 11:08:48 +0200 Subject: Open Source leader? (was Re: Celebrity advice) References: <23891c90.0308280317.ac68b38@posting.google.com> Message-ID: aahz at pythoncraft.com (Aahz) wrote: >OTOH, Perens is also (like me ;-) a self-described asshole. When I saw >him at the Waterside Conference earlier this year, he basically claimed >that only assholes could make significant progress in the Open Source >community. Linus and Guido are obvious counter-examples in some >respects, but as you point out, they're not really interested in a >spokesmodel position. This a dangerous meme so I'll try to expose its working mechanism. First two related forms: "Thanks to microsoft which squished all the competition on the software market, we now have standards and all computer programs are compatible with the other surviving computer programs" "Firing people is hard, nobody wants to do the dirty work, so we need people who don't care about other people to be in charge of big companies and accordingly they should be paid top salaries" Excuse my English, but I still hope the readers get the general idea behind those and other expressions of this very dangerous meme. The general working mechanism seems to be to accept the current state of affairs as unavoidable and to deny the possibility that things could have gone different. Since the "what if" question is paramount to all progress, this is an effective way to inhibit the creative and critical capabilities in the human brain. Countermeasures: Since the meme takes different forms all the time one could create a pattern recognition scheme to identify it and generate antimemes using a template. For example a derived antimeme for the microsoft form would be: -If microsoft hadn't stalled progress in software development by hiding the algorithms used for their software we would *now* be there where we will be in twenty years. An antidote to the antisocial big company leader: -If people at the top are enriching themselves without any consideration for those who they should be leading, people lower in the hierarchy will take this as a role model. One ends up with a lot of people that don't care. Anton From john at rygannon.com Thu Sep 11 11:54:33 2003 From: john at rygannon.com (John Dean) Date: Thu, 11 Sep 2003 15:54:33 GMT Subject: Problems with setting up mod_python and Apache References: <3f5f6b41$0$239$fa0fcedb@lovejoy.zen.co.uk> <4zK7b.11532$NW3.6643@news1.central.cox.net> <3f605bee$0$199$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3f609ad5$0$234$fa0fcedb@lovejoy.zen.co.uk> Hi Steve Thank you very much for your reply Funnily enough I sorted out Apache problem before reading you post. Thanks all the same. I have mod_python working like a dream. So now in to the hard part. I hope you won't mind if I explain. The project I am working on, Rekall, contains serveral WSYWIG designers. Two of these designers are of particular interest for what I have in mind - the Form and Report Designers. Form and Report definitions are stored in XML format either as a file in the file system or in a SQL Database. The basic idea is to load a string object with the form or report definition. Then using Pythons XML DOM module build a HTML document plus the required SQL query string(s). If it is a form then we'll will need to build both the HTML data input form and the backend form processor. I guess this will need a publisher handler. I expect Reports to be a lot easier, but since I am talking about several report output during a single session I suppose I will need to get my head around dynamic handlers. Now that's frightening -- Best Regards John From skip at pobox.com Fri Sep 19 14:58:02 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Sep 2003 13:58:02 -0500 Subject: [OT] New Play: SPAMELOT In-Reply-To: References: Message-ID: <16235.20922.932775.43117@montanaro.dyndns.org> Daniel> http://www.dailyllama.com/news/2003/llama206.html I particularly liked the last sentence: Casting for SPAMELOT will begin shortly. Run away. Skip From oystein at gnubg.org Wed Sep 17 16:19:44 2003 From: oystein at gnubg.org (=?ISO-8859-1?Q?=D8ystein_Johansen?=) Date: Wed, 17 Sep 2003 22:19:44 +0200 Subject: texi2html in a cgi ? In-Reply-To: <33803989.0309171007.28ca7fda@posting.google.com> References: <8vL9b.30567$Hb.466972@news4.e.nsc.no> <33803989.0309171007.28ca7fda@posting.google.com> Message-ID: Miki Tebeka wrote: > I see two ways: > 1. Write the texi file to disk (use tempfile.mkstemp) and run the script > (using os.system) on it and send back the result > 2. Import texi2html (make sure it's in sys.path) and use it (this is not tested...) > ---- > from texi2html import TexinfoParser, HTMLHelp > from tempfile import mkdtemp > from os.path import dirname, join > > def to_html(file): > '''Convert texinfo to html. Return top html file''' > outdir = mkdtemp() > parser = TexinfoParser() > parser.sethtmlhelp(HTMLHelp("","")) > parser.setincludedir(dirname(file)) > parser.setdirname(outdir) > parser.parse(open(file)) > return join(outdir, "%s.html" % parser.topname) It works locally with the file below: #!/usr/bin/python from texi2html import TexinfoParser, HTMLHelp from tempfile import gettempdir from os.path import dirname, join def to_html(file): '''Convert texinfo to html. Return top html file''' outdir = gettempdir() parser = TexinfoParser() parser.sethtmlhelp(HTMLHelp("","")) parser.setincludedir(dirname(file)) parser.setdirname(outdir) parser.parse(open(file,"r")) return join(outdir, "%s.html" % parser.topname) to_html("faq.texi") It creates several html files in /tmp/, one file for each section, but how do I create only one file, faq.html? > Remeber to delete the directory from time to time ... I will! >>(Unexperienced Python programmer, who has just fallen in love with this >>beautiful programming language.) > > The more you'll know the deeper you'll fall in love :-) More and more each day! Thanks, -?ystein From edreamleo at charter.net Mon Sep 29 17:27:39 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 29 Sep 2003 16:27:39 -0500 Subject: A startup puzzle References: Message-ID: > Perhaps using a proxy object...might work: Great idea! Some complications: 1. Sometimes the test "if not realApp:" causes unbounded recursion. To avoid any possibility of this happening the startup code just creates the app object before any code actually uses the app proxies. This is easily done. 2. A __call__ method in the proxy allows the code to use either app().x or app.x. In short, the following pattern appears like it will work in all my modules: from leoGlobals import * app = leoProxy() # leoProxy defined in leoGlobals # Now the code can reference either app.x or app().x. To do this, I use the following code: gApp = None # Set before any reference to proxy. class leoProxy: def __getattr__(self,attr): return getattr(gApp,attr) def __call__(self): return gApp Many thanks for this great idea. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From newsgroups at jhrothjr.com Tue Sep 9 16:16:45 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 9 Sep 2003 16:16:45 -0400 Subject: How to instatiate a class of which the name is only known at runtime? References: Message-ID: "Marco Herrn" wrote in message news:mailman.1063135996.15871.python-list at python.org... > Hi, > > I am writing a program that has to instantiate a class from which I > don't know the name until runtime. That leads to two problems for me. > > 1. How to do the import? I didn't find a way to give a string to the > import statement. As Nick said, you can use the exec statement. You can also use the _import() function. > 2. How to write such code to instantiate? > > The first is a problem, when I don't know where the classes reside. I'm not sure what you mean by this. Modules exist on disk in a directory. There may be more than one class in a module, and there is no way of automatically asking for a class and having the module containing that class loaded. > Currently it is planned that all these classes reside in a specific > subdirectory. Is it possible to say 'import * from subdirectory' ? No. It is possible to load the names of all the modules in the subdirectory, though. That doesn't tell you what classes are in each module unless you either establish some standards or use a configuration file of some kind. You could, of course, simply import all of the modules, and then loop through them looking for the classes. > What other problems could occur here and how could I avoid them? The biggest problem I can see is name collisions, and that's only a problem if you don't establish standards, and use the simplest method, which is to use the identifier that the import statement adds to the module. > And to the second question, I have no idea about how to do this. Any > hints? As Nick points out, the easiest way is simply to build an import statement, and then exec it. John Roth > > > Bye > Marco > > -- > You can't judge a book by the way it wears its hair. > > -- > Marco Herrn herrn at gmx.net > (GnuPG/PGP-signed and crypted mail preferred) > Key ID: 0x94620736 > From rune.hansen at viventus.no Sat Sep 27 06:41:14 2003 From: rune.hansen at viventus.no (Rune Hansen) Date: Sat, 27 Sep 2003 12:41:14 +0200 Subject: Unicode 3 digit decimal conversion In-Reply-To: <3f755040-60d3252a-a4c8-4da8-850c-4dd661983a2d@news.szn.dk> References: <3f755040-60d3252a-a4c8-4da8-850c-4dd661983a2d@news.szn.dk> Message-ID: Hi , yes, of course *blush*. Thanks /regards /rune Klaus Alexander Seistrup wrote: > Rune Hansen wrote: > > >>>>>unicode("Gratis ?l","iso-8859-1") >> >>u'Gratis \xf8l' >> >>>>>ord("\xf8") >> >>248 >> >>What I need is the converted string to read u'Gratis \248l' (* >>How do I do this without going through each and every character >>of the string? > > > How about > > #v+ > > >>>>print unicode('Gratis ?l', 'iso-8859-1').encode('utf-8') > > Gratis ??l > > > #v- > > > // Klaus > From python at sarcastic-horse.com Tue Sep 16 18:57:13 2003 From: python at sarcastic-horse.com (python) Date: Tue, 16 Sep 2003 18:57:13 -0400 Subject: Fw: Re: how to build a list of mx.DateTime objects from a start and end date? Message-ID: <20030916185713.6677dc4d.python@sarcastic-horse.com> I wrote a generator to do it like so: def dr(startdate, enddate): mm = mx.DateTime.RelativeDateTime(months=1) while startdate <= enddate: yield startdate startdate += mm I created the list with: >>>> import mx.DateTime >>>> nov1999 = mx.DateTime.Date(1999, 11) >>>> mar2003 = mx.DateTime.Date(2003, 3) >>>> alldates = [d for d in dr(nov1999, mar2003)] This was my first generator! > Hi- > > > I want to make a list of mx.DateTime objects that cover all the monthly > intervals between two points. For example: > >>>> import mx.DateTime >>>> nov1999 = mx.DateTime.Date(1999, 11) >>>> mar2003 = mx.DateTime.Date(2003, 3) >>>> alldates = mk_list(startdate=nov1999, enddate=mar2003) >>>> alldates > [ ... a bunch of mx.DateTime objects including and between the startdate > and enddate ...] > > How would I do something like this? > > > Thanks for the help. > > -- > http://mail.python.org/mailman/listinfo/python-list > From jjl at pobox.com Thu Sep 18 08:52:59 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Sep 2003 13:52:59 +0100 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> Message-ID: <87r82e6yxg.fsf@pobox.com> Ken Godee writes: > Lothar Scholz wrote: [...] > I downloaded it all right from there site, Qt<->python converted html > docs as well (except ODBC, on win32 I use pyscopg). > > Know matter how you look at it, This is a GREAT DEAL, just for the > Qt/pyqt license issue's alone! > The kompany has put together a good deal with Trolltech and riverbank > for python users. $79 personal and $399 commercial with rights to > distribute the run-time elements. > I guess one could stick with straight c++ and pay trolltech $2,000 > plus per developer instead if you wanted to :) > (opps, for win32 platform development might want to spend another > grand+ to compile with MS VC++ compiler) John, is Ken right that buying the commercial BlackAdder license means you don't have to pay for the TT license too? Certainly a good deal if so. John From gh at ghaering.de Mon Sep 15 03:32:51 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 15 Sep 2003 09:32:51 +0200 Subject: pyc2py In-Reply-To: References: Message-ID: <3F656B23.8090808@ghaering.de> News M Claveau /Hamster-P wrote: > Pirate ? Pardon? There are lots of legitimate reasons for reverse-engineering. -- Gerhard From gh at ghaering.de Mon Sep 8 11:02:36 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 08 Sep 2003 17:02:36 +0200 Subject: Comments on Python Redesign In-Reply-To: <3F5B8C51.6462BC38@alcyone.com> References: <3F5B8C51.6462BC38@alcyone.com> Message-ID: <3F5C9A0C.9060705@ghaering.de> Erik Max Francis wrote: > Could someone remind me what need there is for a redesign in the first > place? Of all the Python-related efforts that one could put time into, > this seems like one of the least useful. I guess (I may be wrong) that Tim Parkin is not a developer, but apparently he has experience with web design. For some reason he chose to volunteer for proposing a redesign of the Python homepage (foolishly so, he might think by now). There's hardly any point in you telling him what to spend his time on for free, is there? :-/ Generally, in the open source community there's no point in telling people what they should do. Of those that are involved with open source in their spare time, everybody contributes to what are her or his priorities, according to their skills. Many of these projects might be a waste of time, but neither of your time nor mine :-) I dislike the connotation that web design (or writing documentation) would be less valuable than more technical contributions to Python. -- Gerhard From tchur at optushome.com.au Sat Sep 27 16:38:44 2003 From: tchur at optushome.com.au (Tim Churches) Date: 28 Sep 2003 06:38:44 +1000 Subject: Microbiology and/or image analysis tools In-Reply-To: <45bbfad.0309271119.386ded65@posting.google.com> References: <45bbfad.0309271119.386ded65@posting.google.com> Message-ID: <1064695124.1189.2.camel@emilio> On Sun, 2003-09-28 at 05:19, BW Glitch wrote: > Hello all, > > I've been searching on the web for microbiology and or image analysis > tools in any language (but I would prefer to be in Python ;), but I > haven't found anything useful. Almost every library I've found is > commercial. The only one I've seen open source is OpenEV ( > http://openev.sourceforge.net/ ). > > Is there any library open source available in these areas? I don't know if it is written in Python (probably not), but iPath might be of interest to you, maybe - see http://ipath.sourceforge.net/ - it is certainly an interesting and commendable project. -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From tim.parkin at pollenationinternet.com Sun Sep 7 09:46:42 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 14:46:42 +0100 Subject: Comments on Python Redesign In-Reply-To: Message-ID: <000401c37546$7bf10760$0a00a8c0@JASPER> Jeff Hinrichs said: > [...snip...] > I agree that the python.org site could use a face-lift, however, my > concern with the design presented is along the lines of page size and/or > browser compatibility. If you design via CSS using too many of the newer > features some older browsers will have problems rendering, if you don't > use CSS for that layout then you'll be using too many graphics. You > should keep in mind the fact that Python is used internationally. > So bandwidth, browser compatibility and internationalization are all > very valid concerns. > > If the redesign limits the number of people who can access it's > information or hinders their access to the same then I would be (-1) > on the effort. Remember, that the most popular and highly used sites, > i.e. google and yahoo, are quite boring in a design sense but are off > the chart for usability and accessibility. It's the content and the > accessibilty to that content that has made them so popular. I would > vote to emulate these attributes in any python website redesign. Although it is true that a lot of css 'hacks' prohibit the viewing of websites in older browsers, this is by no means a rule. One of the prime considerations in the redesign and a very early discussion was about accessibility. As far as we discussed, the site would be as accessibile as possible whilst not having to work to the lowest common denominator. It is perfectly possible to create designs that work quite well in older browsers but without some of the decorative/style elements whilst allowing more modern browsers to use the facilities for which the w3c have worked so hard to create. The main culprit in limiting the use of these standards is Netscape 4. As long as the website renders in such a way as to provide all of the functionality of the site then it is a general consensus that this would be adequate. (for instance, the netscape version of the redesign might lose some of the menu item box surround, the curved line, the boxes etc). As for bandwidth, the use of css designs (and I hasten to add, not necessarily table-less designs) can reduce bandwidth incredibly. The current site is a very respectable 22k and I would look to getting the whole of the new design in at around 30k (for home page, graphics can be made 20k without significant loss) and considerably less for interior pages as the only graphics will have been cached, around 18k or maybe less. For Google, I agree it's very usable but it also only has one main purpose (a search box and few links). The Python site has to satisfy many purposes, some of which act as almost contradictory to what developers may wish for. I hope I've reached a compromise as the main page will not be the one most used by developers and will be the one of most imortance to IT decision makers. For Yahoo, however, I think it's an absolute mess and is widely used as an example of a badly designed site as far as usability is concerned (I refer to more recent yahoo designs). For accessibility, well, it takes 71 cursor movements to get to the 'Internet' category. Hope this lays a few of your concerns to rest Tim Parkin From mwh at python.net Thu Sep 4 06:16:40 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 4 Sep 2003 10:16:40 GMT Subject: Quickie mail.python.org status References: <727daa7e.0309031140.1af820b2@posting.google.com> Message-ID: <7h3ptigg8ul.fsf@pc150.maths.bris.ac.uk> skip at pobox.com (Skip Montanaro) writes: > (Posted via Google so some fraction of the c.l.py community sees > it. :-) > > I noticed that python-related mail has been at best trickling in today, > so took a quick peek at mail.python.org. Since 4am today exim has > rejected over 15,000 messages because they contained executable > attachments or suspicious (sobig-style) subjects. I'm sure that's nothing > compared to sites like SourceForge or AOL, but it conspires to keep > useful mail from flowing through that machine. What happened to the firewall hack? I didn't think exim was supposed to be *seeing* the sobig stuff... Cheers, mwh -- About the use of language: it is impossible to sharpen a pencil with a blunt axe. It is equally vain to try to do it with ten blunt axes instead. -- E.W.Dijkstra, 18th June 1975. Perl did not exist at the time. From gh at ghaering.de Mon Sep 8 13:19:32 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 08 Sep 2003 19:19:32 +0200 Subject: Get the date of last modification of a file In-Reply-To: References: Message-ID: <3F5CBA24.1060006@ghaering.de> Manuel Bastioni wrote: > It's possible using only a built-in module? Sure: >>> import os, stat >>> s = os.stat("c:/tmp") >>> time.strftime("%Y-%m-%d %H:%M", time.localtime(s.st_mtime)) '2003-09-08 19:17' > Outgoing mail is certified Virus Free. What a stupid thing to say. -- Gerhard From bgailer at alum.rpi.edu Fri Sep 12 11:51:21 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 12 Sep 2003 09:51:21 -0600 Subject: Open MS Excel Spreadsheet with Python In-Reply-To: <37ee60c8.0309120616.794e2bf1@posting.google.com> References: <221d8dbe.0307160619.2c2943c3@posting.google.com> <221d8dbe.0308150959.b18167c@posting.google.com> <37ee60c8.0309120616.794e2bf1@posting.google.com> Message-ID: <6.0.0.22.0.20030912094842.0380cb90@66.28.54.253> At 08:16 AM 9/12/2003, Ajith Prasad wrote: >Would appreciate any advice on how to get started with the script. >Created an empty spreadsheet "test.xls" on drive F. Then at the >PythonWin prompt tried and obtained: > >>> xlapp=UseExcel("f:\test.xls") What precedes this code> Where does UseExcel() come from? Try "f:\\test.xls" (\t is the tab character and must be escaped) >Traceback (most recent call last): > File "", line 1, in ? > File "UseExcel.py", line 16, in __init__ > File ">", line 2, in Open >com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', >"'f:\test.xls' could not be found. Check the spelling of the file >name, and verify that the file location is correct.\n\nIf you are >trying to open the file from your list of most recently used files on >the File menu, make sure that the file has not been renamed, moved, or >deleted.", 'C:\\Program Files\\Microsoft >Office\\Office10\\1033\\xlmain10.chm', 0, -2146827284), None) [snip] Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From buzzard at urubu.freeserve.co.uk Thu Sep 18 19:39:33 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 19 Sep 2003 00:39:33 +0100 Subject: problem with user confirmation References: Message-ID: "Matthew" wrote in message news:ec1162c7.0309181523.2077b7e5 at posting.google.com... > I am have written a medium sized program and everything works fine > except for one piece. At a certain point in the program I want to do a > simple user confirmation, eg Are you sure ? y/n. The problem that I am > having is that after the user enters an answer and presses enter, the > program executes the rest of the code regardless of what the user > response was. > > Heres my code: > > def confirmAction(self, msg): > if not msg: > msg = 'Are you sure y/[n]> ' > print msg > confirm = sys.stdin.readline()[:-1] > print 'confirm = \'%s\'' %(confirm) > if confirm == 'y' or 'Y' or 'Yes' or 'YES' or 'yes': > return 1 > return 0 [snip] 'Y' evaluates to true. Maybe try something like: if confirm in ['y', 'Y', 'Yes', 'YES', 'yes']: etc. Duncan From newsgroups at jhrothjr.com Fri Sep 5 18:24:51 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 18:24:51 -0400 Subject: Why the 'self' argument? References: Message-ID: "Michael Peuser" wrote in message news:bjat11$70s$07$1 at news.t-online.com... > > "Grzegorz Staniak" > > > I'm a newbie Python user, a systems administrator - I've been trying > > to switch from Perl to Python for administrative tasks - and one thing > > I cannot understand so far is why I need the special 'self' (or anything > > esle) argument in class method definitions. > > You probably do not mean "class methods"; this a technical term in OOP. > > The Python class basics are *very* similar to the implementation of Perl > classes!! > You should not have much problems.... Actually, I think he *does* mean "class methods." They are new in 2.2 after all, and I missed the qualification the first time around. John Roth > > Kindly > Michael P > > From anthonypolis at hotmail.com Sun Sep 21 14:27:50 2003 From: anthonypolis at hotmail.com (anthony polis) Date: Sun, 21 Sep 2003 18:27:50 +0000 Subject: Creating a new file Message-ID: Hello, I'm new to Python. Is it possible to create a NEW file in Python? I read the tutorial on file input in the documentation but it only explains how to work with existing files. Can someone point me in the right direction? Thanks, Anthony _________________________________________________________________ Instant message during games with MSN Messenger 6.0. Download it now FREE! http://msnmessenger-download.com From peter at engcorp.com Mon Sep 8 17:13:58 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Sep 2003 17:13:58 -0400 Subject: Eureka! (Re: Comments on Python Redesign) References: <3F5CD10B.2020709@teksavvy.com> <200309072018.05589.dave@pythonapocrypha.com> Message-ID: <3F5CF116.2F755AA6@engcorp.com> Skip Montanaro wrote: > > Dave> I don't know of any problem with tinyurls - *any* server can > Dave> provide a "bad" redirect; as with any URL whether or not you > Dave> follow it depends on the context and on how much you trust the > Dave> sender. > > The only other reasons I could think of to object to tiny urls are: > > * Perhaps the tinyurl folks are not trustworthy (are they keeping track of > your browsing habits and selling that info?). That seems unlikely, since > they don't appear to be storing cookies in my browser. > > * The tinyurl website can become a bottleneck, preventing people from > getting where they want to go. The tinyurl.com website seems to be fairly > unreachable for me at the moment, though this is the first time I've seen > this, and it appears to be a problem more with Northwestern's connection > to the net than tinyurl.com's. > > * There's no guarantee tiny urls will remain unique or even available for > long periods of time. Their current practice of using four lower-case > letters suggests they have space for about 450,000 unique URLs before > extending to a fifth letter. * You can't tell ahead of time what site you are going to be redirected to. As a result, you lose complete freedom to choose whether or not you should follow the link. (Note for the imprecise: I didn't say you completely lose freedom, I said you lose complete freedom.) -Peter From skip at pobox.com Wed Sep 17 12:24:07 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Sep 2003 11:24:07 -0500 Subject: fast way to filter a set? In-Reply-To: References: Message-ID: <16232.35495.501167.780179@montanaro.dyndns.org> fortepianissimo> I know I can do things like fortepianissimo> s=Set(range(1,11)) fortepianissimo> s=Set(filter(lambda x:x%2==0,s)) fortepianissimo> But this seems a bit slow since filter returns a list fortepianissimo> which then must be converted back to a set. Any tips? The only thing which comes to mind is: >>> s = sets.Set(range(1,11)) >>> s Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) >>> keys = list(s) >>> dummy = [s.discard(x) for x in keys if x%2] >>> s Set([2, 4, 6, 8, 10]) You still create a list, but don't create a second set. Skip From BrenBarn at aol.com Thu Sep 4 01:25:02 2003 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 4 Sep 2003 05:25:02 GMT Subject: Importing/reloading modules Message-ID: I'm fooling around with some MUD server code, and I want to add a "reload" command that will let MUD wizards reload the server modules, so that changes to the MUD parser and such can be effected without having to shut down and restart the server. Now, what I want to do at the top of my main module, instead of just "import somemodule", is something like this: try: reload(somemodule) except NameError: import somemodule . . . so that it imports the module if it's just starting up, and reloads it otherwise. The problem is that I want to be able to call this code multiple times, so I can call it from the "reload" command. I can't figure out how to do this appropriately. If I put the try/except in a function, it doesn't import the module name into the global namespace, so that's no good. I could, of course, import the modules normally and write a separate function that reloads them, but then if I decided to import another module or remove one, I'd have to change both pieces of code. What I want is to get one piece of code that imports modules, or reloads them if they're already imported, and I need to be able to call this code like a function, from anywhere in my program. (There are also "from foo import bar" statements that I need to re-execute along with the reloads.) Something like: importFunc(): from foo import bar # except import it into the global namespace try: reload(baz) except NameError: import baz # except import it into the global namespace Someone suggested that I fiddle with __import__, but I'm not sure exactly what to do, or if this is the best approach. The documentation seems to suggest that simply doing __import__ ('somemodule', globals(), globals()) won't actually stick the module name into the global namespace -- is there some way to make this happen, though? -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From Scott.Daniels at Acm.Org Fri Sep 5 15:19:26 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 05 Sep 2003 12:19:26 -0700 Subject: Can't Open PY Files In-Reply-To: References: Message-ID: <3f58e1bb@nntp0.pdx.net> derek / nul wrote: > ... I have to call python file like this python myprogram.py > Derek Install the Win32all stuff -- you'l get file associations set up. The "assoc" "dos box" command can be used to see file associations: C:\> assoc .py .py=Python.File Once the proper associations have been made, you can run programs with: C:\> myprogram.py -Scott David Daniels Scott.Daniels at Acm.Org From aahz at pythoncraft.com Mon Sep 1 10:49:06 2003 From: aahz at pythoncraft.com (Aahz) Date: 1 Sep 2003 10:49:06 -0400 Subject: exception question References: Message-ID: In article , Gon?alo Rodrigues wrote: > >For error processing I found convenient maintaining a dictionary where >the keys are exception *classes* and the values are callables. Of >course, for this to work, exception classes have to be hashable which >I happily found that they were. So my question is, can I count on this >behaviour? Or is this behaviour I should not count on? (I found >nothing on the docs about it, thus the question). If it's not documented, you can't count on it. There's no intrinsic reason exception classes would be made unhashable, *but* classes become unhashable as soon as they implement __cmp__() or __eq__() *and* they fail to implement __hash__(). So if someone ever asks to compare exceptions, it could be an issue. You may want to bring this issue up on python-dev. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From jjl at pobox.com Wed Sep 3 19:16:01 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Sep 2003 00:16:01 +0100 Subject: Invisible function attributes References: <51809ae4.0309030715.7706cadb@posting.google.com> Message-ID: <87he3tfopa.fsf@pobox.com> lefevrol at yahoo.com (Olivier Lefevre) writes: [...] > So it would appear that function attributes are not really > there until the first call to the function. If that is the Not function attributes in general, just those that are first assigned to in the function body. No special rule here, though, because... > intended behaviour, it is really weird. I couldn't find any > explicit discussion of this topic in the LRM. > > Thanks if anyone can shed some light on this, ...what I'm guessing you haven't figured out yet is that everything works like this in Python. For example, what might be called a 'class declaration' in other languages isn't really a declaration in Python, it's code that gets executed at runtime. Same is true of functions: if WANT_SPAM: def sayhello(): print "spam" else: def sayhello(): print "eggs" sayhello() And your foo.a = 1 isn't a declaration (Python doesn't have them, really), it's just an attribute assignment. John From mpeuser at web.de Fri Sep 5 18:05:43 2003 From: mpeuser at web.de (Michael Peuser) Date: Sat, 6 Sep 2003 00:05:43 +0200 Subject: I need a little help with Tkinter Entry widget References: <221e7b06.0309051235.2d5b4868@posting.google.com> Message-ID: "Phil Schmidt" schrieb im Newsbeitrag news:221e7b06.0309051235.2d5b4868 at posting.google.com... > I'm trying to make a custom entry widget, as in the code that follows. > There are two problems I'm trying to fix: > > 1) I would like the widget to behave as myEntry.Escape() does now, > except that it happens on loss of focus, not when pressing Esc. > Then why don't you bind and ? Kindly Michael P From bokr at oz.net Thu Sep 4 13:36:13 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2003 17:36:13 GMT Subject: Circle Hell References: Message-ID: On Thu, 04 Sep 2003 07:55:18 -0700, Talon (by way of Talon ) wrote: >Hi all, > >I am new to Tk, so please bear with me. I need someone better at math >than me to help me figure this out. I am drawing multiple arcs on the >same circle. All arcs start at 90 and have varying negative extents >(different colors, goes all the way around. Represents a microbial >genome). So now that my arcs are drawn, I would would like to draw a >line, 25 pixels long that starts on the circle at the endpoint of each >of the arcs, and looks like an extension of the radius extending above >the circle. Then I would like to print text at the end of this line. So >my question is how do I dynamically calculate the line coordinates? >Circle size is fixed, number of arcs and their extents are variable. > >Code for drawing arc; >$x1,$y1 = 25 >$x2,$y2 = 775 >$xcenter = $x2/2 + $x1; >$ycenter = $y2/2 + $y1; > >$canvas->createArc($x1,$y1,$x2,$y2, > -width=>10, > -outline=>$colors[$color], > -style=>'arc', > -start=>90, > -extent=>-$actual_angle, > -tags=>$myorfs{$key}[1]); > >What I have so far to draw lines: > >$xstart = (cos($current_arclength)*$radius+$xcenter) /10; >$ystart = (sin($current_arclength)*$radius+$ycenter) /10; These look ok except dividing by 10, assuming the units for the angle are ok (degrees vs radians?) Dividing by 10 seems weird here, so try leaving it out. >$canvas->createLine($xstart+$xcenter, > $ystart+$ycenter, >From above, xstart already has xcenter in it, so don't add it again. Same for ycenter. > $xstart+($xstart*0.01)+$xcenter, > $ystart+($ystart*0.01)+$ycenter); If you want to draw a 25-pixel line, where is the "25"? You just need to resolve the 25 into x and y components and add them to your respective starting points, I would think. So UIAM the above becomes (giving a name to the 25-pixel length (assuming dimensions are in pixels) $tick_length = 25.0; $xstart = cos($current_arclength)*$radius+$xcenter; $ystart = sin($current_arclength)*$radius+$ycenter; $canvas->createLine($xstart, $ystart, $xstart+ cos($current_arclength)*$tick_length, $ystart+ sin($current_arclength)*$tick_length); > >This draws an oval of lines, inside the orginal circle, with the line >length having sin periodicity around the circle. Can anyone improve my >math so that I can get the lines placed properly with the proper length? > >Please email me directly as well as respond to the list. Thanks so much >in advance. > >--Math Challenged Mark > >Mark.Evans.B at bayer.com HTH Regards, Bengt Richter From jroznfgre at jngpugbjreXEBCXNbet.cy Fri Sep 19 09:12:00 2003 From: jroznfgre at jngpugbjreXEBCXNbet.cy (JZ) Date: Fri, 19 Sep 2003 15:12:00 +0200 Subject: Webware and RAM! Message-ID: How much memory WebKit should normally take??? As I can see, every WebKit daemon takes over 40MB (sic!) of RAM. WebKit lauches 10 daemons during startup, so I need over 400MB for WebKit alone! Is it normal or I have something wrong configured? -- JZ ICQ:6712522 From rganesan at myrealbox.com Fri Sep 5 02:13:38 2003 From: rganesan at myrealbox.com (Ganesan R) Date: Fri, 05 Sep 2003 11:43:38 +0530 Subject: in Ram database? References: Message-ID: >>>>> "John" == John D writes: > I kinda like the idea of being able to define smaller tables as > "in-memory" types, and the really large massive ones in other forms > managed by mySQL, PostGres, or bsddb3 databases. Use PySQLite (http://pysqlite.sf.net). Make sure that you have at least version 2.8.1 of SQLite and give the database name as :memory: (this is not obvious from the documentation). Since SQLite can handle databases upto 2 terabytes, you use it to store "really massive ones" on disk too :-). Ganesan -- Ganesan R From ulysses_dm at yahoo.com.cn Wed Sep 3 09:32:42 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 3 Sep 2003 06:32:42 -0700 Subject: How to accelerate python application GUI speed Message-ID: <43e3984e.0309030532.3fe88bbc@posting.google.com> Hi,all I use wxPython make a bittorrent client. I find wxPython very slow and use many many memory. When app start, it need 19MB memory. I only use common GUI components. Python is a really good programming language. But how to do a small,smart, efficency GUI in win32,it's a big question. I need make GUI,core code is bittorrent code. I can't change it.it's really good code. I read book 'Python Programming on Win32' ,I get following idea. I test it. 1. Use wxpython ,it's successful,but very slow . 2. use python for delphi. I test it, but it need embed python code to delphi. So need change original code.Actually I don't know how to change .it's big project. 3. User win32com, make a com server by delphi. com server have form. make python code as com client. I make a com server and invoke the server by pythonwin. but the form can't show. :( anyone do it ,could you share you code to world. 4. use pythonwin. mfc or win32gui framework. I check the demo code, it's very complex. you know I hate MFC. it's a joke. i like VCL so much. 5. I have a another idea. use wxWindows (c lan) build a GUI. embed python code . or embed wxWindows code to python by SWIG. I have't test it. if you have do it. Please tell us. Thanks. Ulysses ulysses_dm at yahoo.com.cn From merman at snafu.de Thu Sep 4 09:54:57 2003 From: merman at snafu.de (T. Kaufmann) Date: Thu, 04 Sep 2003 15:54:57 +0200 Subject: question: How can I put empty directories into a zip-archive? Message-ID: <3F574431.6020902@snafu.de> Hi there, in my directory are some 'normal' files like *.py sources and some empty directories too. How can I put all togehter into a zip-archive? There is no problem to zip the *.py files but if I try to add empty directories an exception is trown. Thanks. o-o Thomas From jjl at pobox.com Tue Sep 9 14:43:47 2003 From: jjl at pobox.com (John J. Lee) Date: 09 Sep 2003 19:43:47 +0100 Subject: Codesample for xml/xslt transforming References: Message-ID: <871xupg5uk.fsf@pobox.com> axel at pizza.home.kosnet.com (Axel Straschil) writes: > Hello! > > > BTW, I used to waste a lot of time with xslt. > > Jep, hard work for eight lines: > from Ft.Lib.Uri import OsPathToUri > from Ft.Xml import InputSource > from Ft.Xml.Xslt.Processor import Processor > STY = InputSource.DefaultFactory.fromUri('test.xsl') > SRC = InputSource.DefaultFactory.fromUri('test.xml') > proc = Processor() > proc.appendStylesheet(STY) > print proc.run(SRC) That looks like Python code to me, Axel, not XSLT . It's writing the XSLT that's the pain, not interpreting it (though that can certainly be 'arbitrarily difficult' -- in the words of K&R, IIRC -- if the XSLT implementors have hidden the command-line utility well enough). The utility of XSLT is that everybody can agree to hate it equally <0.3 wink>. If the world were saner, we'd all agree to *like* Python equally, but there you go. (actually, I don't hate it in itself -- just the way people view it as being particularly useful, which seems unjustified) > > I think you are most of the time quicker with SAX for > > parsing XML and "print" to create XML. > > It's for an CMS-System. I think XML and XLST is a good thing > if programmer and webdesigner have to work together, and you > realy want to seperate the content from the design > (Even when I think god had a bad day when he craeted > webdesigner ;-). XML is good because it's an widely-understood, easy-to-read, not-to-complicated, *non*-loathesome standard that gets the job done. XSLT... well, it's a standard. And it has an 'X' in the name, of course, which is the killer feature . John From mpeuser at web.de Thu Sep 4 18:33:42 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 00:33:42 +0200 Subject: OT: best book in years References: <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> Message-ID: "Peter Hansen" schrieb im Newsbeitrag news:3F57A9F5.F579219D at engcorp.com... > "John J. Lee" wrote: > > > > Peter Hansen writes: > > [...] > > > This sounds like a good opportunity to read "Zen and the Art of Motorcycle > > > Maintenance" (by Robert Pirsig) if you have not already. It's certainly > > > about IT, and ties into "The Zen of Python" (by Tim Peters) nicely, too. :-) > > > > Don't read it, it's a pile of junk. :-) IMNSHO. > > Are you trying to start the book-burning thread again? :-) To my unbiased ;-) opinion it *is* overestimated. But it a good supplement to C.P Snow's "Two Culture Theory". It might be disapponting for somone who seeks simple help for software development.... Kindly Michael P From jjl at pobox.com Wed Sep 10 08:38:16 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Sep 2003 13:38:16 +0100 Subject: java pythpn extension (JPE) download fails References: Message-ID: <87smn4byyv.fsf@pobox.com> "marcus b." writes: > I'm trying to get a current version of the java python extensin (JPE), but > the the link on http://jpe.sourceforge.net/ > (http://sourceforge.net/project/shownotes.php?release_id=60438) is not > working. I searched the web to get some other source of download, but > everyone seems referring to this site. Has anyone sucessfully downloaded > this JPE recently? Any hint how to get JPE would be very nice..! CVS? Somebody here mentioned that it's not seen much activity recently, though. John From newsgroups at jhrothjr.com Fri Sep 5 16:30:24 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 16:30:24 -0400 Subject: Why python??? References: <3335321.1062775466@dbforums.com> Message-ID: "yeung_too" wrote in message news:3335321.1062775466 at dbforums.com... > > Dear all, > > > > My college used C for beginner course and use Java to demostrate OO > concept. Anyway, I tried python and found that it is a very good > language. I think many people spend time on Java and university uses > Java because Sun Microsystem spends much money to promote and > develop the Java language. I just feel that our world spends most > time on promote things, rich company can promote computer language > very well. Open source without huge money support, people may > dislike their product. What do you think, But i really like open > source ideas, it improves our world, not just $$$. There are a number of universities using Python as a first language. It's got a lot to recommend it in that position, since it has a minimum of unnecessary baggage and still has good OO capability and an extensive enough library to get something done. Then you can move to the other languages of real commercial interest in subsequent courses. It's also, of course, very useful in situations such as secondary schools where you may want to teach programming, but the students aren't thinking of becoming professional programmers. John Roth > > > > an university student > > (reflect my feeling) > > > -- > Daniel Chan > > > Posted via http://dbforums.com From mickel at csc.fi Thu Sep 18 03:36:33 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Thu, 18 Sep 2003 10:36:33 +0300 (EEST) Subject: Checking if the computer is online In-Reply-To: References: Message-ID: On Thu, 18 Sep 2003, Thomas Heller wrote: > Mickel Gr?nroos writes: > > > Hi all, > > > > I have a silly question. Is there are simple way to check if the computer > > is connected to the Internet? It seems this should be a pretty > > straight-forward thing to do, but as I am totally unfamiliar with sockets > > and such, I ask for your help before getting my hands dirty. > > For windows? > > I want to get this done on both Windows (2000/XP) and (Redhat) Linux (7.x or higher). Isn't there a way to wrap a call to urllib.urlopen in some kind of timer, so that the call fails if there is no answer in N seconds? (I.e. if urllib.urlopen cannot open a specific web page in N seconds, then I assume that the reason is that the computer is not online.) That would be good enough for me. Any suggestions? /Mickel From llothar at web.de Wed Sep 17 09:28:46 2003 From: llothar at web.de (Lothar Scholz) Date: 17 Sep 2003 06:28:46 -0700 Subject: wanted($): mac and linux python gui coders for porting References: <8dsfmvo15uftg7qvc0oivmsg6eeeqelvtm@4ax.com> Message-ID: <6ee58e07.0309170528.9c81592@posting.google.com> Tim Roberts wrote in message news:<8dsfmvo15uftg7qvc0oivmsg6eeeqelvtm at 4ax.com>... > The problem is that 10% of your shareware revenue stream is likely to come > to approximately $1 per month. > > Further, the shareware revenue stream from your Linux port is almost > certainly going to be $0 per month. Linux users do not pay for software > tools like this. There's just too much outstanding stuff available for > free. With his marketing skills it will be $0 even for the windows version. And with a connection that gives me 2Kb/sec on a fast DSL line even the download will be 0. From martin.schneider at illusion-factory.de Tue Sep 9 05:06:01 2003 From: martin.schneider at illusion-factory.de (Martin Schneider) Date: Tue, 9 Sep 2003 11:06:01 +0200 Subject: Python / C: small runtime difference? Message-ID: Hi! I want to extend Python with a C module, so to get the technology clear, I wrote a Bubblesort over 10.000 elements in Python and in a C extension for Python and got it running (YES! :-)) But... The Python Bubblesort runs 103 seconds, the C extension Bubblesort runs 28 seconds, this is about 1:4, which is far worse than I expected (assumed about 100:1 or alike). The interface overhead is neglectable (1/10 second). Is this normal? I am using Borland's free compiler BCC on Win32 and Python 1.5.2 (because the customer uses other modules which do not run under newer versions). Thank you for your ideas! Martin From timr at probo.com Mon Sep 22 01:18:00 2003 From: timr at probo.com (Tim Roberts) Date: Sun, 21 Sep 2003 22:18:00 -0700 Subject: pop3 email header classifier? References: Message-ID: Robin Becker wrote: > >Hi, I'm getting vast numbers of fake upgrade emails containing some kind >of virus. My rather old client can be made to reject these based on some >patterns in the subject line. They're nearly all based on the word >'New', 'Latest', 'Microsoft', 'Patch', 'Pack', ... etc etc. > >Is there a python tool that can be made to delete these from my POP3 >mail box rather than let my client reject? Quite a few seem to have >semi-valid return addresses so I get postmaster rejects from >xxx at microsoft.com etc. Is your e-mail client actually set up to send a RESPONSE when you receive a virus attachment? If so, can you please STOP IT AT ONCE? ALL viruses released in the last 3 years choose random names for both the sender AND recipient. It is not possible to automatically extract the infected individual's e-mail address from a virus message. You can find the address of their e-mail server, but that's all. By sending a polite "you sent me a virus" message, you are doing NOTHING to stop the viruses, you are ANNOYING an innocent person, and you are DOUBLING the e-mail volume damage caused by the virus script kiddies. I got close to 10,000 helpful and completely bogus "you sent my a virus" messages during the "SoBig" fiasco. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From domma at procoders.net Thu Sep 25 08:52:36 2003 From: domma at procoders.net (Achim Domma) Date: Thu, 25 Sep 2003 14:52:36 +0200 Subject: adodbapi / string encoding problem References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:bkumfg$ifj$01$1 at news.t-online.com... > You have to know the encoding of the original file. Why? It's of type 'str' and I would expect that I could write it to DB and get the same 'str' back. That's all I want. Why is it required do know the encoding? Achim From bogus at invalid.tld Thu Sep 4 00:00:45 2003 From: bogus at invalid.tld (Jules Dubois) Date: Wed, 3 Sep 2003 22:00:45 -0600 Subject: Writing solid code book References: <87wucqni5j.fsf@pobox.com> Message-ID: <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> On 03 Sep 2003 13:58:00 +0100, John J. Lee wrote: > The Python Cookbook is the first book I'd have on my list if I were > learning Python now (O'Reilly, eds. Martelli & Ascher). That's the only Python book you think worth having? Or buying? My "Software Engineering" class votes again tomorrow on the language we use for our group project. Tuesday's vote was Java (8 votes), Python (5), C++ (3), and Smalltalk (1); Thursday's vote will be between Java and Python. I get the opportunity to learn one or the other in a week. From mertz at gnosis.cx Mon Sep 8 13:57:41 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 08 Sep 2003 13:57:41 -0400 Subject: What is marketing? References: Message-ID: Alex Martelli wrote previously: |Many techies think of "marketing" as a dirty word because it's so often |misused as an inappropriate synonym for "selling". marketing 1. The act or process of buying and selling in a market. 2. The commercial functions involved in transferring goods from producer to consumer. -------------------- The American Heritage (r) Concise Dictionary of the English Language, Third Edition. Copyright (c) 1992 Houghton Mifflin Company. In other words, 'marketing' is a synonym for 'selling' (commercially). The neutral word that Alex is looking for is 'promotion', which has a subtle but important difference from the dirty word. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Sep 22 23:59:32 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 04:59:32 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: <63gvmvcf6iakbs8pgll7u8ogblkbqld6fp@4ax.com> On Mon, 22 Sep 2003 22:41:04 -0400, "Sean Ross" wrote: >"Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in >message news:5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn at 4ax.com... >> >> Some more looping thoughts - this time on integer for loops... > >Hi. >How about the following: > >for i in 0...10: > # suite > >where 0...10 works something like xrange(10). So you get i=0 then 1 then 2 >... then 9. To get 0 thru 10, inclusive, you'd need to say 0...11 (Ruby has >0..10, but I doubt that'd pass muster here). Personally, I think the conventional '..' has more chance than your '...'. Basically, the idea of '..' specifying an inclusive range is a familiar idea to most people, even those who haven't used languages like Ruby or Ada that use that notation. Having a syntax that looks similar but means something just slightly different is likely to be seriously error prone and confusing. I'm certainly not against '..' in the conventional sense (I like half-open ranges, but I'm not a fundamentalist and inclusive ranges have worked perfectly well in Basic and Ada (and IIRC Pascal, Modula 2 and others). Actually, the main reason I didn't mention it myself is that I figure there must be some reason for its being rejected in the past. I can't seriously believe that it has never been proposed. >Leaving the ellipsis aside, you could add methods to int/long (also ala >Ruby), > >for i in 0.upto(10): > # suite > ># to count down >for i in 10.downto(0): > # suite I'm not sure about this - I'm bouncing between "that's neat!" and "yuck!", but the "yuck!" part may just mean I need to get used to it. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From jepler at unpythonic.net Tue Sep 2 18:34:56 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 2 Sep 2003 17:34:56 -0500 Subject: Difference of hash and __hash__() In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DEAD454A@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DEAD454A@au3010avexu1.global.avaya.com> Message-ID: <20030902223456.GB11303@unpythonic.net> On Wed, Sep 03, 2003 at 07:35:31AM +1000, Delaney, Timothy C (Timothy) wrote: > > From: Terry Reedy [mailto:tjreedy at udel.edu] > > > > "Stefan Fleiter" wrote in message > > news:bj2nv5$hna$1 at news.web.de... > > > > > under Python 2.2.2: > > > > > > >>> s = slice(None,5,None) > > > >>> hash(s) > > > Traceback (most recent call last): > > > File "", line 1, in ? > > > TypeError: unhashable type > > > >>> s.__hash__() > > > 136775584 > > > > > > Can anybody explain this? > > > > It looks like a bug. Extended slices were added for use by Numerical > > Python. It may never have tried to hash them or only done so only > > through the C equivavlent of s.__hash__. Extended slicing of > > sequences was, I believe, only added in 2.3. > > Looks like a bug to me too. Stefan, please raise a bug report on Sourceforge (or it will get lost). Preferably add a patch and test suite ;) > > Tim Delaney No, it's apparently deliberate that slices don't hash (so that {}[1:2] raises an error). I think that slice(None).__hash__ is from object.__hash__, but this is rightfully(?) ignored by PyObject_Hash() which looks at tp_hash (NULL for slice objects) and tp_compare (non-NULL for slice objects) with the result that the object is treated as unhashable. Jeff From bgailer at alum.rpi.edu Mon Sep 1 14:12:24 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 01 Sep 2003 12:12:24 -0600 Subject: Overloading objects In-Reply-To: Message-ID: <5.2.1.1.0.20030901120306.02e89c90@66.28.54.253> At 10:55 AM 9/1/2003 -0300, Batista, Facundo wrote: >In others languages I can do (using sintaxis of Python): > >def myMethod (self, name): > self.name = name > >def myMethod (self, name, age): > self.name = name > self.age = age > >If I'm not wrong, this is "Method Overloading". > >I thought using defaults: > >def myMethod (self, name, age=None): > self.name = name > if age not None: > self.age = age > >but I'm concerned about the scalability of this. > >What's the most pythonic way to do this? Using something like *args or >**args? Depends. In your example, overloading is resolved by the # of args passed, and their meaning depends on their position. If that is all you want, specify defaults as in age=None. Overloading can also depend on the type of data passed to the method, in which case you'll need either an if .. elif structure or a dictionary keyed by types to resolve things. You can also define different methods with the same name by subclassing and using instances of the various subclasses in your various situations. This approach obviates the need for overloading and can make the intent of the program a lot clearer to the reader. IMHO the latter is a better way to deal with complex situations. I often find myself coding default values and if elif structures, and a bell rings reminding me to sublcass. The result is almost always better. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From newsgroups at jhrothjr.com Fri Sep 26 14:10:08 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 26 Sep 2003 14:10:08 -0400 Subject: Reduce need of backslash References: Message-ID: "Nicolas Fleury" wrote in message news:MI_cb.75294$PD3.4794043 at nnrp1.uunet.ca... > Peter Otten wrote: > > > Nicolas Fleury wrote: > > > > > >>I was wondering if the need for \ could be reduce in the language. For > >>example, could a line ending with = or + could be automaticly considered > >>incomplete? > > > > > > Did you know about (...)? > > Actually, no. But it's still not what I'm looking for. It's just that > I'm used to languages where I can put my code on multiple easily to make > lines shorter. As John pointed, it's possible to add () to print. I > just discovered that it can be done with return also. I wonder how to > remove the need for \ in that example: > > parser.StartElementHandler = \ > lambda name, attrs: \ > GenericParser.handleElementStart(self, name, attrs) How about: parser.StartElementHandler = (lambda name, attrs: GenericParser.handleElementStart(self, name, attrs)) John Roth > > Regards, > > Nicolas > From tjreedy at udel.edu Sat Sep 27 01:11:30 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2003 01:11:30 -0400 Subject: Now that rexec is gone... References: Message-ID: "Rainer Deyke" wrote in message news:XA8db.597231$o%2.276974 at sccrnsc02... > Now that rexec is gone, is there any code or information available on > executing Python in a restricted environment? And before I roll my own > solution, exactly where the security holes in rexec anyway? Suggest you google last year of c.l.py for 'rexec'. Also check out py-dev summaries of last fall for discussion of why removed. TJR From forodejazz at yahoo.es Thu Sep 25 11:21:29 2003 From: forodejazz at yahoo.es (=?ISO-8859-1?Q?David_Asorey_=C1lvarez?=) Date: 25 Sep 2003 08:21:29 -0700 Subject: send email References: Message-ID: <1759581e.0309250721.79ecb06@posting.google.com> "Alberto Vera" wrote in message news:... > Hello: > > Could you tell me How I can send an email using WIN2000? What do I need? Using Python, I supose... http://www.python.org/doc/current/lib/module-smtplib.html -- David. From groups-support at google.com Sun Sep 28 06:34:48 2003 From: groups-support at google.com (groups-support at google.com) Date: Sun, 28 Sep 2003 10:34:48 -0000 Subject: [#4071110] baby!your friend send this file to you ! In-Reply-To: <200309281034.h8SAY0Tx003043@smtp8.google.com> Message-ID: <#14.3e1ec6.d01b8d25.3f76b948.4a7f@google.trakken.com> Thank you for contacting us about our Google Groups service. We read all incoming emails and your comments will be forwarded to the appropriate Google team. However, because our resources are focused on completely implementing the changes our users have already suggested, we are not able to respond to each email personally. In order to assist you as quickly as possible, we have included answers to the most frequently asked questions in this message, including instructions on how to post or remove posts from a discussion. It's likely you will find answers to other questions in our Google Groups FAQ, which we continue to update. We are working hard to provide the Web's best access to Usenet and ask that you bear with us as we work to make this a reality. Regards, The Google Team FREQUENTLY ASKED QUESTIONS ABOUT POSTING: * Can I prevent my message from becoming a permanent part of Google Groups? By default, any message you post will be accessible to anyone looking at the newsgroup in which you posted it. However, you can always choose to reply directly to a post by email instead of posting a reply within a newsgroup. With email, only the author will see your message. You can also type " X-No-archive: yes" in the first line of your message. Messages containing this command are sent to Usenet and are available to other newsreaders, but will not be saved in most Usenet archives, including Google Groups. * How do I post to Google Groups? To post a message, you must first identify the newsgroup in which you wish to start a discussion or select an article to which you wish to respond. To start a new thread, click the link that says: 'Post new message to the.name.of.a.group'. You should see this link when you're one level above the actual articles in the group. If you wish to respond to a specific post, you must drill down all the way to the message level. Your message will be "threaded" to that message and the others that have preceded it. You can find an article by searching on a given topic and then clicking on the "View Thread" link; or by browsing through a newsgroup and clicking on an article. When you are ready to post, click on the "Post a Followup" link in the upper right corner of your screen. If the link does not appear, you may not be at the article level. Whether you're replying to a message or starting a new thread, the first time you post you will be taken to a registration page. It's required that you register with an email address and password before posting in order to protect your identity. Follow the instructions for registering. On subsequent visits, simply sign in with your login and password to access the posting form. If you're new to posting, you may also want to spend a few minutes reading about Usenet posting etiquette. This will help you avoid common mistakes and give you a feel for the do's and don'ts of communicating with a potentially global audience. * Can I remove a message after I post it? Google Groups enables the nuking (removal) of an author's own posts from message groups. if you are the author of a message in the archive and would like to remove it, send an email to: groups-support at google.com that contains the following items: . Your full name and contact information, including an email address that can be verified . The complete Google Groups URL (or message ID) for each message you would like to have suppressed . A statement that says "I swear under penalty of civil or criminal laws that I am the person who posted each of the foregoing messages or am authorized to request removal by the person who posted those messages." . Your signature (electronic) To prevent your future posts from being added to the Google Groups archive, type 'X-No-archive: yes' in the header or the first line of the message. * I just posted an article and it's not showing up on Google Groups. Why not? Since Usenet is actually a network of thousands of computers, it takes some time for your message to be propagated to all of them. Usually a message begins showing up within 1-4 hours, but because of random fluctuations in web space, the process sometimes takes longer. * I don't want my email address to be published on the web, but I still want to post. How can I hide my email address? We require a valid email address to post to Google Groups. If you don't want your normal email address to be listed, we encourage you to sign up for an anonymous account with one of the many free email services available on the web and to post from that account. You can find a list of such services by conducting a Google search. From brian at sweetapp.com Mon Sep 15 16:55:32 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 15 Sep 2003 13:55:32 -0700 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: Message-ID: <014901c37bcb$b4476060$21795418@dell1700> > The point I was trying to make (not in this message but in general) is > that it would be simple (trivial but tedious) to create a version of > Python that is thread-safe, and the only reason it is not done is > because it would break old code. Actually, it would be reasonably difficult. If you don't agree why not spend a weekend implementing it and see how robust your implementation is? Also, adding object-level locking would involve a huge performance penalty. > All other modern languages are free-threaded. Ruby is not free-threaded in the sense that you mean. > "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 100 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." > > Yuck. You can release the lock at other times too. If you were doing a long-running calculation that doesn't require use of the Python API, for example, it would be appropriate to release the GIL. > Only one global variable left (in fact there is Py_None as well). Why > not get rid of it, then?? I think that you must be missing something... There is nothing special about Py_None. The number 5 is globally shared just like Py_None is. This is a performance optimization used to prevent lots of small numbers from being allocated and destroyed all the time. Cheers, Brian From max at alcyone.com Mon Sep 8 18:07:30 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Sep 2003 15:07:30 -0700 Subject: Eureka! (Re: Comments on Python Redesign) References: <3F5CD10B.2020709@teksavvy.com> <200309072018.05589.dave@pythonapocrypha.com> <3F5CF116.2F755AA6@engcorp.com> Message-ID: <3F5CFDA2.C947C3A2@alcyone.com> Peter Hansen wrote: > * You can't tell ahead of time what site you are going to be > redirected to. > As a result, you lose complete freedom to choose whether or not you > should > follow the link. (Note for the imprecise: I didn't say you > completely lose > freedom, I said you lose complete freedom.) But you can't tell that any URL, even a long one that looks meaningful, won't redirect you someplace you don't want to go. Even if it's what you expected, there could be something on the page which potentially does something malicious, like a Java bomb. It all comes down to trusting the person who's posting the URL, and that doesn't change whether it's a tinyurl.com URL being posted or something else. (Not that I'm a particular fan of using tinyurl.com, but this seems like a strange thing to complain about.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The people are to be taken in very small doses. \__/ Ralph Waldo Emerson From tim.parkin at pollenationinternet.com Mon Sep 8 05:25:08 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Mon, 8 Sep 2003 10:25:08 +0100 Subject: More Comments on Python Redesign In-Reply-To: Message-ID: <005401c375eb$1ea0b9c0$0a00a8c0@JASPER> David said: >|>I guess you chose not to read the suggestions that I made, or that many >|>other people made. >|I have made changes, font sizes, contrast, line spacing, etc. So I wonder >|how you managed to miss this >Actually, I read them all... well, not in the last couple hours. But >everything up to that on c.l.py, and even on the pythondotorg-redesign >mailing list. Just in case people didn't realise, there is a py-design-forum at :- http://pythonology.org/mailman/listinfo/py-design-forum And a python marketing forum at http://pythonology.org/mailman/listinfo/marketing-python >|The commercial customer is the company that is choosing to use Python on >|a core project, the company that wasts to bas there product on Python, >|the company that is evaluating a recommendation to deploy Python. >Exactly! Whose "customer" is this?! It seems as if working in "the web >design industry" has diminished your ability to write without nonsensical >jargon. A company that may or may not use Python is not a "customer" of >PythonLabs, or PSF, or whomever. It is exactly this gross >misunderstanding, I think, that leads you to create such an inappropriate >page (well, I don't like many of those corporate/marketing pages that big >companies that actually have customers create either)... that combined >with a disregard for usability. Although I use the word customer loosely, I would have thought you would understand my context. Although in your eyes a commercial entity choosing to use Python against, say, C# is not a customer, in the companies eyes they certainly are. They are looking to invest, if they are not actually investing money in Python, they are investing their reputation and liveliehood and if we expect them to use Python we should respect that this is their outlook. If we want to reject this sort of opportunity then fine but the outomce of the marketing python discussions didn't agree. If you have usability issues with the site design please provide them. The issues of font size and contrast have been addressed. David Mertz said: >Y'know... I would have thought the prior note would give you a little clue >about why it's not such a good idea to write notes that do nothing but try >to antagonize me. I'm not vindictive, but I -am- influential. I am certainly not trying to be antagonising, and I didn't think I was, I was merely reacting to some unfounded criticisms of the design I'd put forward. If I seem to have been a little over the top then I apologise profusely but as you can imagine the reaction to 8 weeks of hard work that had been put in by quite a few people. Comments like the one you have made just make me realise how much time we've all wasted. If you are this influential then I shall stop working on the redesign and let someone you like carry on. Tim From tzot at sil-tec.gr Tue Sep 30 10:29:56 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 17:29:56 +0300 Subject: append special chars with "\" References: <3f793544$0$64721@hades.is.co.za> Message-ID: <5o4jnvs04brbir8850q3vc1f8phcth0kjo@4ax.com> On Tue, 30 Sep 2003 13:33:31 +0200, rumours say that Gerrit Holl might have written: >for c in chr: > str = str.replace(c, r"\c") Perhaps you meant: for c in chr: str = str.replace(c, r"\%s" % c) otherwise all characters in chr would change into a literal 'backslash-c'... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From http Tue Sep 30 19:51:15 2003 From: http (Paul Rubin) Date: 30 Sep 2003 16:51:15 -0700 Subject: getting values from an "exec" statement References: Message-ID: <7xr81xx2bw.fsf@ruckus.brouhaha.com> Python isn't really set up for what you're doing. The exec'd code can too easily mess around with the calling code, if it's malicious. You're best off just running the student's program in a separate process and capturing the output. From __peter__ at web.de Tue Sep 23 18:17:54 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 24 Sep 2003 00:17:54 +0200 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> <299f1138.0309230818.22bc9bf6@posting.google.com> Message-ID: Martin v. L?wis wrote: > Peter Otten <__peter__ at web.de> writes: > >> Looking into stringobject.c (judging from a first impression, >> unicodeobject.c has essentially the same algorithm, but with a few >> indirections): > > You are mistaken. The implementation in unicodeobject.c is > fundamentally different. The byte string implementation uses the C > library, the Unicode implementation uses the Unicode character > database. So the former cannot be changed, whereas the latter could, > in theory, be extended to use additional data. I followed the code to fixupper() which operates on a preallocated unicode object and thus cannot cope with a string that expands while being transformed. I didn't actually resolve the macros. While we are at it, would it be viable to "abuse" the encoding/decoding mechanism to do case conversions? Peter From __peter__ at web.de Sun Sep 21 07:17:37 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 21 Sep 2003 13:17:37 +0200 Subject: How to catch socket timeout? References: Message-ID: Achim Domma wrote: > I'm using Python 2.3s timeout sockets and have code like this to read a > page from web: > > request = ... > self.page = urllib2.urlopen(request) > > and later: > > try: > self.data = self.page.read() > except socket.error,e: ... > except socket.timeout: ... > except timeout: ... > > but none of these excepts catches the the timeout while reading the data. > I still get the following exception, which I cannot handle: socket.timeout is a subclass of socket.error, so the timeout exception should be caught by the first except clause. However, I could reproduce your uncaught exception with the following minimalist code: from urllib2 import urlopen import socket slowurl = "http://127.0.0.1/timeout?delay=100" socket.setdefaulttimeout(1) data = urlopen(slowurl) try: data.read() except: # should catch ANY exception print "Timeout raised and caught" # this never shows So it seems there is *no* way to catch the error. I think you should file a bug report. Peter From donn at u.washington.edu Fri Sep 26 19:13:49 2003 From: donn at u.washington.edu (Donn Cave) Date: Fri, 26 Sep 2003 16:13:49 -0700 Subject: safely closing a socket? References: Message-ID: In article , "Russell E. Owen" wrote: > I've been doing some socket programming with threads and am confused how > to safely shut down a connection. > > First of all, using the file-like object returned by urllib to do ftp > file download (Python 2.3, MacOS X), I can hang the process by: > - using one thread to read the file-like object > - trying to close the connection in the main thread (while still > downloading) > it's not clear to me what's hung, but it just sits there. No major CPU > cycles being eaten. Some kind of deadlock, perhaps??? > > I've worked around the problem by setting a flag and having the read > thread quit. But this can take quite awhile. Is there some fast safe way > to terminate such a download? > > Also, is this more generally an issue with sockets? Is it dangerous to > close a socket while another thread may be reading or writing it? Greetings, Russell! It depends on the platform. Casual experiment with two variations - 1. child thread in socketobject.recv(), parent calls socketobject.close() MacOS X: recv returns '' FreeBSD 5.1: recv raises exception (errno EBADF) Redhat Linux 7.2: recv continues 2. child thread in socketobject.makefile('r').read(), parent calls socketobject.close() MacOS X: read continues FreeBSD 5.1: read continues Redhat Linux 7.2: read continues, program doesn't exit So there seems to be an incentive to avoid the file object thing, but you couldn't depend on that working on every possible platform (e.g., Linux.) One sort of deluxe option would be an inter-thread communications channel, probably a pipe, that the child thread reads along with its socket, via select(). It won't interrupt a recv actually in progress, transferring data, but ordinarily the intent is to abort it when it would be waiting for more data. This doesn't work well with fileobject I/O, has to be system level posix.read or socketobject.recv. Donn Cave, donn at u.washington.edu From janeaustine50 at hotmail.com Wed Sep 3 11:13:11 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 3 Sep 2003 08:13:11 -0700 Subject: Tkinter Text widget getting too slow Message-ID: As you add more items, say text lines, in Text widget, it gets too slow and almost impractical to use on. Take idle for example. If the text gets bigger(e.g. print urllib.urlopen('http://www.amazon.com').read() ), it becomes too sluggish to use as an "interactive" shell. I have tried wxPython and it seems to have the same problem (from my experience using PyCrust). Is there any way to speed up Text widget, or should I look for another GUI library? Jane From tim at lesher.ws Wed Sep 3 05:36:15 2003 From: tim at lesher.ws (Tim Lesher) Date: 3 Sep 2003 02:36:15 -0700 Subject: what's wrong with REBOL? References: <6005702b.0309020727.4ba46e78@posting.google.com> Message-ID: Jeff Epler wrote in message news:... > On Tue, Sep 02, 2003 at 09:03:17PM +0000, Christopher Browne wrote: > > "What's wrong" is that 'proprietary nature.' If I write code in Perl, > > Python, or Ruby, I can be certain that I won't get bitten because of > > someone pulling the rug out from under them. > > > > I can't be certain in the same way of the perpetual availability of > > REBOL. > > Of course, it's also possible that it might become impossible to use > "non-proprietary" software. Yes, but any of the apocalyptic situations you mention could happen equally well with proprietary software, and comparing the complexity of portion X10 to that of porting Python (or a similarly-sized, well-factored language) is ridiculous. The gamut of things that would make you completely lose your investment in the language is non-zero with open source languages like Perl or Python, but it's definitely smaller than with proprietary ones like REBOL. On that note, I tried REBOL a few years ago, just before trying Python. I found it an amazing language, but I settled on Python for exactly this reason. Since then, I've found the Python community to have grown significantly, while the REBOL community has not. I don't think that's a coincidence. -- Tim Lesher tim at lesher.ws From tjreedy at udel.edu Mon Sep 29 11:28:56 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2003 11:28:56 -0400 Subject: isNumber? check References: Message-ID: "Rob Hunter" wrote in message news:mailman.1064844761.11275.python-list at python.org... > How do I check if a value is a number in Python? > > One way is (x == type(1)) and (x == type(1.2)) and (x == > type(2387482734274)) and ... > > but this seems kludgy. Any better way? type(x) in (int, long, float, complex) # or, isinstance(x, (int, long, float, complex)) # now preferred, I think But how about x=x-0? This also accepts a user-defined number-class instance. This option gets to the point that 'number' is not exactly defined in either Python or mathematics. So checking for 'numberness' may or may not be what you need . Terry J. Reedy From ask at me.com Wed Sep 24 01:57:25 2003 From: ask at me.com (Greg Krohn) Date: Wed, 24 Sep 2003 05:57:25 GMT Subject: float problem References: Message-ID: <9nacb.1214$NX3.946@newsread3.news.pas.earthlink.net> "Indigo Moon Man" wrote in message news:bkrai0$50pag$1 at ID-70710.news.uni-berlin.de... > for the formula J = I / (12 * 100) where I is low (like about 8 to 15) I > get 0. But when I do it with a calculator it's actually .008333 for example > if I were 10. Is there a way I can get python to recognize the .008333 > instead of it just giving me 0? > > TIA for your help! > > -- > Audio Bible Online: > http://www.audio-bible.com/ > Normally division with integers gives an integer result losing everything after the decimal. Couple of things you can do about that, but basically you have to convert your denominator or divisor to a float before you divide: J = I / float(12 * 100) or J = float(I) / (12 * 100) Alternativly you could use 12.0 instead of 12 (or 100.0 instead of 100 for that matter) J = I / (12.0 * 100) or J = I / (12 * 100.0) And last, but not least, you can import from future to make all division "lossless": from __future__ import division J = I / (12 * 100) I personally prefer the first one, but they will all work fine. greg From tjreedy at udel.edu Sat Sep 6 12:26:43 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Sep 2003 12:26:43 -0400 Subject: Why python??? References: <8Um6b.34442$R32.1077180@news2.tin.it> Message-ID: "Alex Martelli" wrote in message news:8Um6b.34442$R32.1077180 at news2.tin.it... > for a really wide range of tasks. A language we're developing at > AB Strakt as part of the CAPS framework, for example, looks like...: > > attribute salary is Currency > "Salario mensile" > restriction quantity(1) > > on create code Python > if value[0] < minimumSalary: > value = [ minimumSalary ] > return value > %% My reflexive reaction was 'ugh'. My considered reaction is 'bravo'. You have avoided the 'ghetto trap' that I think too many mini-languages fall into by trying to be more or less turing-complete with a proprietary syntax useless for any other task. The Python 'humancode' fits pretty seamlessly into the declaration framework for two reasons: the common use of significant indentation and the semi-natural (versus chicken-scratch) look of Python. > etc -- now THAT is a higher-level language than Python, and it's > a dream to use for directly transcribing into executable code the > results of ERD analysis for typical business applications to be > deployed as multi-layer clients/middleware/server distributed apps; If your declaration form requires overall noticeably fewer written lines than the Python translation, then I probably could learn to like it too. ... > suited. Note that this language uses Python as its lower-level > embedded language; indeed the whole VVHL (very-very high-level) > program gets compiled into Python (by a Python-coded compiler, of > course) and executed as Python (by a Python-coded middleware, of > course -- resting on top of a very special Python-coded OODB and > feeding clients such as GUI ones, Web apps, and batch scripts -- > all typically coded, of course, in Python). I am curious: Will the CAPS marketers reveal or hide the fact that the readable procedural sublanguage is a *real* language that CAPS users can potentially use outside the CAPS box? Terry J. Reedy From aleax at aleax.it Thu Sep 4 09:18:42 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 04 Sep 2003 13:18:42 GMT Subject: Arguments of function as out References: Message-ID: Birgit Rahm wrote: > Hallo Alex, > I hope this posting is near to the netiquette. Perfect, thanks! >> Birgit, you do not seem to have *READ* the answer to which you are >> replying. > I dont understood this in the you described it. > >> >> * If there is more than one result value, all of them are packed into >> >> a >> >> tuple, and this tuple is returned. > I've read this, but I thought that this tuple is returned with the > return statement. I am new to python and I never seen such > a constract: The code that implements this CORBA spec (if it is Python code -- it is quite possible to implement CORBA brokers in Python, and it has been done) will quite likely use the return statement for this, yes, of course. But when you CALL the code, you don't need to worry whether it uses a return statement or some other black magic: you can code your call AS IF the code you called was Python code that uses a return statement for the tuple, e.g. def X(): return 23, 42, 69 therefore you call it as, e.g.: a, b, c = X() would set a to 23, b to 42, c to 69. (You need to know how many items are in the tuple X returns, to use this kind of assigment which is called "unpacking assignment", because you need to list exactly that number of targets on the left of the = sign). > I have had only the IDL and the py File from the IDL, > were stand take *args and return the return value. > In none of my python books such a construct is described. I'm sorry. > > Thanks for helping me, No problem, and you're welcome. I do understand that Python books don't say much about Corba (I didn't myself in the Nutshell, and there is just one very simple example in the Cookbook which does not cover the cases of out and inout parameters). But if the books don't cover *args and/or return-value packing and unpacking, then you might want to get better books;-) Alex From mal at lemburg.com Tue Sep 23 08:25:00 2003 From: mal at lemburg.com (M.-A. Lemburg) Date: Tue, 23 Sep 2003 14:25:00 +0200 Subject: DB2 driver for windows In-Reply-To: <3f6f6c4c$0$1115$6c56d894@feed0.news.be.easynet.net> References: <3f6cc89b$0$1122$6c56d894@feed0.news.be.easynet.net> <3f6f6c4c$0$1115$6c56d894@feed0.news.be.easynet.net> Message-ID: <3F703B9C.3000701@lemburg.com> Philip wrote: > Dave Benjamin wrote: > > >>In article <3f6cc89b$0$1122$6c56d894 at feed0.news.be.easynet.net>, Philip >>wrote: >> >>>i'am looking for a db2 driver for windows >>>the DB2 servers runs on as400 if that makes any difference. >> >>I don't know if you're looking for a native driver, but if you can work >>with ODBC, I was able to get DB2's ODBC driver (the one that comes with >>the DB2 client installation) to talk to the mx.ODBC module. >> >>http://www.egenix.com/files/python/mxODBC.html >> > > Currently i'am using jython for database administration (because didn't find > an native driver) > > I like the java jdbc driver because you don't need to install anything > especialy interesting when sharing code) > > But the downside is that you have the java tiresome api. the obvious reason > way i have choicen python/jython. > > Well, prefer a native one but if it's easy to install the odbc driver > that would be fine too. FYI, mxODBC works fine using the IBM DB2/400 driver for Linux: http://www-1.ibm.com/servers/eserver/iseries/linux/odbc/ -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Sep 23 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From bdesth.nospam at removeme.free.fr Sun Sep 28 18:26:07 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2003 00:26:07 +0200 Subject: [joke] Any tool to translate PHP to Python? In-Reply-To: References: <3f75f5b8$0$20650$626a54ce@news.free.fr> Message-ID: <3f775d15$0$20178$626a54ce@news.free.fr> Bruce Dickey wrote: > Bruno Desthuilliers wrote: > >> Bruce Dickey wrote: >> >>> Hi, >>> >>> I have some PHP scripts I'm moving from my web server to the local >>> PC. They just do file manipulation. >>> >>> Anybody know of a tool for translating PHP to Python? >> >> >> >> Er... What about a programmer ?-) >> >> (sorry, could not resist) >> Bruno >> > > Heh heh. Point taken. I actually *was* assuming I would be the tool -- > I've been around Python long enough to have seen most of the resources > for desktop apps. > > But Python web scripting I have not gotten into or read much about. It > appears to me that Python is increasing in popularity, not only on the > desktop, but also on the web server. > > It seems to me that for folks migrating from PHP to Python, a translator > would be a handy tool. Especially if they have a large site to convert. May be, but to which of the numerous Python-based dynamic web page generation / web framework / web application server would you convert your php source ? Bruno From peter at engcorp.com Thu Sep 11 07:41:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Sep 2003 07:41:53 -0400 Subject: 1.5 vs. 2x - build problem References: <7af2fd5c1a70e3c6ce4fe1f8eee39b9b@remailer.frell.eu.org> Message-ID: <3F605F81.7D6B32A3@engcorp.com> Fritz Wuehler wrote: > > I downloaded a tarball which doesn't compile. The error message says I > need python 2x but all I have is 1.5. Can I fix the compatability > problem and get it to work on 1.5? That's a good question... since you haven't told us what program the tarball actually is, the answer to the question depends entirely on your own programming abilities... Have you tried checking the source or a README or CHANGES file to see what it says about the reasons for requiring 2x? -Peter From amartin at traza-si.com Tue Sep 16 07:22:35 2003 From: amartin at traza-si.com (Aurelio Martin Massoni) Date: Tue, 16 Sep 2003 13:22:35 +0200 Subject: object.attribute vs. object.getAttribute() References: Message-ID: Read this nice article "Why getter and setter methods are evil: Make your code more maintainable by avoiding accessors" http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html "Roy Smith" escribi? en el mensaje news:roy-81B3E5.20291015092003 at reader2.panix.com... > For the past 6-8 months, I've spent most of my time writing C++ and a > little bit of Java. Both of these languages support and encourage the > use of private data and explicit accessor functions, i.e. instead of > writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to > writing Python, I find myself in a quandry. > > Historically, I've always avoided accessor functions and just reached > directly into objects to get the value of their attributes. Since > Python doesn't have private data, there really isn't much advantage to > writing accessors, but somehow I'm now finding that it just feels wrong > not to. I'm not sure if this feeling is just a C++/Java-ism that will > cure itself with time, or if perhaps it really does make sense and I > should change the way I code. > > On the plus side, accessors/mutators give me: > > 1) Implicit documentation of which attributes I intended to be part of > an object's externally visible state (accessors). > 2) Hooks to do data checking or invarient assertions (mutators). > 3) Decoupling classes by hiding the details of data structures. > 4) Vague feeling that I'm doing a good thing by being more in line with > mainstream OO practices :-) > > On the minus side: > > 1) More typing (which implies more reading, which I think reduces the > readability of the finished product). > 2) Need to write (and test) all those silly little functions. > 3) Performance hit due to function call overhead. > 4) Only the appearance of private data (modulo some slots hackery). > 5) Code is harder to change (adding functionality means going back and > adding more slots). > 6) Vague feeling that I'm dirtying myself by letting C++ and Java change > my Python coding habits :-) > > Comments? From aleax at aleax.it Fri Sep 5 05:49:00 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 09:49:00 GMT Subject: Embedded Perl or Python (XPost) References: Message-ID: Chris wrote: ... > So if I call vfunction(); and an add on has been written that redefines > this function (and possibly calls the base c++ function) that it is > called correctly. > > I have chosen perl and python as my preferred languages because of the > large developer base for add ons > > The interpreter will only have a subset of the standard funtionality, for > example sockets will be removed. > > QUESTION > > Given the above which interpreter is most likely to fit my bill with the > smallest footprint ? No idea about "footprint", partly because it so crucially depends on what you will or won't remove. But trying it out for benchmark and measurement is trivially easy for Python -- use Boost Python, which you get from www.boost.org, and the "subclassing C++ in Python with the possibility of overriding virtual functions" functionality is there. Assuming it's just as easy for Perl (sorry, no idea), trying it for both languages and measuring footprint should fit comfortably within an afternoon with ample time left over for tea;-). Alex From skip at pobox.com Tue Sep 2 15:04:20 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 2 Sep 2003 14:04:20 -0500 Subject: MySQLdb -- any way to get "rows matched"? In-Reply-To: References: Message-ID: <16212.59828.291356.709883@montanaro.dyndns.org> mysql> UPDATE example SET AGE=30 WHERE AGE=30; Sheila> Query OK, 0 rows affected (0.00 sec) Sheila> ws matched: 2 Changed: 0 Warnings: 0 Sheila> MySQLdb in Python: >>>> c = conn.cursor() >>>> c.execute("""UPDATE example SET AGE=30 WHERE AGE=30;""") Sheila> 0L >>>> c.messages Sheila> [] >>>> c.info() Sheila> '' Sheila> Being a MySQL and MySQLdb newbie, I'm not sure if there is any Sheila> way to find out how many matched, via Python's MySQLdb module. I Sheila> thought, from the source code, that .messages or .info() for the Sheila> cursor attributes/methods might do it, but apparently not??? I'm not sure what the return value means when executing an update. My guess is that it returns the number of rows changed. If you want to know the number of rows matched, execute a SELECT which matches your WHERE clause: >>> db = MySQLdb.Connection(...) >>> c = db.cursor() >>> c.execute("select * from cities where city='San Jose'") 4L >>> c.execute("update cities set city='San Jose' where city='San Jose'") 0L Skip From SBrunning at trisystems.co.uk Thu Sep 25 11:07:12 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Thu, 25 Sep 2003 16:07:12 +0100 Subject: Help with dialog box Message-ID: <31575A892FF6D1118F5800600846864D014B299D@intrepid> > From: secun at yahoo.com [SMTP:secun at yahoo.com] > Is there a way to have Python set focus on the dialog box and click OK > so my script can continue? See , , and for a series of articles on this sort of thing. Cheers, Simon Brunning. --LongSig ----------------------------------------------------------------------- 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 interstar at postmaster.co.uk Fri Sep 19 16:02:35 2003 From: interstar at postmaster.co.uk (phil) Date: 19 Sep 2003 13:02:35 -0700 Subject: python cgi problem with method = post Message-ID: This is a quick plea on something that has me stumped. I have a python script importing "cgi" I developed my script on a local machine using method = get for uploading form data. My code worked locally and on the hosting service I'm using. I changed to using method = post On my local machine this change works transparently. On my hosting service's machine, all the values that the form returns to the script are now empty. So, I don't expect anyone to be able to answer this ... but what *kind* of thing should I be looking for? Is it to do with versions of python (2.1.3 locally, 2.2 remotely) or "cgi"? Or the webserver (I'm using Apache on Debian locally, I suspect my host is Apache on Red Hat 7.1) Is it something I haven't thought of? cheers phil jones From aleax at aleax.it Mon Sep 22 09:35:31 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 13:35:31 GMT Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale related?)) References: Message-ID: Peter Otten wrote: > Jeff Epler wrote: > >> If this did work, then you can use the DSU pattern like so: >> >> decorated_wordlist = [(locale.strxfrm(w), w) for w in wordlist] >> decorated_wordlist.sort() >> wordlist[:] = [i[1] for i in decorated_wordlist] > > Everytime that someone posts a naive list.sort(compare), the DSU pattern > is proposed to improve execution speed. > > So maybe it's about time to change the sort() method to support a second > argument > > list.sort(compare=None, mapping=None) > > that, if provided, would perform the DSU magic. Or was that already > proposed and rejected? I have not seen this proposed before, and I'm not very clear on what the "compare" and "mapping" arguments are supposed to be in order to let you specify any DSU. Basically it seems you would need two callables, "decorate" to be called with each item in the list (to return for each item the decorated tuple) and "undecorate" to be called with each decorated tuple after the sort (to return the item for the result). How do you turn that into "compare" and "mapping"? Alex From axel at straschil.com Wed Sep 10 03:58:10 2003 From: axel at straschil.com (Axel Straschil) Date: Wed, 10 Sep 2003 09:58:10 +0200 Subject: Codesample for xml/xslt transforming In-Reply-To: <3F5ECF7B.5070404@mxm.dk> References: <871xupg5uk.fsf@pobox.com> <3F5ECF7B.5070404@mxm.dk> Message-ID: Hallo! > Have you used the page templates in Zope? They really are a thing of beauty. Yes, zope's page templates are good. I've two site's where I'm using them. My point of interest is: If your are coding the html-output of a website with dtml/pt in Zope or php, you've got the problem that: - The webdesigner has to dig in your source - You must code your program like the html-code is comming, not the data With the last point, I mean that that a html-page ist codet top down, and so dtml/pt are parest from the top to the bottom. Imagine I'm fetching an Article from via the network from an remote server, the Article has an caption and an content. I want to show the caption in the title-tag of the header, and the article somewhere nested in the body. With dtml/pt, I must either access the remote article server twice, or make a funny variable definition construktion. Not very nice! If my output ist not html, it's xml, a can make an data-orientated output, not design orientated. Maybe dtml/pt is used to produce that xml-code, who cares. The webdesigner is starting at the OUTPUT of the xml-code, he is just seeing that (dynamic modifing) xml-code, he's never digging my source. So, the last thing ist to convert that data-orientated xml to designers xhtml. It's like taking pieces of data from the xml and placing them on the webpage. No funking programming, yust templaging. I think for that, XSLT ist a good thing. But I'm just starting, maybe, in one or two weeks, I'll shredder all that X-Files, or maybe I'll love them ;-) -- Lg, Axel. ____________________________________________________ /_\ Tel: +43(699) 145 09 210 /|_ \xel Fax: +43(699) 445 09 210 _|traschil eMail: axel at straschil.com Public Key: http://www.kosnet.com/pgp-public-key.txt Keyserver: http://www.keyserver.net From theller at python.net Thu Sep 18 06:14:27 2003 From: theller at python.net (Thomas Heller) Date: Thu, 18 Sep 2003 12:14:27 +0200 Subject: Checking if the computer is online References: Message-ID: Mickel Gr?nroos writes: > You wouldn't have some sample code on how I can use the socket module to > test if I can connect to a given URL? (I would't want to rely on other > modules than the ones in the standard library, so therefore I want to > try this socket approach.) Sorry, no. But it's easy to figure out yourself. Thomas From eppstein at ics.uci.edu Tue Sep 23 13:01:16 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 23 Sep 2003 10:01:16 -0700 Subject: Bottleneck? More efficient regular expression? References: <3f7069db_4@corp.newsgroups.com> Message-ID: In article <3f7069db_4 at corp.newsgroups.com>, "Tina Li" wrote: > I've been struggling with a regular expression for parsing XML files, > which keeps giving the run time error "maximum recursion limit > exceeded". Why not use a real XML parser? xml.parsers.expat is easy enough to use, doesn't have problems with recursion limits, and will continue working when someone generates a valid XML file in a slightly different version than the one you expect. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From gerrit at nl.linux.org Tue Sep 23 11:33:23 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 23 Sep 2003 17:33:23 +0200 Subject: load changes of subclasses In-Reply-To: References: Message-ID: <20030923153323.GA4145@nl.linux.org> Tom wrote: > Date: Tue, 23 Sep 2003 16:56:55 +0200 > > Hi, > > I have a main program that uses a lot of definitions in different classes. > They are included like this: > from subclass1 import * > from subclass2 import * Note that 'subclass1' and 'subclass2' are not classes, but modules. A class is created with the 'class' statement: class MyClass: def method(self): return "Hi there!" A module is a file in the library. > My problem is: whenever I make changes in one of the classes I have to > close and reopen the main program for the changes to take effect. This > is kind of annoying, because I always want to test if my changes are > correct and that's why I have to run the main program. Is there some > kind of a shortcut where I don't have to close and reopen the main program? You can use the reload() function for that: >>> print reload.__doc__ reload(module) -> module Reload the module. The module must have been successfully imported before. > I hope this question is not too stupid, but I am still quite new to Python. Stupid questions do not exist (hm, my first post here makes me think otherwise), stupid answers do, so: I hope this answer is not too stupid, but I am not a Computer Scientist. yours, Gerrit. -- 241. If any one impresses an ox for forced labor, he shall pay one-third of a mina in money. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From martin at v.loewis.de Mon Sep 22 16:30:29 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 22 Sep 2003 22:30:29 +0200 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> Message-ID: Peter Otten <__peter__ at web.de> writes: > # The German es-zed is special--the normal mapping is to SS. > # Note: the titlecase should never occur in practice. It is equal to > titlecase(uppercase()) > > 00DF; 00DF; 0053 0073; 0053 0053; # LATIN SMALL LETTER SHARP S > [...] > > Thus, to comply with the standard, "?".upper() --> "SS" is required. No. It would be required if .upper would claim to implement SpecialCasing - but it makes no such claim. > My personal impression is that, even before the orthography reform in 1998, > the SZ variant was seldom used. There is, of course, the famous "MASSE oder MASZE" example, in particular in the form "WIR TRINKEN BIER IN MASSEN". Regards, Martin From martin at v.loewis.de Sat Sep 6 12:07:14 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 06 Sep 2003 18:07:14 +0200 Subject: Standard Lib To Use New-Style Classes? References: Message-ID: John Abel writes: > A while back, I saw a thread asking if the standard lib modules would > be modified to use the new logging module, and it got me thinking. As > the new-style classes will be default for 2.4, will the standard lib > modules be modified accordingly? Who says newstyle classes will be the default in 2.4? Patches in the direction of using newstyle classes more frequently are probably encouraged, provided they demonstrate that they preserve reasonable backwards compatibility. Regards, Martin From colarte at telesat.com.co Tue Sep 23 04:09:49 2003 From: colarte at telesat.com.co (Camilo Olarte) Date: Tue, 23 Sep 2003 03:09:49 -0500 Subject: "Protected" property in Python? In-Reply-To: <1rgll5pslncci.1iu0qs9ekf45q.dlg@40tude.net> References: <1rgll5pslncci.1iu0qs9ekf45q.dlg@40tude.net> Message-ID: <20030923030949.7aeccd48.colarte@telesat.com.co> On Mon, 22 Sep 2003 23:22:44 -0600 Jules Dubois wrote: > I'm want to create a superclass with nothing but attributes and properties. > Some of the subclasses will do nothing but provide values for the > attributes. > (I'd also like to make sure (1) that the subclass provides actual values > for the attributes and (2) that no "client" module adds or removes > attributes or properties, but I don't know how to do those.) > I don't understand what I'm doing wrong, or maybe what I want to do is > impossible. Here's a stripped down version of the code: Question : why didn't you initialize your super class???? if you do it passing the values you want as arguments then you could have a code like : #! /usr/bin/python class SuperClass(object): def __init__(self,stat_code): # self.__statusCode = "value bound in SUPERCLASS" self.__statusCode = stat_code getStatusCode = property(lambda self: self.__statusCode) class SubClass(SuperClass): def __init__(self): self.__statusCode = "value bound in SUBCLASS" SuperClass.__init__(self,self.__statusCode ) if __name__ == "__main__": s = SubClass() print s.getStatusCode print try : print s.__statusCode except : print "cannot do that.. print s.__statusCode" where you don't have private attributes visible and yet you have the values you passed from the subclass.. NOTE : later on accessing those values from your sublass other than from the SuperClass initialization is other story...(setattribute,getattribute...or self.functions) In your local python documentation.. read the tutorial section on classes: /python2.2-doc/html/tut/node11.htm From claird at lairds.com Sat Sep 27 11:24:21 2003 From: claird at lairds.com (Cameron Laird) Date: Sat, 27 Sep 2003 15:24:21 -0000 Subject: Access to database other web sites References: <87n0crbi8z.fsf@pobox.com> Message-ID: In article <87n0crbi8z.fsf at pobox.com>, John J. Lee wrote: >tibi87 at hanmail.net (Jenny) writes: > >> I am doing research about realationship between sales rates and >> discounted prices or recommendation frequency. To do this, I need to >> access the database of commercial web sites via internet. I think this >> is possible because it it simmilar to the work of price comparison >> sites and web robot. > >IIUYC, what you're contemplating is called "web scraping" -- at least, >it is by Cameron Laird, and I like the name. Others might know it as >"web client programming". Cameron wrote an article about this a while >back (Unix Review?) which you might like if you're a newbie -- Google >for it (but note that the Perl book he mentions has actually been >replaced by a newer one by Sean Burke, also from O'Reilly). > > >> I am studying python these days because I thinks it is a good language >> for the work. >[...] > >I think so too. . [excellent and detailed technical advice] . . Also filling a niche in this territory is PyCurl . The references at are likely to be at least inspirational. I'm ... reserved about the prospects for the proposed research. The commercial sites you want to study are, in my experience, some of the most difficult to "scrape". Complementing that difficulty is the poverty of inference I antici- pate you'll be able to ground on what you find there; their commerce has a lot more noise than signal, as I see it. 'Twould be great, though, for you to uncover something real. Good luck. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From bokr at oz.net Fri Sep 5 20:52:55 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Sep 2003 00:52:55 GMT Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <3f59014d$0$152$a1866201@newsreader.visi.com> <3f591d28$0$175$a1866201@newsreader.visi.com> Message-ID: On Fri, 5 Sep 2003 20:15:00 -0400, "John Roth" wrote: [...] >If you don't have to write "self" as the first parameter of a method, >that reduces the complexity. Everything else remains the same. > Except for cases where two self-parameters are visible at the same time, and both are used in an inner scope and must be distinguished by giving them different names. ISTM you'd have to turn off some dynamic capabilities of python to make "self" implicit. (An example came up in a past discussion, some time ago). Regards, Bengt Richter From fgeiger at datec.at Tue Sep 30 05:07:28 2003 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 30 Sep 2003 11:07:28 +0200 Subject: [PMW 1.2] Dialog controls vanish upon editing Message-ID: <3f794786@news.swissonline.ch> Hi all, I use PMW 1.2 on Python 2.3.0 on Win2k. I've created a dialog that looks like so: +----------------------+ Name | | +----------------------+ +----------------------+ Caption text head | | +----------------------+ +----------------------+ # Digits w/o sign | | +----------------------+ +----------------------+ Caption text tail | | +----------------------+ +--+ Is editable | | +--+ +--------------------+-+ Parameter name | |V| Drop-down. +--------------------+-+ I pull down the drop-down control, select an item, the drop-down closes and - vanishes. All controls have vanished. After half a second or so the first one reappears, but w/o its label 'Name'. The other ones reapper if I click onto the pane where they are supposed to be. They also reapper if I change to an other app and then come back again. I guess this is because a window update is issued by the OS. What do I miss? Many thanks in advance and kind regards Franz GEIGER Code: class QCWidgetNumberEditor(_Editor): ''' +----------------------+ Name | | +----------------------+ +----------------------+ Caption text head | | +----------------------+ +----------------------+ # Digits w/o sign | | +----------------------+ +----------------------+ Caption text tail | | +----------------------+ +--+ Is editable | | +--+ +--------------------+-+ Drop-down. Offers only existing Parameter name | |V| parameters, i.e. you have to first +--------------------+-+ create at least one parameter. ''' def __init__(self, parent, x, y, traits=None): _Editor.__init__(self, parent) self._pos = (x, y) self._traits = traits self._isEditable = Tkinter.IntVar(0) self._createAndPackEntryFields_() return def traits(self): return self._traits def _createAndPackEntryFields_(self): w = Tkinter.Label(self.interior(), pady = 20 ) w.pack(expand = 1, fill = 'both', padx = 4, pady = 4) parent = w # Create and pack the EntryFields. nameId = '' if self._traits: nameId = self._traits.name() self._tkwNameId = Pmw.EntryField(parent, labelpos = 'w', value = nameId, label_text = 'Name of number control:', validate = self._validateNameId_, modifiedcommand = self._onChangedNameId_, command = self._onNameId_ ) textDisplayed = '' if self._traits: textDisplayed = self._traits.textHead() self._tkwTextDisplayedHead = Pmw.EntryField(parent, labelpos = 'w', value = textDisplayed, label_text = 'Caption text head:', # validate = {'validator' : 'real', # 'min' : 10, 'max' : 99, 'minstrict' : 0 # }, modifiedcommand = self._onChangedTextDisplayedHead_ ) textDisplayed = '1' if self._traits: textDisplayed = str(self._traits.numDigitsExclSign()) self._tkwNumDigitsExclSign = Pmw.EntryField(parent, labelpos = 'w', value = textDisplayed, label_text = '# Digits w/o sign:', validate = {'validator' : 'integer', 'min' : 1, 'max' : 5, # 'minstrict' : 0 }, modifiedcommand = self._onChangedNumDigits_ ) textDisplayed = '' if self._traits: textDisplayed = self._traits.textTail() self._tkwTextDisplayedTail = Pmw.EntryField(parent, labelpos = 'w', value = textDisplayed, label_text = 'Caption text tail:', modifiedcommand = self._onChangedTextDisplayedTail_ ) if self._traits: self._isEditable.set(self._traits.isEditable()) else: self._isEditable.set(0) tkwIsEditable = Tkinter.Checkbutton(parent, variable=self._isEditable, text='Editable on target', command=self._onToggleIsEditable_ ) paramNames = Proxy.DataProxy().parameterNames() self._tkwParamName = Pmw.ComboBox(parent, labelpos = 'nw', scrolledlist_items=paramNames, label_text="Parameter name" ) i = 0 if self._traits: paramName = self._traits.parameterName() try: i = paramNames.index(paramName) except ValueError: pass try: self._tkwParamName.selectitem(Proxy.DataProxy().parameterNames()[i]) except IndexError: pass entries = (self._tkwNameId, self._tkwTextDisplayedHead, self._tkwNumDigitsExclSign, self._tkwTextDisplayedTail, tkwIsEditable, self._tkwParamName ) for entry in entries: entry.pack(fill='x', expand=1, padx=10, pady=5) Pmw.alignlabels(entries) self._tkwNameId.component('entry').focus_set() return def _execute_(self, event): if event == 'OK': nameId = self._tkwNameId.getvalue() textDisplayedHead = self._tkwTextDisplayedHead.getvalue() numDigits = int(self._tkwNumDigitsExclSign.getvalue()) textDisplayedTail = self._tkwTextDisplayedTail.getvalue() isEditable = self._isEditable.get() paramName = self._tkwParamName.get() if nameId and numDigits > 0 and paramName: param = Proxy.DataProxy().parameters(paramName) self._traits = QCWidgetTraits.QCWidgetNumberTraits(nameId, self._pos[0], self._pos[1], textDisplayedHead, numDigits, textDisplayedTail, isEditable, paramName ) self.deactivate() return def _onChangedTextDisplayedHead_(self): text = self._tkwTextDisplayedHead.getvalue() return def _onChangedNameId_(self): return def _onChangedNumDigits_(self): text = self._tkwNumDigitsExclSign.getvalue() return def _onChangedTextDisplayedTail_(self): text = self._tkwTextDisplayedTail.getvalue() return def _onToggleIsEditable_(self): return def _onNameId_(self): return def _validateFunName_(self, text): return 1 # 2DO def _validateNameId_(self, text): if Proxy.DataProxy().parameterExists(text): return -1 return 1 From ndalton at lastminute.com Wed Sep 17 07:06:34 2003 From: ndalton at lastminute.com (Niall Dalton) Date: Wed, 17 Sep 2003 12:06:34 +0100 Subject: Wrapper for libevent? Message-ID: Hello, Has anyone already wrapped libevent for use in Python? Regards, niall From mertz at gnosis.cx Tue Sep 30 17:19:58 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 30 Sep 2003 17:19:58 -0400 Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> Message-ID: <+Nfe/kKkXkJT092yn@gnosis.cx> Taking up Bengt's suggestion, and some various others, I created a bit array version of the primality data structure. That is, each bit of the file 'primes.bitarray' encodes the primality of the number corresponding to its bit position. However, only ODD numbers are mentioned in this file, since it's rather easy to rule out evens (and special case 2). This produces a 6.25 mB file for the first 10**8 numbers. I was disappointed that gzip only reduces the size by 41%. I would have guessed better, given the predominance of 0 bits. Still, no reason not to use the [gzip] module to read the data. You can download the data file, if you wish, at: http://gnosis.cx/download/primes.bitarray.gz I decided to check how quickly I can check primality using this data structure. Pretty well, to my mind (for reference, I have a PIII 733Mhz; nothing very fast for nowadays). Here's the code: #!/usr/bin/python import gzip bit_source = gzip.open('primes.bitarray.gz') prime_bits = bit_source.read(100000) def isPrime(N): "Check primality on pre-generated bit field (read more as needed)" if N < 2: return False elif N==2: return True elif not N % 2: return False else: # Check if we need to extend prime_bits global prime_bits if 8*len(prime_bits) < N: needed = 1+(N//8) - len(prime_bits) prime_bits += bit_source.read(needed) byte, bit = divmod(N, 16) bit = 7 - bit//2 return ord(prime_bits[byte]) & 2**bit if __name__=='__main__': from time import clock from random import randint # generate a million numbers to check tests = [] for _ in xrange(10**6): tests.append(randint(1,10**8)) start = clock() primes = 0 for n in tests: if isPrime(n): primes += 1 print "%d primes in 1e6 numbers (%.2f secs)" % (primes,clock()-start) Here's the timing: % test_bits.py 57546 primes in 1e6 numbers (29.57 secs) I figured there was no need to read the whole data file in unless a check required it--I just read in a smallish 100k at initialization. Of course, in the course of a million tests, I am pretty sure I wind up reading in essentially the whole file at some point. One nice thing to do would be to make 'bit_source' a bit smarter. I.e. it could be a class that generated more primes when needed (maybe using gmpy as Alex suggests). In principle, 'isPrime()' could then check unbounded primes (subject to time and resource constraints). The next thing would probably be to store sparce accumulations as Bengt suggested (and Alex implemented in a different fashion). That is, another structure could store "every 1000th prime" in order to answer questions like "how-many-less-than" and "which-is-Nth-prime". Maybe I'll Emile's bitcounting techniques to do this. Yours, Lulu... -- 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 oblivious at web.de Fri Sep 26 16:30:31 2003 From: oblivious at web.de (Dominic) Date: Fri, 26 Sep 2003 22:30:31 +0200 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) In-Reply-To: References: <3F71B857.2D1E3268@engcorp.com> <3F720759.34D7BD3E@engcorp.com> <3F720D28.83C3E99@engcorp.com> <3F731B17.61C17B3A@engcorp.com> Message-ID: <3F74A1E7.5040102@web.de> Well, first of all I agree with you that a more traditional approach using queues is better and more predictable. And yes on a single CPU machine I was thinking about stopping all "low priority" threads. This is somehow creaky and fragile but you don't need a thread per "task" as in your queue based alternative. So you could have 3000 "tasks" and one thread e.g. However every "task" would need to recover from it's injected exception which is kind of unpredictable and hard to program. I would not use such an architecture ;-) Now to the delay: from testx import interrupt from thread import start_new_thread,exit from time import sleep,ctime from sys import stdin,stdout def f(): try: while 1: sleep(1) print 'hi there', ctime() stdout.flush() except StandardError: print 'done: ',ctime() exit() tid=start_new_thread(f,()) sleep(1) print 'initiate:',ctime() interrupt(tid, StandardError()) print 'press any key' stdin.readline() result=""" [dh at hawk Python]$ python2.3 main.py initiate: Sat Sep 27 00:11:30 2003 press any key hi there Sat Sep 27 00:11:30 2003 hi there Sat Sep 27 00:11:31 2003 hi there Sat Sep 27 00:11:32 2003 hi there Sat Sep 27 00:11:33 2003 hi there Sat Sep 27 00:11:34 2003 hi there Sat Sep 27 00:11:35 2003 hi there Sat Sep 27 00:11:36 2003 hi there Sat Sep 27 00:11:37 2003 done: Sat Sep 27 00:11:37 2003 [dh at hawk Python]$ """ machine=""" Linux hawk 2.4.18-6mdk #1 Fri Mar 15 02:59:08 CET 2002 i686 unknown """ testx=""" # Pyrex version 0.8.2 cdef extern int PyThreadState_SetAsyncExc(long id, obj) def interrupt(id, obj): PyThreadState_SetAsyncExc(id, obj) """ As you can see it takes about 7 seconds until the exception is injected. Ciao, Dominic > > >>While playing with the new feature I noticed that it >>takes a long time (>3 seconds) until the exception is thrown. >>In contrast to the possibility to interrupt the main thread >>with interrupt_main which seems not to be delayed. > > > Hmmmm... care to show exactly the code you've been trying? > I get EXACTLY opposite results, as follows...: > > > import time > import thread > import threadex > > def saywhen(): > for x in xrange(100000): > time.sleep(0.1) > > def intemain(): > global when_sent > when_sent = None > time.sleep(1.0) > when_sent = time.time() > thread.interrupt_main() > time.sleep(1.0) > > im_delays = [] > for i in range(10): > tid = thread.start_new_thread(intemain, ()) > try: > saywhen() > except: > when_received = time.time() > im_delays.append(when_received - when_sent) > > def get_interrupted(): > global when_received > when_received = None > try: > saywhen() > except: > when_received = time.time() > > it_delays = [] > for i in range(10): > tid = thread.start_new_thread(get_interrupted, ()) > time.sleep(1.0) > when_sent = time.time() > threadex.threadex(tid, KeyboardInterrupt) > time.sleep(1.0) > it_delays.append(when_received - when_sent) > > main_id = thread.get_ident() > def intemain1(): > global when_sent > when_sent = None > time.sleep(1.0) > when_sent = time.time() > threadex.threadex(main_id, KeyboardInterrupt) > time.sleep(1.0) > > im1_delays = [] > for i in range(10): > tid = thread.start_new_thread(intemain1, ()) > try: > saywhen() > except: > when_received = time.time() > im1_delays.append(when_received - when_sent) > > > im_delays.sort() > im1_delays.sort() > it_delays.sort() > print 'IM:', im_delays > print 'IT:', it_delays > print 'IM1:', im1_delays > > > > > Module threadex is a tiny interface exposing as 'threadex' > the PyThreadState_SetAsyncExc function. And the results on > my Linux (Mandrake 9.1) box are as follows...: > > > [alex at lancelot sae]$ python pai.py > IM: [2.4993209838867188, 2.4998600482940674, 2.4998999834060669, > 2.4999450445175171, 2.4999510049819946, 2.4999560117721558, > 2.4999659061431885, 2.499967098236084, 2.4999990463256836, > 2.5000520944595337] > IT: [0.20004498958587646, 0.39922797679901123, 0.39999902248382568, > 0.40000700950622559, 0.40000808238983154, 0.40002298355102539, > 0.40002298355102539, 0.40002405643463135, 0.40003299713134766, > 0.40004003047943115] > IM1: [0.10003900527954102, 0.39957892894744873, 0.40000700950622559, > 0.40000796318054199, 0.40001499652862549, 0.40002000331878662, > 0.40003204345703125, 0.40003299713134766, 0.40004301071166992, > 0.40005004405975342] > [alex at lancelot sae]$ > > i.e., interrupt_main takes a very repeatable 2.5 seconds; > PyThreadState_SetAsyncExc typically 0.4 seconds, whether it's > going from main to secondary thread or viceversa, with occasional > "low peaks" of 0.1 or 0.2 seconds. Of course, it's quite > possible that there may be something biased in my setup, or > it may be a platform issue. But I'd be quite curious to > see the code you base your observation on. > > > Alex > From amk at amk.ca Fri Sep 5 12:20:06 2003 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 05 Sep 2003 11:20:06 -0500 Subject: How to override distutils install? References: Message-ID: On Fri, 5 Sep 2003 09:35:39 -0500, Skip Montanaro wrote: > I would like to override the distutils install class. It doesn't look like > it was designed for that. Do I have to import distutils.command and Supply a cmd_class argument to setup(), like this: setup(name = ..., cmdclass = {'build_py': qx_build_py}, ) qx_build_py is a Command subclass that will be used in place of the default build_py target. --amk From petitmermet at mat.ethz.ch Sat Sep 20 15:10:46 2003 From: petitmermet at mat.ethz.ch (Marc Petitmermet) Date: Sat, 20 Sep 2003 21:10:46 +0200 Subject: raw string Message-ID: I can do the following replacement: r"kr\xdf6;ger".replace('\\','&#') -> 'kr෶ger' But how can I do this using a variable which contains the above string? Obviously, the following code returns not the string with replacement but the name of the variable itself: name = "kr\xdf6;ger" r"name".replace('\\','&#') -> 'r"name" Sorry, if this is a stupid question but I have not found an answer so far (or I have been using the wrong keywords for searching). Thanks for any help. Regards, Marc From mpeuser at web.de Fri Sep 12 04:06:25 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 12 Sep 2003 10:06:25 +0200 Subject: Tkinter Canvas/Grid question References: Message-ID: "Gary Richardson" > Michael, Jeff, > > Thanks for your replies. I made the changes indicated above and the resizing > works just fine now. I'm still puzzled as to why pack() would be used with > the frame and grid() used with the canvas, and other widgets. No, no! I just use pack() because it is much simpler and you made no constraints as to how to show the frame in the toplevel.. There is a lot of useful information in that chapter from Nacy Welsh's book ..... > was under the impression that only a single geometry manager should be used > in a program. I guess the rule is: a single geometry manager must be used > within a frame and its descendants. Is that correct? Nearly. You can freely choose the g.m. in EVERY frame (but then stick to it in THAT frame) Kindly Michael P From fgeiger at datec.at Tue Sep 30 01:36:09 2003 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 30 Sep 2003 07:36:09 +0200 Subject: ANN Tkinter Calendar Widget References: Message-ID: <3f7915fd@news.swissonline.ch> Looks good. Wouldn't this be a good contribution to PMW? Regards Franz GEIGER "Camilo Olarte" schrieb im Newsbeitrag news:mailman.1064886460.11442.python-list at python.org... > If you ever need a calendar dialog in Tkinter , You can use mine: > http://pythonical.sourceforge.net/pyTkCalendar.html > Camilo Olarte > From cpl.19.ghum at spamgourmet.com Sat Sep 27 05:02:03 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Sat, 27 Sep 2003 11:02:03 +0200 Subject: monolith py2exe References: Message-ID: Max, > once we are on the topic, has there been any movement to do a monolith > option for py2exe (e.g. there is only one exe, no dlls necessary). this > is somewhat useful because the exe can be freely moved around without > worrying about the dlls. This would be a VERY GOOD THING. All the PYDs and DLLs and so on in ONE file. Yes, that would lead to 2-4 pythonXX.dlls in memory ... yes, all the other DLLs (wxPython...) would be more than one time in memory, and on disk... But: some compression added (UPX) the files would be of reasonable size (below 20MB), and distribution would become a charme. +1 for this wish Harald From aleax at aleax.it Mon Sep 22 08:49:24 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 12:49:24 GMT Subject: Problems with string and lists (searching and replaceing) References: Message-ID: jblazi wrote: > I should like to search certain characters in a string and when they are > found, I want to replace other characters in other strings that are at > the same position (for a very simply mastermind game) for my pupils. > > This very simple thing does not seem simple at all. > > If I use strings, I cannot replace their parts (though I can use > string.find for the searching). I think it is a bad idea that strings are > not mutable, but I suspect that this has been discussed here for ages. Not really (most of us appear to have no problems with immutable strings). And indeed I don't see what's complicated with your task, at all. Suppose the string you're "searching certain characters in" is held by variable "searched_string", the characters you are searching in (any sequence, list or other) variable "characters", the "other strings" are (e.g.) all the items of list "otherstrings", and finally the replacement characters are in dictionary "replacers" indexed by the found characters and with a default of say '*' when a found character is not a key in "replacers". Note that all of these or similar hypotheses are obviously needed whether strings are mutable or not. Now, if strings were mutable, the obvious solution (avoiding exceptions, as you asked) might be: for c in characters: where = searched_string.find(c) if where<0: continue replace_with = replacers.get(c, '*') for another in otherstrings: if where < len(another): another[where] = replace_with Now since strings are NOT mutable, you need to change this to: for c in characters: where = searched_string.find(c) if where<0: continue replace_with = replacers.get(c, '*') for i, another in enumerate(otherstrings): otherstrings[i] = another[:where] + replace_with + another[where+1:] i.e, keep track of the index and set there another string build of three parts -- preceding, replace_with, succeeding. In this case you do not have to ensure that where References: <3f53ad7e_5@corp.newsgroups.com> Message-ID: <3f53af79_5@corp.newsgroups.com> Paul D. Fernhout wrote: > Thanks for the pointer to e4graph. I found more info about it here: > http://www.marshallbrain.com/robotic-freedom.htm Oops, sorry, I had the wrong url in my cut&paste buffer and didn't do not enough proofreading. The (incorrect, and unrelated) URL I posted came from this recent Slashdot article: http://slashdot.org/article.pl?sid=03/08/31/182228&mode=thread on the future of jobs given robotics. The correct URL for the e4graph introduction I quoted is: http://www.e4graph.com/e4graph/e4graphintro.html --Paul Fernhout http://www.pointrel.org -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From abuseonly at sgrail.org Thu Sep 4 18:37:38 2003 From: abuseonly at sgrail.org (derek / nul) Date: Thu, 04 Sep 2003 22:37:38 GMT Subject: Can't Open PY Files References: Message-ID: On Thu, 4 Sep 2003 21:35:05 +1000, "Roger Booth" wrote: >I've recently downloaded and installed Python23 and am having trouble getting it to function. > >I've set the Windows 2000 path variable "C:\Python23" but when I type "python" in a dos command line I get a message saying > "'PYTHON' is not recognized as an internal or external command, operable program of batch file". > >It does open when I type in the full path, and via Start\Programs\Python23, but when I enter "import 'filename'" from a file's home > directory, I get a message saying: "no module named 'filename'". While in your dos box, what is the output of path? Is the python path on the end? I have to call python file like this python myprogram.py Derek From syver at inout.no Thu Sep 18 07:20:10 2003 From: syver at inout.no (Syver Enstad) Date: 18 Sep 2003 13:20:10 +0200 Subject: DLL info References: Message-ID: "Ladv?nszky K?roly" writes: > Could someone suggest me how to gather various information (version number > etc.) from a Windows DLL? > Thanks for any help, I looked at win32 all but it seems the functions aren't exposed there. Grap ctypes by Thomas Heller and the MSDN Platform SDK documenation. Here's what you need: from ctypes import * windll.version.GetFileVersionInfoA Or: windll.version.GetFileVersionInfoW From tismer at tismer.com Wed Sep 3 07:23:18 2003 From: tismer at tismer.com (Christian Tismer) Date: Wed, 03 Sep 2003 13:23:18 +0200 Subject: [Zope-dev] Zope 2.7 running with Stackless 3.0 In-Reply-To: <3F5577AD.9030702@zope.com> References: <3F4D44EB.5010500@tismer.com> <3F4DF1E7.1010103@zope.com> <3F4E3CE1.5030405@tismer.com> <3F4E47DF.9060800@zope.com> <3F526AE3.50608@tismer.com> <3F5577AD.9030702@zope.com> Message-ID: <3F55CF26.502@tismer.com> Hi Shane, > Christian Tismer wrote: > >> Since you have written the Boa debugger, can you help >> me what exactly you would need? >> There has been a request to find the function that >> created a frame, recently on the main list. >> Do you think such a feature would make writing >> edit-and-continue simpler, or is it not needed? > > > Let me think out loud for a moment: > > The debugging-aware editor tells the debugger that file X, lines M-N, > have changed, and that the debugger should reload that code before > continuing. If the debugger can find a loaded module that corresponds > with that file, the debugger should compile it using the compile() > builtin, then pull code objects out of the compiled module. The > debugger should then modify every affected code object in the module. Sounds tricky, anyway. If code is changed that logically comes before the current line, how to get the locals right, or changed scope and such, without re-executing the code so far? > The tricky part is that there's a very good chance the user edited code > that's on the stack. We can examine the stack, looking for code objects > that got replaced in the step above. We can identify replaced code > objects by the co_filename and co_firstline attributes. When we find a > match, we need to replace the code object on the stack with new code. > In other words, "frame.f_code = new_code". Now for the super-tricky > part: we need to set the frame's f_lasti and f_lineno to reasonable > values. I think that's not *that* hard. The debugger would support a "set next statement", anyway, and by default we could either try to be on the same line (numerically) as before editing, or try to do a match on the source code. There is alost nothing on the frame stack between lines, just some trivial flags in case of conditionals. > It would be possible to compute the new f_lineno if the editor > told us exactly which lines were inserted or deleted. Maybe we could > base f_lasti on f_lineno by searching the bytecode for a specific > SET_LINENO instruction. We could enhance that with an instruction > offset computed by examining the original f_lasti and f_lineno. Yes, I > think that could work, except when the user edits code on the very line > that is being executed, in which case we should probably give up and > tell the user that the debugger needs to restart or continue with old code. Or, this is at least solvable, somehow. > So Stackless' role in all of this is essentially the ability to set the > f_code, f_lineno, and f_lasti attributes of a frame object, or to mimic > that capability in some way. I'm not sure that anything else is needed. > I wonder how difficult it would be to patch standard Python to support > this. Supporting this is easy for both Pythons. One problem with Standard Python is that the C interpreter is using the frame, and some variables are local to the C stack. Not so much of a problem, we just have to escape the frame, modify it, and restart it. This is implemented in a limited way for generators, and of course this is completey supported by Stackless. Leaving and re-entering frames is Stackless' job all the time. The need to update a code object that is on the frame stack is in fact almost impossible without stackless, since all frames on the stack are on the C stack as well, and they are not closed. The nested interpreters would have to be unwound and re-established. This is impossible at the moment, or would need a larger patch. This patch exists, it has the name Stackless. As nother benefit, you can even decide to continue debugging tomorrow, and simply pickle your running program or even your whole session to the disk. ... > In my previous email, I was suggesting that you talk to one of the IDE > companies about getting *paid* (either as a contractor or employee) to > make Stackless the ideal platform for IDEs. :-) Now I understand, thanks a lot. I didn't remember that those you mentioned were commercial companies. I will try to make them interested, of course. many thanks -- 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 wilkSPAM at OUTflibuste.net Wed Sep 17 10:06:03 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Wed, 17 Sep 2003 16:06:03 +0200 Subject: Simple python cgi question References: Message-ID: <87llsnmrw4.fsf@flibuste.net> Stephen Boulet writes: > First of all, I'm not sure that the easiest way to do this is with > python ... > > I'd like to set up a web page that would accept a text file, process > it with a local program, and then make available generated pdf and > postscript files for downloading. > > I'd like to limit the size of the file to be uploaded. > > I have apache2 already up. Is this a job for (mod_)python? Yes why not ? -- William Dode - http://flibuste.net From soundwave56 at yahoo.ca Wed Sep 3 16:42:24 2003 From: soundwave56 at yahoo.ca (Hank) Date: 3 Sep 2003 13:42:24 -0700 Subject: quick and smart way for parsing a CSV file? Message-ID: <731fc603.0309031242.4e5493ce@posting.google.com> Hi, I have a CSV file from excel that looks like this (simplified): name,description,type1,type2,name,filename test1,this is a test,0.000,1.000,, test2,another test,1.000,0.000,newname,filename test3,this is a test,0.000,1.000,, test4,this is a test,0.000,1.000,, test5,this is a test,0.000,1.000,, test6,this is a test,0.000,1.000,, what i want at the end is a dictionary like dict1[name] = test1 dict1[description] = "this is a test" . . . dict2[name] = test2 dict2[description] = "another test" whats a fast and quick way of parsing it? Look for the first comma, strip that entry out of the string, keep going? Thought there might be some shortcuts. Thanks From fredrik at pythonware.com Tue Sep 2 03:45:00 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 Sep 2003 09:45:00 +0200 Subject: beep is not genrated by python (was Re: just a beep) References: <000701c370e7$892ed550$5401a8c0@borg.fielden.com.au> Message-ID: "Leo" wrote: > so again: is there a more robust and terminal independent way to > generate a beep? on windows, use winsound.Beep: >>> import winsound >>> help(winsound.Beep) Help on built-in function Beep: Beep(...) Beep(frequency, duration) - a wrapper around the Windows Beep API The frequency argument specifies frequency, in hertz, of the sound. This parameter must be in the range 37 through 32,767. The duration argument specifies the number of milliseconds. On WinNT and 2000, the platform Beep API is used directly. Else funky code doing direct port manipulation is used; it's unknown whether that will work on all systems. From theller at python.net Thu Sep 18 03:10:34 2003 From: theller at python.net (Thomas Heller) Date: Thu, 18 Sep 2003 09:10:34 +0200 Subject: Checking if the computer is online References: Message-ID: Mickel Gr?nroos writes: > Hi all, > > I have a silly question. Is there are simple way to check if the computer > is connected to the Internet? It seems this should be a pretty > straight-forward thing to do, but as I am totally unfamiliar with sockets > and such, I ask for your help before getting my hands dirty. For windows? Thomas From link0937 at hotmail.com Tue Sep 23 05:26:31 2003 From: link0937 at hotmail.com (Link) Date: Tue, 23 Sep 2003 17:26:31 +0800 Subject: How to load the DLL with PyRun_SimpleString? References: Message-ID: Exactelly, the named example is .DLL and put it on the sys.path. That I had check it carefully. But the result make me sad what I failed to load. Could you give me more advice? Such as the other statement for loading DLL as same as the 'PyRun_SimpleString' command. Regards, Link "Syver Enstad" ???????:u1xu7rhk3.fsf at online.no... > "Link" writes: > > > Hi, > > > > Have anyone know how to import the DLL in C program? > > > > > > Actually, I have used the statement 'PyRun_SimpleString' to import > > .PY, > > > > > > Such as, > > r = PyRun_SimpleString("import os"); > > It's be fine. > > > > > > If importing the DLL by this commdand, > > > > Such as, > > r = PyRun_SimpleString("import example"); > > > > return the error code -1. > > Is the .dll named .pyd? Is the .pyd on your sys.path? > > > -- > > Vennlig hilsen > > Syver Enstad From martin at v.loewis.de Tue Sep 30 17:41:34 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Sep 2003 23:41:34 +0200 Subject: PEP-0263 and default encoding References: <3f782aef-bdbbd6f1-a72a-4a6c-8b23-c4915b89a61f@news.szn.dk> <3f79171c-d4c587aa-d4ac-44b9-97da-5e0024d4d268@news.szn.dk> Message-ID: Klaus Alexander Seistrup writes: > Python barfs if there are non-ASCII characters in comments and there > is no coding-line. Not necessarily. An UTF-8 BOM would do just as well. > Still beats me why it doesn't use the sys.getdefaultencoding() instead > of inconveniencing me. See my other message. REgards, Martin From amk at amk.ca Wed Sep 3 10:03:57 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 03 Sep 2003 09:03:57 -0500 Subject: Code complete electronic version ? References: Message-ID: On Wed, 03 Sep 2003 13:40:48 +0100, Jim Dabell wrote: > If it's too much, buy it second-hand. It's a good book, and although > plenty of it is just common sense, it's the type of common sense that's > easy to miss :) Isn't it mostly concerned with C, though? McConnell's _Rapid Development_ is pretty good, though, and examined the development process more than language-related things. --amk From p.useldinger at myrealbox.com Thu Sep 11 18:04:27 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Fri, 12 Sep 2003 00:04:27 +0200 Subject: Web server with Python Message-ID: Hi all, after my unsuccessful try to run Apache 2 with mod_python and Python 2.3, I am looking for an alternative approach. My aim is to write a small web-based application: Python - the solution must be based / usable on Python 2.3 Portability Targeted plaforms are - Windows 2000 Server - Windows XP Pro - AIX 5.1 Webserver: - supporting up to 50 concurrent client connections - must be able to use Python 2.3 to create dynamic pages I can think of 3 alternatives to Apache: - Medusa - Twisted - Zope Which one is the easiest to work with? Which one is known to work on an AIX 5.1 platform, for instance? Persistent storage - Is ZODB easily usable from outside Python, i.e. to produce reports without reverting to programming? - Is MySQL with Python a good combination? Regards, -PU From gcraib at hotmail.com Wed Sep 17 02:07:28 2003 From: gcraib at hotmail.com (Gordon) Date: 16 Sep 2003 23:07:28 -0700 Subject: Python exercises Message-ID: <3d19203b.0309162207.153b9922@posting.google.com> Hi, I was wondering if someone could point me in the direction of some online exercises to help me learn to program (in Python). I'm currently working through Magnus Hetland's Practical Python, which doesn't have any exercises/problem sets (for the beginning chapters on things like string manipulation etc). I'd rather not get another book. Cheers, Gordon From hat at se-126.se.wtb.tue.nl Tue Sep 16 09:17:18 2003 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Tue, 16 Sep 2003 13:17:18 +0000 (UTC) Subject: Directory names from untrusted data References: Message-ID: On Sat, 13 Sep 2003 16:08:52 +0100, Jim Dabell wrote: > > I'm in the middle of writing a small app for Linux that needs to create > directories that take their names from untrusted data. If possible, I'd > like to preserve special characters rather than switching them with dummy > characters. For instance, using bash, I'd just escape characters with Preserving characters supplied by untrusted data sounds like you do trust your supplier at least a little bit. Depending on how paranoid you are and how secure you must be, this may be dangerous. > backslashes when I want to create a directory name with, say, a slash in. > > I've been through the manual, Google and Usenet, and I've done a bit of > experimenting, but I can't seem to find a way of doing this in python. The Do what in Python? Filtering chars or making dirs? Both can easily be done in Python Filtering: safename='' for kar in untrustedname: if kar in string.letters: safename=safename+kar else: safename=safename+'_' Making dir: os.path.mkdir(safename) Obviously, the code above is extremely non-secure, you should do some checking on existance of the directory name, provide an atomic creation primitive, and set the access rights to something sensible. > only thing I can think of is to spawn a bash shell to do it, which I'd > rather not have to do. Does anybody have a better way of doing this? > Also, are there any other things I should watch out for (e.g. excessively > long names)? Short answer: Everything, including all things you think you can trust. Longer answer: Read a few docs about secure programming to get sufficiently paranoid. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From maney at pobox.com Sat Sep 6 19:05:08 2003 From: maney at pobox.com (Martin Maney) Date: Sat, 6 Sep 2003 23:05:08 +0000 (UTC) Subject: OT: best book in years References: <3F5891C8.A7DD1A20@hotmail.com> Message-ID: Aahz wrote: > McMaster Bujold (start with _Shards of Honor_, but don't read _Barrayar_ > yet if you pick up the _Cordelia's Honor_ omnibus). Are you advising the traditional publication order or reading here? I did that the first time; last year I went through them again in internal chronology sequence, and damned if I don't think they work just perfectly well that way. I suspect Baen, and presumably Lois, would agree, as that seems to be the way they're packaging the omnibus reissues, at least mostly. > Social SF: anything by Ursual K. LeGuin, _Courtship Rite_ by Donald > Kingsbury I stumbled across Kingsbury's _Psychohistorical Crisis_ at a bargin book outlet early this year, and thought it was absolutely stunning. I have to keep telling myself it's too soon to reread it, yet. A couple months ago I had to dig out CR as a surrogate. I hadn't read it in donkey's years, and I'm happy to say that I found it had aged very well. No, Martin, it is still TOO SOON! (this group/list is dangerous. just a few hours ago I was looking forward to finishing _Death in a Tenured Position_; now it's looking more like a obstacle that wants overcoming. sheesh! maybe i can find some nice python programming project to distract me...) -- The true danger is when liberty is nibbled away, for expedients, and by parts. -- Edmund Burke From dakidd at sonic.net Sun Sep 14 17:45:16 2003 From: dakidd at sonic.net (Don Bruder) Date: Sun, 14 Sep 2003 21:45:16 GMT Subject: Huh?!?!? What is it that I'm seeing here? Message-ID: First off, I'm a non-Python type person - I prefer a compiled language, when the option is available, with a strong preference for C and/or C++. (Sorry, boyz-n-girlz, I'm not interested in "You need to learn a real language like _________" fights, or debates over the merits and/or shortcomings of C/C++ - C/C++ is what I want the program I'm working with to be written in, and that means that all discussion regarding language choice is moot. End of discussion there.) I'm in the process of trying to convert a Python script/program or whatever the favored term is into C and/or C++, and of course, due to my unfamiliarity with Python, I'm hitting some stuff that looks to be idiomatic, without being able to locate a definition/description of the idiom. Most of what I'm messing with seems pretty straightforward - it's converting nicely into C++, and with my testing so far, appears to be performing properly (albeit somewhat inefficiently, since I haven't done any tweaking yet) but one particular construct has me stumped. It looks like this: if __name__ == '__main__': run(argv[1:]) This (or a markedly similar construct) sits all by its lonesome self at the bottom of several of the source files, apparently not part of any class or declaration. It seems to be *FAIRLY* common in the group of files that make up the program, which makes me think it may be some sort of "preprocessor directive" type thing, similar to a C construct that would conditionally compile in a "main()" routine if a given symbol is/isn't defined. In all cases where this construct appears, there's a corresponding "run()" method, which, confusingly, appears to be outside the scope of any lexical blocks that I can recognize, so I've got no contextual clue there... I've paged through all the online Python docs I can find, but although I recall seeing a reference to __name__ as some sort of special variable/identifier, that was when I first came up against the language, so I paid no attention at that time. Now, when I actually NEED it, I can't LOCATE it! Can anybody help me out here? Judging by how common it is in the files in this program, and the fact that I simply cannot re-find the discussion of the "__name__" thing, I have to assume it's one of those "Duh! Anybody smarter than a sheep already knows that!" constructs that anyone with some experience with the language has used/understands without needing more explanation. Unfortunately, I have little-to-no experience with Python, and even less interest in learning it - chances are so far beyond "high" that I'll never write a single line of code in it that the number might as well be infinite, since I have zero interest in taking the time to learn a new language for a one-off project. I simply want a program that was originally (however good, bad, or in-between the original decision might have been) written in Python turned into a C/C++ program that I can work with effectively using existing skills and knowledge. Not knowing/understanding the function of this construct appears to be hindering that process, so maybe somebody here can help me out? Thanks in advance... -- Don Bruder - dakidd at sonic.net <--- Preferred Email - unmunged, SpamAssassinated Hate SPAM? See for some seriously great info. I will choose a path that's clear: I will choose Free Will! - N. Peart Fly trap info pages: From peter at engcorp.com Tue Sep 2 13:41:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 02 Sep 2003 13:41:35 -0400 Subject: artificial intelligence? References: <7ZCdnQAI0aeAo8-iU-KYuA@giganews.com> Message-ID: <3F54D64F.16C2A783@engcorp.com> Istvan Albert wrote: > > Arthur wrote: > > We've noticed that customers who have purchased books by Mark Lutz often > > enjoy the books of Sedi 200. So you might like to know that Sedi 200's > > newest book, Earth's Core and Lower Mantle (Fluid Mechanics of Astrophysics > > and Geophysics, V.11), > > """ > > > > Any theories on how the Amazon.com AI machine got this far off track? > > Discovering so called "serendipitous" items, items that cannot > be related with classical methods (say content or author) yet > are very desirable to the consumer is the holy > grail of personalization. As the example above shows it > can go totally gaga. Why "gaga"? Has anyone actually purchased "Earth's Core and Lower Mantle"? It could be an absolutely un-put-downable book! Maybe Amazon is *right*... ;-0 -Peter From paul at subsignal.org Thu Sep 18 06:22:40 2003 From: paul at subsignal.org (=?ISO-8859-1?Q?paul_k=F6lle?=) Date: Thu, 18 Sep 2003 12:22:40 +0200 Subject: [NEWBIE] access return values Message-ID: hi folks, during the last couple of days I wrote my first small app with wxPython and it all works pretty well, but now I'm somewhat lost. I'd like to access the return value from a function inside an imported module (a method of a class of that module eh?) ---gui.py---- from wxPython.wx import * from app.py import * user=UserObject(config) # class instance from app.py the class UserObject has a function set_pwd() which returns a var, say "ch_success" indicating success/failure wich I'd like to pass to a Dialog to give some feedback to the user. but: --in gui.py---- d=wxMessageDialog(self, user.ch_success,"Info:", wxICON_INFORMATION | wxOK) gives: AttributeError: UserObject instance has no attribute 'ch_success' That makes sense, since ch_success is a local variable of set_pwd(), so I tried to make it global but with very little success so far. I tried: --in app.py---- def set_pwd(someargs, moreargs) do stuff // ... global ch_success or: return ch_success or: self.ch_success Nothing worked (but frankly, I don't really know what I'm doing here). Any ideas? Thanks Paul From tjreedy at udel.edu Wed Sep 3 12:10:32 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 3 Sep 2003 12:10:32 -0400 Subject: Difference of hash and __hash__() References: <338366A6D2E2CA4C9DAEAE652E12A1DEAD454A@au3010avexu1.global.avaya.com> Message-ID: "Stefan Fleiter" wrote in message news:bj4dhh$24s$1 at news.web.de... > So, should I write a bugreport or not? > Are you sure it is "rightfully ignored" or not? At worse, a bug report such 'Slice hashing: behavior or doc bug?' would be closed by someone in the know as 'Not a bug'. If it is not a behavior bug, then docs could use slight modification, and so a bug report would be appropriate anyway. Ref Manual 5.3.3 Slicings says nothing about hashability. If not hashable, in spite of being mutable, "Slices are not hashable" could be added at end. Ref Manual 3.3.1 Basic customization, __hash__( self) entry says "Called for the key object for dictionary operations, and by the built-in function hash() " This implies to me that if there is a __hash__() method, then hash() will call it. If not true, then a 'maybe' could be added. Lif Maual 2.1 Built-in Functions, hash( object) says only "Return the hash value of the object (if it has one)." If having __hash__() does not mean 'has one', then what does. Feel free to copy if you do file. Terry J. Reedy From tjreedy at udel.edu Tue Sep 2 12:11:31 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 2 Sep 2003 12:11:31 -0400 Subject: what's wrong with REBOL? References: <6005702b.0309020727.4ba46e78@posting.google.com> Message-ID: "Mike Henley" wrote in message news:6005702b.0309020727.4ba46e78 at posting.google.com... > So as i needed a mature enough solution, but liked the way snipsnap > worked, i looked around, and on freshmeat i found vanilla, with a > development status of 5; production/stable. I went to its site, where > a working demo impressed with its capabilities. The site is though > poorly documented, very poorly documented i had to use trial and error > to work out how to install it. If you learned something that might help others, consider contributing a writeup if you think (or find out) that site maintainers would consider adding it. > What's wrong with Rebol? It is not Python ;-) and I don't know what unmet need it would fill for me. But your experience moved it up a bit on the list of languages I might look at someday. Terry J. Reedy From kbilsted at hotmail.lala.com Tue Sep 9 19:01:16 2003 From: kbilsted at hotmail.lala.com (kasper graversen) Date: Wed, 10 Sep 2003 01:01:16 +0200 Subject: virtual inner classes in python? References: <3F5E54DF.8ED73922@engcorp.com> Message-ID: On Tue, 09 Sep 2003 18:31:59 -0400, Peter Hansen wrote: thanks for your quick reply. Yes indeed I wanted foo to be an inner class of Test and __init__ to be the constructor of test. Running my example, I wanted the inner-foo of Test2 to be instantiated rather than foo of Test.. this, however, was difficult for me, since I had to type "Test.Foo()" where I wanted to just type "Foo()" and then let python look in its local scope. ((trying your suggestion)) YAHUUU!! "Test2.foo.show" is printed on the screen just as I wanted it to! great! many thanks! now, since you are confused(?) with my code posting, how should I go about posting python code the next time I want to do so? -kasper > kasper graversen wrote: >> >> I've just started learning python. I see methods are declared virtual by >> default as in Java. Nice. However, the inner class construct seems to be >> even weaker as that of Java. Not nice! :-( Why are inner classes not >> virtual? will they be in a near future? What other language can you >> recomend, if python cannot provide what I need? >> >> My problem is that in the __init__ below, I cannot instantiate "Foo" but >> have to explicate "Test.foo".. secondly, I want to instantiate the "Foo" >> in >> test2 rather than in tester in the current example.. >> >> class Test: >> def __init__(self): >> lala = Test.Foo() >> lala.show() >> class Foo: >> def show(self): >> print "Test.foo.show" > > With the tabs that you used, the above formatting is what some of us > saw. It seems you meant for "class Foo" to appear at the same level > of indentation as the "def __init__", right? > > As for "declared virtual by default", I don't think this is quite > correct for Python. All methods are always virtual in Python, unless one > goes to extremes to simulate some other effect, I think. > > Anyway, I believe the problem you are experiencing stems from a lack > of understanding of how Python finds things in its "namespaces". This is > a key concept to issues such as the one you are investigating, > and you won't get far if you assume Python is anything like Java > or other static languages in this respect. > > First, you need to specify Test.Foo because otherwise you are asking for > a Foo that is found in the global (module) namespace. > You could also use "self.Foo" in this case, though it might be > considered slightly less clear, but I have a feeling it would do roughly > what you want, whatever that is. (You didn't really > make it clear what you want, as near as I can tell.) > > -Peter > -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From davecook at nowhere.net Fri Sep 5 20:50:52 2003 From: davecook at nowhere.net (David M. Cook) Date: Sat, 06 Sep 2003 00:50:52 GMT Subject: newbie question on which win32 GUI to choose References: Message-ID: In article , Rain wrote: > Now I want to narrow topic and ask this question: > Which one have a little more clear logic and easy to learn and use? > Not considering the local platform and feeling, and the deployment.I > know pyGTK need GTK runtime libs. Unless running on win32 is of secondary importance, I don't think Gtk would is a good choice until some of the Gtk/win32 bugs and other issues are worked out. Dave Cook From mickel at csc.fi Wed Sep 24 09:15:41 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Wed, 24 Sep 2003 16:15:41 +0300 (EEST) Subject: How to catch socket timeout? In-Reply-To: References: <3F6DD4D7.AF309B4@hotmail.com> <7h3smmm4bkj.fsf@pc150.maths.bris.ac.uk> Message-ID: On Wed, 24 Sep 2003, Mickel Gr?nroos wrote: > On Wed, 24 Sep 2003, Michael Hudson wrote: > > > Paul writes: > > > > > What's the best way to do this under Python 2.1? > > > I believe socket.timeout was a 2.3 feature. > > > Wrap it in threads? > > > > There's Tim O'Malley's timeoutsocket.py (google for it), which was the > > inspiration for the feature in 2.3 (though I don't think any code from > > there actually survived). > > I can't get the timeoutsocket module to work on my Redhat Linux! (The > timeout works fine on Windows 2000.) I'm running Python 2.2.2. > > Here's the test code: > > import timeoutsocket > timeoutsocket.setDefaultSocketTimeout(1) > s = timeoutsocket.socket(timeoutsocket.AF_INET, timeoutsocket.SOCK_STREAM) > s.connect(("www.google.com", 80)) > s.close() I might add, that I conducted the test by running the above code with and without my Ethernet cable plugged to the computer. When it was plugged connect() worked just fine, when unplugged, the connect() call timed out on Windows as expected but not at all on Linux. /Mickel G. -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From nid_oizo at yahoo.com_remove_the_ Fri Sep 26 10:30:36 2003 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 26 Sep 2003 10:30:36 -0400 Subject: Reduce need of backslash Message-ID: Hi, I was wondering if the need for \ could be reduce in the language. For example, could a line ending with = or + could be automaticly considered incomplete? Regards, Nicolas From Mike at DeleteThis.Geary.com Thu Sep 25 22:04:14 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 25 Sep 2003 19:04:14 -0700 Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: > Stephen Ferg wrote: > > But now, among a small group of cognoscenti, it is a truism that this > > is a myth, and that Windows will allow you to use either the forward > > or the backward slash as a pathname separator. Ben Finney wrote: > I highly doubt it, since the forward slash (or just "slash") is the > conventional Windows command-line option indicator, analogous to the > hyphen on Unix. To accept it as the start of a filename would break > zillions of existing systems, for no appreciable benefit to Microsoft. Actually, every version of Windows, and every version of MS-DOS from 2.0 on, has accepted "/" as a path delimiter. Don't confuse the command line with the Windows or DOS kernel. Most command lines don't allow "/" because it conflicts with the use of "/" for a switch deliminer. But the Windows and DOS kernels are happy with either "\" or "/". -Mike From jroznfgre at jngpugbjreQBGbet.cy Mon Sep 15 09:07:00 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Mon, 15 Sep 2003 15:07:00 +0200 Subject: caching the sql queries References: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> Message-ID: On Mon, 15 Sep 2003 13:34:45 +0200, Gerhard H?ring wrote: >In my opinion, this sort of caching should really be done in the >application layer, not in the database access layer. Why not? It caches only db recordsets an it is total independend from other form or cache. -- JZ From newsgroups at jhrothjr.com Mon Sep 15 20:08:01 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 15 Sep 2003 20:08:01 -0400 Subject: irritating problem References: <20030915150042.22749.00001062@mb-m23.aol.com> Message-ID: "Park997" wrote in message news:20030915150042.22749.00001062 at mb-m23.aol.com... > Hi, > > I have a script that runs correctly in IDLE, runs correctly when invoked in the > Command Prompt (Win XP), runs correctly from Komodo, but flashes a black box > too fast to see when the icon is double clicked and produces no output. There > are no error meassages from any of the methods that produce output. All of the > other modules in the same directory (these are imported to the problem module) > work correctly in any start mode. > > python 2.3. > > Obviously this isn't a disaster, but it "bugs" me. Is there a fix or method of > obtaining diagnostic information on this? When you say "all of the other modules ... work correctly in any start mode," do you mean that when you double click on the icon they come up in a dos box and the box stays around after the module exits? Or does your comment about importing them mean that you don't attempt to run them independently? There are *two* command prompts in Windows XP. One is the Command Prompt you seem to be using (the one with the "c:" icon), the other is the DOS box. It's cleverly hidden, but it still exists. The default action for both of them is to run the command and then exit immediately; that's why you get the black box that flashes and then vanishes. If your script provides a keyboard interface, the console window will stay around as long as you keep reading keyboard input; it will still go away immediately when you exit from the console loop and exit the Python script. There's no obvious way I know of to double click on a Python icon and have the XP console window stay around after the script exits. This is because Python itself invokes the command line processor, and there's no opportunity to pass it the -k (I think that's the one) parameter. What I do in the rare cases where I want to directly invoke a Python script and have the console window stay around is to create one (or sometimes two) .cmd files. The first .cmd file invokes a second copy of the XP command line with the -k parameter (which makes it stay around) and then Python itself. [cmdfile1.cmd example] cmd -k python myscript.py parameters... [end of command script] This doesn't allow you to set environment variables. If you want to do that, you need two .cmd files. [cmdfile1.cmd example] cmd -k cmdfile2.cmd [end of cmdfile1.cmd] [cmdfile2.cmd example] set envvar=somethingOrOther python myscript.py theWorldsGreatestParameter [end of cmdfile2.cmd] HTH John Roth > > Thanks, > > Wendell Cropper From indigomoon at bonbon.net Wed Sep 24 03:00:48 2003 From: indigomoon at bonbon.net (Indigo Moon Man) Date: Wed, 24 Sep 2003 01:00:48 -0600 Subject: float problem References: Message-ID: Gary Herron spake thusly: > > You're getting bit by the difference between integer and float > division. > > In versions of python prior to 2.3 (and in 2.3 under normal > circumstances), division of two integers returns an integer and > division of two floats (or a float and an integer )returns a float: > Great! Thank you very much! -- Audio Bible Online: http://www.audio-bible.com/ From bokr at oz.net Wed Sep 3 15:07:45 2003 From: bokr at oz.net (Bengt Richter) Date: 3 Sep 2003 19:07:45 GMT Subject: reading large file References: <9bd0dd3f.0309030400.7fa2dc0f@posting.google.com> Message-ID: On 3 Sep 2003 05:00:39 -0700, g_alleon at yahoo.fr (guillaume) wrote: >I have to read and process a large ASCII file containing a mesh : a >list of points and triangles. >The file is 100 MBytes. > >I first tried to do it in memory but I think I am running out of >memory therefore I decide to use the shelve >module to store my points and elements on disks. >Despite the fact it is slow ... Any hint ? I think I have the same >memory problem but I don't understand why >since my aPoint should be removed by the gc. > >Have you any idea ? > Since your data is very homogeneous, why don't you store it in a couple of homogeneous arrays? You could easily create a class to give you convenient access via indices or iterators etc. Also you could write load and store methods that could write both arrays in binary to a file. You could consider doing this as a separate conversion from your source file, and then run your app using the binary files and wrapper class. Arrays are described in the array module docs ;-) I imagine you'd want to use the 'd' type for ponts and 'l' for faces. Regards, Bengt Richter From iscaris at hotmail.com Fri Sep 12 06:43:48 2003 From: iscaris at hotmail.com (Fernando) Date: 12 Sep 2003 03:43:48 -0700 Subject: Usenet posting wiht python Message-ID: Hi, How can I send a usenet posting from a python app? Thanks O:-) From neil.padgen at mon.bbc.co.uk Tue Sep 9 07:32:29 2003 From: neil.padgen at mon.bbc.co.uk (Neil Padgen) Date: Tue, 09 Sep 2003 11:32:29 +0000 Subject: Massive unit test vs MySQL References: Message-ID: On Monday 08 September 2003 22:28, Richard Wesley wrote: > In article , > Neil Padgen wrote: > > I doubt it - it is generated by mysqldump. And there is no problem > from the command line. > I use exactly the same approach to set up my unit tests, but I have a different way to get the mysqldump data into the database: os.system('mysql database_name < dumpfile') -- Neil -- From tim.parkin at pollenationinternet.com Sun Sep 7 07:43:03 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 12:43:03 +0100 Subject: Comments on Python Redesign In-Reply-To: Message-ID: <001b01c37535$38848030$0a00a8c0@JASPER> Terry Ready said: > YUCK< YUCK< YUCK. > > The pollenation site is one of the worst I have seen. The mockup page > has teeny type that IE will not enlarge. > > I care that the site remain physically readable and that it remain a > vehicle for information rather than childish egos. > > Using IE6, I need a magnifying glass > to read this page. This is done in the arrogant style of 'we know > better than you what type size you should have'. Also known as the > 'control the user experience' school. Awful. For me, one of the > worse pages I have ever seen. Anti-Pythonic. > > > interior page: > Only slightly better. The low contrast gray-on-gray comments page is > also barely readable. (Others reported the same.) For my > less-than-perfect 50+ year-old eyes, it is physically the WORST > comments page I have ever seen. It is a case study in > anti-accessibility design. The person responsible should not touch > our site. Perhaps the people who have commented on the site should realise it's a proposal and a work in progress. As constructive comments go the only feedback I have gathered is that the fonts are too small and the contrast is a little low. I've adjusted contrast on key elements and also increased the font size. These pages are here : http://pollenation.net/assets/public/python-main-2.html http://pollenation.net/assets/public/python-interior-2.html also bearing in mind that the html page will be accessible and hence allow text resizing here is a sample of +1 text size. http://pollenation.net/assets/public/python-main-2larger.html http://pollenation.net/assets/public/python-interior-2larger.html Also, Terry, the design was an 'image', a 'mockup', a 'png' to be specific, it did not dictate font size. As far as accessibility is concerned, the only problem was the contrast and the font size both of which I've changed as I agree they were too low and too small respectively. Although I agree that the font size should be bigger, the current site is not an exemplar of accessibility. The following example taken from the interior page I have shown.The first is in comparison with my original design, the second show a comparison with the amendments showing normal and +1 font sizing. (the text on my samples may benefit from increasing the line height using css) http://pollenation.net/assets/public/python-text-comparison-new.gif http://pollenation.net/assets/public/python-text-comparison.gif As a side note, I haven't been to any school of 'control the user experience'. Furthermore I think making comments such as accusing me of having a 'childish ego' and being 'arrogant' are IMO extremely disrespectful and I would appreciate an apology. I am quite hurt and dissapointed to see such coments on what I had considered a respectable forum for discussion although I'm sure they are not representative. Tim Parkin Terry: > I otherwise do not have too much concern about particulars and therefore > not much to contribute. From cjh_nospam at managesoft.com Tue Sep 2 19:30:35 2003 From: cjh_nospam at managesoft.com (Clifford Heath) Date: Wed, 03 Sep 2003 09:30:35 +1000 Subject: Aspect oriented Everything? In-Reply-To: References: <32cc321c.0308221316.2f5793ac@posting.google.com> <3F52BB3C.70406@managesoft.com> Message-ID: <1062545436.26178@excalibur.osa.com.au> Anton Vredegoor wrote: >>Proprietry standards for basic technologies are doomed. > Right. However the previous long piece of text lead me to read this > the exact opposite way of what is written above at first. :-). I believe in tools, and on re-reading I guess you thought I was about to start spruiking some tool, and I *am* invoking tool-makers to rise to the challenge. OTOH - they shouldn't expect money for it, only glory :-). Clifford. From aleax at aleax.it Fri Sep 26 08:45:22 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 12:45:22 GMT Subject: why the inconsistency? References: <4bh3nv0esljf8pkegog0lc4lmg87siv1oc@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > On 23 Sep 2003 18:04:33 -0700, rumours say that mensanator at aol.com > (mensanator) might have written: > > [snipped] >>But if I want to know how many digits 2**64 has, I can't >>just do > > If only math.log(2**64)/math.log(10) worked with longs without > converting them into floats first... :( I'm not sure how you'd compute log on integer numbers. Anyway, if you're in a hurry to know the number of digits in 2**64 -- I see math.log(x,10) taking about 4 usec per loop, len(str(x)) about 6.3, in each case with x=2*64 and measuring with timeit.py (elapsed time, as I'm measuring on Linux). gmpy.numdigits(x) repeatably takes a bit less than 2 usec per loop; if you're interested in speedy computations with "multi-precision" values (integers, rationals, OR floats), you could do worse than looking into gmpy (plug, plug;-). (Note: all times measured on my old Athlon -- I did choose an Ahtlon, back about 30 months ago, exactly because I had seen benchmarks where it outperformed Intel CPU's by a mile on multi-precision integral computations, particularly with the GMP library...). Alex From harry.pehkonen at hotpop.com Mon Sep 1 14:30:50 2003 From: harry.pehkonen at hotpop.com (Harry Pehkonen) Date: 1 Sep 2003 11:30:50 -0700 Subject: super question References: <7h3k78s3dc3.fsf@pc150.maths.bris.ac.uk> Message-ID: <70df36e9.0309011030.4de74e3b@posting.google.com> Sorry -- Google is not letting me reply to the correct posting . . . Aahz wrote: > > but why not just do: > > > > class C(B): > > def meth(self, arg): > > B.meth(self, arg) > > > >Is there any difference? > >Any advantage either way? > The advantage comes when you rename B or when you have multiple base > classes for C. Like this?: class C(A, B): def __init__(self): for parent in C.__bases__: parent.__init__(self) I don't think there is one definitive answer to the question of how to do this. Harry. From duncan at NOSPAMrcp.co.uk Mon Sep 29 10:51:32 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 29 Sep 2003 14:51:32 +0000 (UTC) Subject: Question: Inheritance from a buil-in type References: <3F7848C6.8070306@snafu.de> Message-ID: "T. Kaufmann" wrote in news:3F7848C6.8070306 at snafu.de: > A simple but important question: > > How can I initialize a super class (like dict) correctly in my > subclass constructor? > > A sample: > > class MyClass(dict): > def __init__(self): > dict.__init__(self) > ... > > > Is there a general rule to do this for all buil-in types? There are two rules. Generally, immutable objects get their initial values from the constructor (__new__) while mutable objects are constructed with a default value (e.g. empty list or dict) and are then set by the initialiser (__init__) method. A few types which you might expect to be immutable are actually mutable (e.g. property). Mutable example (use for list, dict, property, etc.): class MyClass(dict): def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) Immutable example (use for tuple, int, etc.): class MyClass(tuple): def __new__(cls, *args, **kw): return tuple.__new__(cls, *args, **kw) If there is any chance of your class being subclassed with multiple inheritance involved, you should consider using super instead of naming the baseclass directly, but most of the time you can get away with a direct call to the baseclass. -- 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 dag at velvet.net Mon Sep 29 10:53:34 2003 From: dag at velvet.net (Dag) Date: Mon, 29 Sep 2003 14:53:34 GMT Subject: Prime number module Message-ID: Is there a python module that includes functions for working with prime numbers? I mainly need A function that returns the Nth prime number and that returns how many prime numbers are less than N, but a prime number tester would also be nice. I'm dealing with numbers in the 10^6-10^8 range so it would have to fairly efficient Dag From mertz at gnosis.cx Thu Sep 11 13:58:53 2003 From: mertz at gnosis.cx (David Mertz) Date: Thu, 11 Sep 2003 13:58:53 -0400 Subject: safari References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <51809ae4.0309040634.7999e400@posting.google.com> <51809ae4.0309110734.1e5d28be@posting.google.com> <87y8wvfd6d.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) wrote previously: |Pearson and O'Reilly owned by a single company, or something? I have |a vague recollection that Pearson owns some other companies... There's been a huge amount of consolidation in publishing. Pearson is not the parent of Addison-Wesley, Longman, Benjamin Cumming, New Riders, Peachpit, Cisco Press, Prentice Hall, SAMS, Que, and several more imprints. It's really a rather bad thing, although they do not seem to use the degree of ideological acid-test that, say, MediaCorp acquisitions do. I started writing my book for AW, only to find it a Prentice book when it was published (it still has the AW imprint, but the meaning seems diluted). That said, I'm pretty sure that O'Reilly remains one of the few independent publishers of technical books. I think Manning is also. Yours, David... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From tim.parkin at pollenationinternet.com Sun Sep 7 17:13:35 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 22:13:35 +0100 Subject: Comments on Python Redesign In-Reply-To: Message-ID: <003201c37584$ec5c7140$0a00a8c0@JASPER> Aahz: > That said, there likely will be a subsection of python.org that is > aimed at managers, with a more designed look and more graphics; > someone trying to convince a specific manager could point zir into > the subsection. Fernando: > A visible 'corporate' link, along with a single-level url > www.python.org/corporate, perhaps even aliased to > corporate.python.org) can satisfy the PHBs with minimal effort. Please don't consider this, the majority of corporate users will find the site themselves or through links in articles magazines, etc. so they will still get first impressions from the main home page. If anything we could provide a developer portal page which may be used as a bookmark. Personally I think this is a bad idea also. What is wrong with the information architecture / navigation on the page proposal. Please could we move this discussion to one of the appropriate lists aswell. I suggest python-marketing to begin with. Fernando: > That's why you really need to post a readable > html site, not a png: it's almost impossible for anyone but you to > properly judge the site with graphical screenshots. It takes a long time to create a professional html design that is cross browser to the extent needed for this site and also as accessibile as possible. I am unwilling to spend this amount of time just to get some feedback on a design that might possibly be used. To give you an idea of how much this HTML design would cost from a consultancy (which is what pollenation is), calculate professional rates at approx thirty two hours work (my guess, about ?1,600 or maybe $2,500). Could someone please explain why it's impossible to judge the design of the site without it being rendered as HTML. Perhaps the accessibility / speed needs HTML, but not the design. Do people feel that the design would be impossible to create as a optimal HTML entity? Fernando: > And since the starting thread of the discussion was a post by Tim > himself, that seemed a perfectly fair thing to do. It may have been > dragged here from elsewhere, but the first 'Comments ...' post was > by Tim, and he's been responding in the discussion actively. > As long as the comments were civil Actually the first post wasn't by me and I only saw it as it was mentioned in my blog, at which point I subscribed to comp.lang.python. Fernando: > A basic rule of design should always be: a default (www.python.org) > value should satisfy the _majority_ of usage cases (not those with > the most money/corporate power/whatever). Since the majority of > visitors to the site can arguably be thought to be developers, > _that_ is the audience the default url should target. No, a basic > rule of design is to create something that satisfies the brief. In this case the brief is to provide a site whose default view provides a developer friendly page but with a heavy marketing bias. As long as the page still satisfies the information needs of the developer then it satsifies the brief. David Eppstein: >"rightly jumping all over the design" Why are they rightly jumping all over it? Is this the purpose of discussion? I would say people should be "right providing constructive feedback". From pgardell at bbn.com Fri Sep 26 07:51:25 2003 From: pgardell at bbn.com (Paul Gardella) Date: Fri, 26 Sep 2003 07:51:25 -0400 Subject: Python for CGI scripting In-Reply-To: Message-ID: <005e01c38424$84376da0$ce0aa8c0@PGARDELL> Also check out "Core Python Programming" by Wesley Chun (2001, Prentice-Hall). It has an approx 60-page chapter on web programming with Python, incl CGI. Paul -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Eric Wichterich Sent: Thursday, September 25, 2003 8:02 PM To: python-list at python.org Subject: Re: Python for CGI scripting Hello Mark, have a look at O'Reilly "Programming Python" by Mark Lutz, topic "Internet Scripting" (page 513ff.). It helped me a lot to get started writing scripts for internet applications. Good luck, Eric Am Freitag, 26.09.03 um 00:46 Uhr schrieb python-list-request at python.org: Von: "mark" Datum: Do, 25. Sep 2003 23:58:03 Europe/Berlin An: Betreff: Python for CGI scripting I am beginning to get interested in how I can use Python in place of something like Java for Website scripting. Are there any books on this, or any tutorials on the Web I could read? Any help is appreciated. - Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From tzot at sil-tec.gr Thu Sep 4 12:57:45 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 04 Sep 2003 19:57:45 +0300 Subject: How do I match this with re References: <8f8ffe67.0309040835.368f9565@posting.google.com> Message-ID: <0arelvci3jats8k8l5no6c0t8q53kgrse5@4ax.com> On 4 Sep 2003 09:35:18 -0700, rumours say that sjoshi at ingr.com (Sunit Joshi) might have written: >Hello All >I have a problem here where I need to find the drive letters in a text >file and replace them with another letter. Now the lines can be as >long as this > >6 'C:\pds\bddin64\report\mto\' 'SJOSHI' >'D:\pds\bddin64\report\format\' 'SJOSHI' > >with multiple entries for path; i.e. there may be 2, as above or 1 or >more then 2. If I use the expression .*'([A-Z]:).*?', it only matches >the 2nd D: How do I get all the path groups ..?? I assume that the drive letters will be directly after a single quote. You need this re: reDriveLetter = re.compile(r"(?<=')[A-Z](?=:\\)"). You can try reDriveLetter.findall() or the reDriveLetter.finditer() functions then, each match object will match a single capital letter. Very important to everyone working with regular expressions: the redemo.py script. Search for a Scripts directory in your python directories (it's under Tools on Windows, otherwise get it from the source distribution), redemo.py is in there along with other useful scripts. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From duncan at NOSPAMrcp.co.uk Mon Sep 15 12:26:44 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 15 Sep 2003 16:26:44 +0000 (UTC) Subject: unique unions of several dict keys References: Message-ID: python at sarcastic-horse.com wrote in news:mailman.1063641206.10374.python-list at python.org: > I have several different dictionaries. I want to make a unique list > of all the keys in all the dictionaries. What would be the best way > of doing that? Create a new empty dictionary then use the update method on it for each of other dictionaries. The keys of that dictionary are the values you want. e.g. >>> def UniqueKeys(*dicts): tmpDict = {} for d in dicts: tmpDict.update(d) return tmpDict.keys() >>> print UniqueKeys({ 'a':1, 'b': 2 }, {'b': 3, 'c': 4}) ['a', 'c', 'b'] >>> -- 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 medved at fcc.net Sun Sep 14 10:51:23 2003 From: medved at fcc.net (Ted Holden) Date: Sun, 14 Sep 2003 10:51:23 -0400 Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <17d520f6.0309130704.7944c876@posting.google.com> <87znh89ufv.fsf@pobox.com> Message-ID: <7ICdnZSX7bE0H_miU-KYgw@fcc.net> John J. Lee wrote: > I've never seen anybody give a convincing reason why GTk is a good > choice for *anything* except writing GNOME apps. I've just been putting myself through a sort of a crash course in pygtk, basically a text indexing and retrieval application which already existed in several Windows and KDE versions as well as a Tcl/Tk version which nobody had used in several years. The idea is to have some sort of a version of the thing which integraters could work with, i.e. written mainly in a scripting language, and python appears to be several levels of advancement above Tcl. Tk appears to be more functional at this point, nonetheless there was no way to avoid having Tk code twisted and wound in and around app code in the Tcl version of the thing whereas the glade/gtk version of the thing produces a gui in an XML file and an absolute minimum of anything related to guis in my own code. The difference between the two is about 400 lines of very readable code versus about 2500 lines of code which was marginally readable. I'd MUCH rather deal with pygtk, and assume anything I might miss from Tk will be there in a year. The LINUX community appears to have developed a sort of a magical nexus of things including gcc, swig, python, pygtk, glade, and zope which, taken together, amounts to a new sort of programming paradigm. The really big piece of magic in the picture is swig. This says that you you can write library code in c++ and call it from a python program with a gui produced by glade sitting there in an XML file, and all you'd ever need to distribute to customers would be the .so file which swig produced, one or two .py files, and the xml file. That also says that if a customer wasn't totally happy with some aspect of the interface, he could screw around with it until he was. I don't see an easy way to beat all of that. From lp at your-pants-coder.dk Mon Sep 1 08:50:40 2003 From: lp at your-pants-coder.dk (Larz) Date: 01 Sep 2003 12:50:40 GMT Subject: Python Documentation? References: <3f530ea6$0$32489$edfadb0f@dread16.news.tele.dk> Message-ID: claird at lairds.com (Cameron Laird) wrote in news:vl6dmm8jutl140 @corp.supernews.com: > Python already has a structure--and much content!--for > comparable collaboration in www.python.org/cgi-bin/moinmoin/ >. Moreover, as several > follow-ups have explained, Python developers have differ- > ent work practices than PHPers, and a different relation > to documentation. In particular, it's hard to overempha- > size how much working Python programmers depend on > interactive introspection: use of the interpreter's > built-in help, pydoc, and related facilities to discover > and confirm details that, in PHPonia, are regarded as > matters for online documentation. Yes, I agree that a lot of python programmers think differently. Even though, I sense a general consensus, especially among beginning Pythoneers, that the community lacks a great tool, like the one PHP has. Of course I am not just thinking about the documentation itself, which you could get with pydoc/help(), but also experience, pointers, pitfalls that other people ran in to. That's what makes it a community ;) Anyway, I am pretty sure we're going to fill a much needed niche, and if not, we're certainly going to meet our own needs ;) -- larz to mail me, remove your pants! From gh at ghaering.de Mon Sep 15 07:34:45 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 15 Sep 2003 13:34:45 +0200 Subject: caching the sql queries In-Reply-To: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> References: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> Message-ID: <3F65A3D5.4090603@ghaering.de> JZ wrote: > Is there any equivalent of caching sql queries for Python like ADOdb > for PHP? (For those who did not hear about ADODb and its feature : > http://phplens.com/adodb/caching.of.recordsets.html) I'm not aware of any such thing for Python, and I find it dubious, too. In my opinion, this sort of caching should really be done in the application layer, not in the database access layer. -- Gerhard From jepler at unpythonic.net Sun Sep 14 22:14:44 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 14 Sep 2003 21:14:44 -0500 Subject: Is there "let binding" in Python? In-Reply-To: <20030914214340.13608.qmail@web40904.mail.yahoo.com> References: <20030914214340.13608.qmail@web40904.mail.yahoo.com> Message-ID: <20030915021439.GA30615@unpythonic.net> For more information about Python's scoping rules, you can read parts of the tutorial and language reference. Here are some relevant URLs: Tutorial 9.2 Python Scopes and Name Spaces http://www.python.org/doc/tut/node11.html#SECTION0011200000000000000000 Language Reference 4.1 Naming and binding http://www.python.org/doc/ref/naming.html The rules are pretty simple, which probably means they're too simple to do whatever you're trying to explain about Scheme. You can write def outer(): x = 3 def f(arg): return arg * x return f(5) to have outer() return 15, but you can't write def outer(): x = 3 def f(arg): return arg * x x = 4 return f(5) to have outer() return 15, because 'f' will take the value of x from the enclosing scope, and that value is 4 at the time of the call. If you want to have f capture the value of x at that moment, you must manually introduce another layer of nesting: def outer(): x = 3 def inner(x): def f(arg): return arg*x return f f = inner(x) x = 4 return f(5) or you can try to structure your code so that you can avoid re-using the name 'x'. One common example of a situation where you can't avoid it is something like this: from Tkinter import * def button_func(i): print "pressed button", i def make_stupid_gui(): t = Tk() for i in range(10): b = Button(t, text="Button #%d" % i, command=lambda: button_func(i)) b.pack() make_stupid_gui() Instead, you must write def make_stupid_gui(): t = Tk() for i in range(10): def make_binding(i): return lambda: button_func(i) b = Button(t, text="Button #%d" % i, command=make_binding(i)) b.pack() A programmer who is more comfortable with objects than with lambdas might write something like this instead class ButtonCallback: def __init__(self, i): self.i = i def __call__(self, i): print "pressed button", i def make_stupid_gui(): t = Tk() for i in range(10): b = Button(t, text="Button #%d" % i, command=ButtonCallback(i)) b.pack() make_stupid_gui() > PS: I'm a newbie, so the answer in fact might be super-easy. Not an answer, but advice: when writing programs in Python, write Python programs. If it's your task to translate some Scheme (or any other language) into Python as literally as possible, my heart goes out to you. Jeff From hildegarde_roth at yahoo.de Thu Sep 18 13:50:46 2003 From: hildegarde_roth at yahoo.de (Hilde Roth) Date: 18 Sep 2003 10:50:46 -0700 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <95b4b9ac.0309171233.21f4c07@posting.google.com> Message-ID: <95b4b9ac.0309180950.30b44d89@posting.google.com> > Like it or not, there are no "different dimensions", just lists of lists > of lists... You are being too litteral. A list of list is like a 2D array from an indexing point of view, a list of lists of lists like a 3D array etc. E.g., (((1,10),(2,20),(3,30)),((-1,'A'),(-2,'B'),(-3,'C'))) is a 2 x 3 x 2 rectangular data structure and has 3 dimensions. Hence, e.g., l[0;2;1] ~ l[0][2][1] = 30 > [alist[2], alist[-3], alist[7]] and [alist[i] for i in [2, -3, 7]] I agree that comprehensions alleviate the problem to an extent. However the first notation is definitely cumbersome for all but the shortest index lists. > It covers the most common cases of list item extraction with a concise > syntax. Maybe but 1/ it is more or less redundant: the (x)range syntax could have been extended with the same effect 2/ it lacks generality since it can only generate arithmetic progressions Hilde From mertz at gnosis.cx Sun Sep 7 03:51:27 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sun, 07 Sep 2003 03:51:27 -0400 Subject: Redesign of Python site References: Message-ID: "Terry Reedy" wrote previously: |To me, the the purpose of the Python site is to convey information to |lots of different programmers. It should therefore be physically |readable by as many people as possible. and not just 20-30 year olds |with 20-20 vision. I completely agree with most posters on the demo webpage redesign. The fonts are horribly, unreadably small. And the whole is cluttered, busy, and difficult to get visually oriented to. As others observed, the low-contrast colors make the small fonts EVEN MORE difficult to read. Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From colarte at telesat.com.co Sun Sep 7 08:25:14 2003 From: colarte at telesat.com.co (colarte at telesat.com.co) Date: Sun, 7 Sep 2003 07:25:14 -0500 Subject: in Ram database? In-Reply-To: References: Message-ID: <1062937514.3f5b23aa6c549@ilpostino3.telesat.com.co> try searching for : gadfly Mensaje citado por "John D." : > Does anyone know if there is an "in-ram" dictionary based database > for Python. > > I can see some applications where this can really be powerful in > applications requiring 10,000 records or less. > > Is such a database available? If so, who is working on it, > or where is it? > > I've heard that Python supports a stand-alone database. I looked > for it in the Docs, and see the "dbm" module. I haven't found > any examples of code, so don't know how to use them. I'm one > of those guys that learn through examples, and have very little > luck in figuring out how to use anything unless I can see examples > of their use. > > My idea is that ALL datums would be Python Dictionary objects, so > not only can you store data, but python objects as well. > > Storage to disk would be through pickled files, or through CSV > format, allowing easy import and export from other databases. > > I'm sure something like this exists, I just haven't found it yet, > and if not, then I'm well on my way of implementing one myself. > > I kinda like the idea of being able to define smaller tables as > "in-memory" types, and the really large massive ones in other forms > managed by mySQL, PostGres, or bsddb3 databases. > > Any leads you guys??? > > JD > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Telesat, m?s f?cil...m?s Internet. http://www.telesat.com.co/ From jacobsmail at gmx.net Wed Sep 24 16:10:57 2003 From: jacobsmail at gmx.net (Jacob H) Date: 24 Sep 2003 13:10:57 -0700 Subject: Newbie: Changing a string to a class attribute. Message-ID: <33fbf9ec.0309241210.7acfddb9@posting.google.com> This is a very simple problem and I'm sure the answer is a no brainer. However my brain can't see the answer. ;) Given code like this: def exec_method(object, method): # object is an instantiated object, e.g. log # method is a string that matches a method of object, e.g. "update" # code stuff here that calls object.method, e.g. log.update() What is the best way to turn method, a string, into a valid reference to the actual class method? My first thought was eval(). But I can't do this: eval("class.method()") Eval will look for a method actually called method() and there isn't one. What's a good solution for this? Heck, for all I know, Python implicitly provides functionality to solve this problem. Can anyone help? :) Jake From jlh at cox.net Sun Sep 7 09:07:18 2003 From: jlh at cox.net (Jeff Hinrichs) Date: Sun, 07 Sep 2003 13:07:18 GMT Subject: Comments on Python Redesign References: Message-ID: "Tim Parkin" wrote in message news:mailman.1062934990.9290.python-list at python.org... [...snip...] > Perhaps the people who have commented on the site should realise it's a > proposal and a work in progress. As constructive comments go the only > feedback I have gathered is that the fonts are too small and the > contrast is > a little low. I've adjusted contrast on key elements and also increased > the > font size. These pages are here : [...snip...] I agree that the python.org site could use a face-lift, however, my concern with the design presented is along the lines of page size and/or browser compatibility. If you design via CSS using too many of the newer features some older browsers will have problems rendering, if you don't use CSS for that layout then you'll be using too many graphics. You should keep in mind the fact that Python is used internationally. So bandwidth, browser compatibility and internationalization are all very valid concerns. If the redesign limits the number of people who can access it's information or hinders their access to the same then I would be (-1) on the effort. Remember, that the most popular and highly used sites, i.e. google and yahoo, are quite boring in a design sense but are off the chart for usability and accessibility. It's the content and the accessibilty to that content that has made them so popular. I would vote to emulate these attributes in any python website redesign. - Jeff From claird at lairds.com Tue Sep 2 09:32:44 2003 From: claird at lairds.com (Cameron Laird) Date: Tue, 02 Sep 2003 13:32:44 -0000 Subject: artificial intelligence References: Message-ID: In article , Alex Martelli wrote: . . . >ways. There's quite a substantial body of literature, by now, on the >general issue of frequent fallacies on reasoning about probabilities. . . . Computing-related references on this general issue appear in . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From ulysses_dm at yahoo.com.cn Thu Sep 11 12:14:26 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 11 Sep 2003 09:14:26 -0700 Subject: PyQt: Can't show PY variable in QT filedialog as initially parameter Message-ID: <43e3984e.0309110814.7d759662@posting.google.com> Hi, I use PyQt 3.8 non-commercial version in win32. I get a big question. I Can't show PY variable in QT filedialog as initially parameter. Code sample is following: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ fileName="test.avi" def saveSomething(aString): dl = QFileDialog.getSaveFileName(aString, "*.*", self, "FileDialog") or dl = QFileDialog.getSaveFileName(QString(aString), "*.*", self, "FileDialog") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ these code can't show corrent string. If I use string constant. dl = QFileDialog.getSaveFileName("test.avi", "*.*", self, "FileDialog") Dialog show it correctly. Thanks. Ulysses From newsgroups at jhrothjr.com Fri Sep 5 11:35:35 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 11:35:35 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> Message-ID: "Grant Edwards" wrote in message news:3f58a2bd$0$156$a1866201 at newsreader.visi.com... > In article , John Roth wrote: > > > Technically, it would be possible to make "self" a reserved > > word, and not have to put it in the method declaration. > > However, there are a lot of people who use something other than > > the word "self," so that would break existing code. > > It would also make the language more complex and irregular. How? John Roth > > -- > Grant Edwards grante Yow! Could I have a drug > at overdose? > visi.com From cliechti at gmx.net Wed Sep 10 17:53:17 2003 From: cliechti at gmx.net (Chris Liechti) Date: 10 Sep 2003 23:53:17 +0200 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> <3F5F8742.C1C66903@engcorp.com> <3F5F95B9.A8CB5786@easystreet.com> Message-ID: achrist at easystreet.com wrote in news:3F5F95B9.A8CB5786 at easystreet.com: > Peter Hansen wrote: >> >> >> Queue.Queue.get() ... >> > > That looks good. But that needs a thread to block, right? yes > A generator manages to run without being a thread (at least > overtly). If we have the suck() statement, we also need > something that's the opposite of a generator (a Sucker?) > and something that's the opposite of an iterator (a Suckee?). > I'm starting to get an idea why this is completely not all > there. basicaly you poll every generator (or more precicly "iterable" as that is what a generator returns), one after the other... enjoy the link below. > The main question this raises is "How lightweight are threads?" > Can I program with dozens or hundreds of python threads in a > program (for example under Windows) and not notice that this is > an inefficient or inept coding style? this one is for you :-) http://www-106.ibm.com/developerworks/linux/library/l-pythrd.html you wont get happy with hundrets of native threads, but with the light ones from above you can have thousands... generaly you will find interesting stuff here (one line): http://www- 106.ibm.com/developerworks/views/linux/articles.jsp?sort_order=desc&expand= &sort_by=Date&show_abstract=true&view_by=Search&search_by=charming+python%3 A chris -- Chris From opo at opo.com Thu Sep 11 09:58:52 2003 From: opo at opo.com (franck) Date: Thu, 11 Sep 2003 15:58:52 +0200 Subject: GET and POST Message-ID: HI, this is my code params = {} params['fuseaction'] = '*****'; params['user'] = '***'; params['password'] = '**********'; params['num_card'] = '******'; params['date_of_birth'] = '****'; params = urllib.urlencode(params) f = urllib.urlopen("http://bidule.com",params) print f.read() my contact tell me i must do a GET or fuseaction and POST for other param. i dont know how to do this and if its possible. someone tell me its ok to do that, but how in python? i dont unsderstand the different between GET and POST but i know how to code it separately. thx in advance. From mwh at python.net Mon Sep 29 14:40:47 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Sep 2003 18:40:47 GMT Subject: A startup puzzle References: Message-ID: <7h365jb1lzo.fsf@pc150.maths.bris.ac.uk> Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: > On Mon, 29 Sep 2003 11:31:05 -0500, "Edward K. Ream" > wrote: > > >Any ideas for a clean solution? Thanks. > > I am not sure that I understand what you are saying, but I'll make a > quick suggestion... > > Perhaps 'app' can be a global variable within 'leoGlobals', but > assigned the value 'None' when the module is imported. Your > initialisation code can then reassign the variable at the appropriate > time. This wont work. --- a.py --- a = None --- b.py --- import a a.a = 1 --- c.py --- from a import a import b print a running c.py will print "None". Names, objects and bindings, remember :-) Cheers, mwh -- Or if you happen to be resigned to the size of your trouser snake and would rather not be reminded of it, training a shared classifier to reject penis-enlargement spam stops Barry from getting the help he so desperately needs. -- Tim Peters, c.l.python From list-python at ccraig.org Fri Sep 12 08:46:54 2003 From: list-python at ccraig.org (Christopher A. Craig) Date: 12 Sep 2003 08:46:54 -0400 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911162016.02027750@telecommunity.com> <3F615217.8060106@sci.fi> Message-ID: Harri Pesonen writes: > After sleeping over night, I think that I got it. :-) The simple solution is, > that each thread created in Python gets its own independent interpreter state > as well. And there could be a separate thread-global interpreter state for > shared memory access. Access to this global state would always be > synchronized. There could even be multiple named global states, so that the > thread interlocking could be minimized. The python syntax for creating objects > in this global state should be invented: > > > synchronize a = "abcd" > > Also when creating the new thread, it's arguments would be copied from the > creating state to the new state. > > > What does it sound? Of course it would be incompatible with the current > threading system in Python, but it would be totally multithreading, no global > interpreter lock needed. It would be faster than current Python, there would > be no need to free or acquire the lock when calling OS functions, and no need > to check how many byte codes have been processed, etc. > Couldn't you do this now with multiple processes and the shm module? -- Christopher A. Craig "I affirm brethren by the boasting in you which I have in Christ Jesus our Lord, I die daily" I Cor 15:31 (NASB) From logistix at cathoderaymission.net Mon Sep 29 16:43:36 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 29 Sep 2003 13:43:36 -0700 Subject: Python parser that records source ranges References: Message-ID: <3c91a864.0309291243.6fb1196f@posting.google.com> Jonathan Edwards wrote in message news:... > The parser library module only records source line numbers for tokens. I > need a parser that records ranges of line and character locations for > each AST node, so I can map back to the source. Does anyone know of such > a thing? Thanks > > Jonathan You know there's not going to be a one-to-one relationship, right? Most ast nodes are symbols and aren't going to match to any tokens. Python asts also use a lot of intermediate nodes to enforce operator precidence. Anyway, I have some rather specialized code in PyXR that syncs tokens to an ast. You probably won't be able to use it out of the box but it should give you a good start: http://www.cathoderaymission.net/~logistix/PyXR/ The source file of particular interest to you would be astToHtml.py: http://tinyurl.com/p3cn From r.erens at eurosys.nl Mon Sep 29 11:34:20 2003 From: r.erens at eurosys.nl (Roger Erens) Date: Mon, 29 Sep 2003 17:34:20 +0200 Subject: warnings during installation of python2.3.1 on SCO_SV 3.2v5.0.5 Message-ID: <6D9E338D57C2D411AC5800105AF41E12FE7ABF@MAILNT> Dear list, I'm trying to install python2.3.1 on an SCO-box. After running ./configure --prefix=/usrdir/rogere the output of make shows (among others:) running build running build_ext building 'struct' extension creating build creating build/temp.sco_sv-3.2-i386-2.3 cc -DNDEBUG -O -Kpic -belf -belf -Ki486 -DSCO5 -I. -I/usrdir/rogere/Python-2.3.1/./Include -I/usrdir/rogere/include -I/usrdir/rogere/Python-2.3.1/Include -I/usrdir/rogere/Python-2.3.1 -c /usrdir/rogere/Python-2.3.1/Modules/structmodule.c -o build/temp.sco_sv-3.2-i386-2.3/structmodule.o creating build/lib.sco_sv-3.2-i386-2.3 cc -Wl,-G,-Bexport build/temp.sco_sv-3.2-i386-2.3/structmodule.o -L/usrdir/rogere/lib -L/usr/local/lib -o build/lib.sco_sv-3.2-i386-2.3/struct.so *** WARNING: importing extension "struct" failed with exceptions.AttributeError: 'module' object has no attribute 'load_dynamic' I also get lots of these warnings for other extensions, like 'regex', 'pcre', '_hotshot', etc, etc. In the end I can start up the Python interpreter; however, importing one of the above extensions fails: >python Python 2.3.1 (#2, Sep 29 2003, 16:43:28) [C] on sco_sv3 Type "help", "copyright", "credits" or "license" for more information. >>> import regex Traceback (most recent call last): File "", line 1, in ? ImportError: No module named regex Does anyone have a clue about how I should resolve these warnings? I'd be glad to send any extra needed information if required. Best regards and thanks in advance, Roger Erens > uname -X System = SCO_SV Node = ontwik2 Release = 3.2v5.0.5 KernelID = 98/07/02 Machine = i80386 BusType = ISA Serial = 5FL004745 Users = 30-user OEM# = 0 Origin# = 1 NumCPU = 2 >ld -V SCO UNIX Development System Release 5.1.1A 27Jul98 395 /usrdir/rogere/Python-2.3.1 >cc -V SCO UNIX Development System Release 5.1.1A 27Jul98 From garyr at fidalgo.net Sun Sep 21 10:52:02 2003 From: garyr at fidalgo.net (Gary Richardson) Date: Sun, 21 Sep 2003 07:52:02 -0700 Subject: Tkinter cursor question References: Message-ID: [snip] > > @sourceName > This form only works on Windows, and will load a Windows system cursor > (.ani or .cur) from the file specified in sourceName. > > Kindly > MichaelP > Michael, Thanks for your reply. I am using Windows so I guess I'm out of luck as far as designing my own cursor. I tried the form that is supposed to work with windows but no luck with that either. The code below produces the error message: TclError: bad cursor spec "@CROSS_M.CUR". I also tried using the full pathname ("@C:\windows\cursors\cross_m.cur" and "@c:\\windows\\cursors\\CROSS_M.CUR") but the result was the same. Any further advice? Thanks, Gary Richardson ------------- from Tkinter import * root=Tk() Text(root,bg="white",cursor="@CROSS_M.CUR").pack() root.mainloop() From pweldon at mindspring.com Sun Sep 21 08:26:27 2003 From: pweldon at mindspring.com (Phil Weldon) Date: Sun, 21 Sep 2003 12:26:27 GMT Subject: python script as an emergency mailbox cleaner References: Message-ID: Inboxer for Outlook is a plugin written with Python that will analyze collections of what you consider legitimate e-mail and and what you consider illegitimate e-mail. I downloaded it and ran it against a collection of 1500 messages generated by the Worm.Automat.AHB and 265 the latest legitimate e-mails I've received. After the analysis, Inboxer has detected about 250 Worm.Automat.AHB generated messages with no false negatives and no false positives (granted there were only three new legitimate e-mails. Phil Weldon "Alex Martelli" wrote in message news:G6Zab.127313$R32.3854946 at news2.tin.it... > All my mailboxes have been filling up with files of about 130k to 150k, no > doubt copies of some immensely popular virus. So, I've no doubt lost lots > of real mail because of "mailbox full" conditions (the proliferating fake > bounce messages more or less ensure nobody knows their mail to me has > bounced, either). > > As an emergency response I and Anna developed, over the last half hour, a > small Python script to be run from cron every few minutes and automatically > scrub any POP3 mailbox from files in the target size range. I'm saving them > to a local file for potential later perusal, but that's obviously easy to > comment out if needed. Here's the tiny script in question...: > > import poplib > import time > > print 'Start at', time.asctime() > > host = 'pop.mail.yahoo.com' > port = 110 > user = 'aleaxit' > pasw = 'secret' > > logfilename = 'bigjunk' > minsize = 130000 > maxsize = 180000 > fromtag = 'From aleaxit at yahoo.com %s\n' > > ps = poplib.POP3(host, port) > ps.user(user) > ps.pass_(pasw) > > messages = ps.list() > print '%d messages, %d bytes' % (len(messages[1]), messages[-1]) > > logfile = open(logfilename, 'a') > > for sms in messages[1]: > sid, ssize = sms.split() > if minsize <= int(ssize) < maxsize: > message = ps.retr(sid) > print 'retrieving and deleting msg#%s, %d bytes, %d lines' % ( > sid, message[-1], len(message[1])) > logfile.write(fromtag % time.asctime()) > for line in message[1]: > logfile.write(line) > logfile.write("\n") > logfile.write('\n') > ps.dele(sid) > > ps.quit() > > print 'Done at', time.asctime() > print > > > Hope it can come in useful to somebody...!!! > > Alex & Anna > From nowan.noware at nohowe.net Mon Sep 8 14:40:09 2003 From: nowan.noware at nohowe.net (Nowan) Date: Mon, 08 Sep 2003 18:40:09 GMT Subject: spyce hangs on 'file not found' References: <3F5804CE.3050109@nohowe.net> Message-ID: <3F5CCBFF.2050306@nohowe.net> > Works fine, except when I attempt to read a nonexistent file. In other > words, I go after /template/stuff.html but stuff.html doesn't exist. > > Ordinary CGIs work correctly, meaning Apache correctly handles a 'file > not found' > > Spyce works differently. The browser hangs. My CPU utilization goes to > 100% and I get a runaway python process I can't kill, even as > administrator. > > Any suggestions? A python bug or a spyce bug? Reading the source for > either is way beyond my level now? Known problem? Workaround? > > Anyone know how I can kill the runaway python process? > -------------------------------------- Still looking at this. I see from the spyce doc that spyce has special error codes spyceNotFound, spyceError and spyceForbidden, which obviously correspond to the Apache NotFound, SystemError and Forbidden error codes, (404, 500, etc). Perhaps I need to configure something to trap spyceNotFound, so that it doesn't go into an hung state? Does anybody use Spyce? From cagi at cs.tu-berlin.de Tue Sep 9 10:40:28 2003 From: cagi at cs.tu-berlin.de (Carsten Gips) Date: Tue, 9 Sep 2003 16:40:28 +0200 Subject: Jython: jythonc and cPickle Message-ID: <20030909164028.1bd961d5.cagi@cs.tu-berlin.de> Hi, I have a jython script, which should load a pickled object: file = "blabla" infile = open(file, 'rb') o = cPickle.load(infile) When I put this code in a file and execute it using jython, everything works well. However, when I freeze the code using jythonc (using: jythonc -a -j bla.jar bla.py) and start the program using java (java -jar bla.jar), then the cPickle.load throws an exception and cannot load the object. Does anybody know a solution to this problem? I have to use the freezed version .... Thanks Carsten -- wehr ainen rechtschreipfaehler fintet, dahrf ien behallten From simonb at webone.com.au Tue Sep 16 20:26:06 2003 From: simonb at webone.com.au (Simon Burton) Date: Wed, 17 Sep 2003 10:26:06 +1000 Subject: Extending the python language References: <5696a130.0309161449.5944f7fa@posting.google.com> Message-ID: On Tue, 16 Sep 2003 15:49:21 -0700, John D wrote: > I'm writing a class definition in python with some array atributes > from Numeric 2.0. I'm using UserArray, UserList, to subclass my > classes. But some of the methods I need to write in C mainly because > of computing speed. I need to pass to those C functions array and > lists objects that the C functions can access their contained values > like arrays and lists. PyRex is good at this. Have a look at the cgkit for an example. Simon Burton. From xtian at toysinabag.com Mon Sep 22 17:47:51 2003 From: xtian at toysinabag.com (xtian) Date: 22 Sep 2003 14:47:51 -0700 Subject: Slicing vs .startswith References: <3F6F3E38.5221D7E7@engcorp.com> Message-ID: David Eppstein wrote in message news:... > In article <3F6F3E38.5221D7E7 at engcorp.com>, > Peter Hansen wrote: > > > > For example, which one of the following would be more efficient, or , > > > moreover, more pythonic? > > > > > > if aa[:3] == 'abc': > > > > > > vs > > > > > > if aa.startswith('abc'): > > > > The latter is clearly more readable. > > More Pythonic, too, I think. "Readability counts," and "There should be > one-- and preferably only one --obvious way to do it." In this case, > startswith must be the one obvious way, or else why would it exist in > the standard library at all? It's also much more maintainable - if in the future that 'abc' needs to change to 'abcdef', the slicing version requires changes in two places (just asking for bugs), while startswith requires only one. Of course, all these things (readability, maintainability and pythonicism) are fairly closely interrelated. xtian From FBatista at uniFON.com.ar Thu Sep 11 13:29:26 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 11 Sep 2003 14:29:26 -0300 Subject: Import question Message-ID: #- Any ideas???? I always try to put all the site-specific modules in the directory Python23/lib/site-packages. Bonus: Python searchs in that place automatically. . Facundo From davecook at nowhere.net Wed Sep 10 02:31:19 2003 From: davecook at nowhere.net (David M. Cook) Date: Wed, 10 Sep 2003 06:31:19 GMT Subject: pygtk clist usage References: Message-ID: In article , Ted Holden wrote: > If anybody has any sort of a clue as to how to use a clist generated by > glade as a list, the 'GtkList' changed to 'GtkClist' by hand, and add input > strings using 'append' and end up seeing more than just the first character > of each line, I'd appreciate hearing from them. Sounds like you are appending a string instead of a list of strings. BTW, CList is deprecated (meaning it will go away in the next major gtk release). ListStore/TreeView can be a bit hard to make the transition to, though, as the documentation is rather scattered and fragmentary. Best sources of info are * The examples in the pygtk-demo directory. * The FAQ: http://www.async.com.br/faq/pygtk/index.py?req=all * The manual: http://www.moeraki.com/pygtkreference/pygtk2reference/ Dave Cook ____)/ \(____ _,--''''',-'/( )\`-.`````--._ ,-' ,' | \ _ _ / | `-. `-. ,' / | `._ /\\ //\ _,' | \ `. | | `. `-( ,\\_// )-' .' | | |/' \' `\( \(_)/ )/' `/ `\| ` ` V V ' ' Splifford the bat says: Always remember Don't waste time learning deprecated APIs. From buzzard at urubu.freeserve.co.uk Thu Sep 4 18:46:09 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Thu, 4 Sep 2003 23:46:09 +0100 Subject: Selecting elements from a list References: <87y8x4w6ym.fsf@gvdnet.dk> Message-ID: "Martin Christensen" wrote in message news:87y8x4w6ym.fsf at gvdnet.dk... > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Howdy! > > Suppose I have a list A containing elements that I want to put into > list B if they satisfy some property. The obvious way of doing it > would be, > > B = [] > for i in A: > if A.property(): > B.append(i) > > Now, list comprehensions, map() etc. can make a lot of list operations > easier, but I haven't found a shorter, more elegant way of doing this. > Have I missed something, or will I have to stick to my explicit loops? > > Martin > Is this the sort of thing you mean? >>> A = [0, 1, 2, 'four', 'five', 6.0] >>> [x for x in A if isinstance(x, str)] ['four', 'five'] >>> Duncan From BrenBarn at aol.com Sun Sep 7 23:36:38 2003 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 8 Sep 2003 03:36:38 GMT Subject: exec code with timeout? Message-ID: I am fiddling around with a Python-based MUD which allows users to code MUD objects in Python. This code is executed from within the server code with "exec". However, sometimes errors in user code can result in infinite loops, which cause the MUD to hang. I am wondering if there is a way to put a timeout on the exec, so that it returns control to the main program if the user code doesn't return within a certain amount of time. I am not concerned with security per se here -- in general I can assume that any users who are using the MUD are trusted and will not write malicious code. I am chiefly aiming to catch simple, unintentional programming errors. For instance, I don't want the MUD to hang just because someone innocently forgot to include a break inside a "while 1:" block. All I need is a very crude form of control -- a simple timeout would do. I have looked at the thread modules, hoping that I could exec the user code in a separate thread, sleep in the main thread, and then at the end of the time limit terminate the user code thread. However, there doesn't seem to be any way to terminate a subthread from within the main thread. Am I entirely out of luck here, or is there some module than can do what I want? (I am working primarily on Windows at this point, but I would like a solution that works on as many platforms as as possible.) -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From dave at 3dex.com Thu Sep 11 19:34:22 2003 From: dave at 3dex.com (Dave Benjamin) Date: Thu, 11 Sep 2003 23:34:22 GMT Subject: Flash Remoting in Python? References: <7712111.0309111357.3be3b591@posting.google.com> Message-ID: <2E78b.1002$8g2.829@news1.central.cox.net> "Randy" wrote in message news:7712111.0309111357.3be3b591 at posting.google.com... > Does anyone have any interest in a project like this? It would be > port for the most part; the AMF format is already well known. In > addition, there is a lot of similarities between ActionScript objects > and native Python objects; porting between the two data types would > not be difficult. I think it would be fantastic to have support for this in Python. In fact, the only thing that's even made me consider using PHP lately is the AMFPHP library. But be careful! Last time I checked, AMFPHP was not endorsed or supported by Macromedia. This means a) it might not be legal, especially with the DMCA and other such intrusions, b) Macromedia could change their protocol anytime they want, causing everyone to have to reverse-engineer the changes. Another way to set up an RPC interface between Flash and Python would be to use plain old HTTP GET/POST, with either urlencoded key-value pairs or WDDX as a serialization format. (PyXML supports WDDX, as does PHP, as does Flash if you Google around for the wddx.as script). Cheers, Dave PS. Still a good idea for a project, though. =) From aahz at pythoncraft.com Fri Sep 26 14:14:12 2003 From: aahz at pythoncraft.com (Aahz) Date: 26 Sep 2003 14:14:12 -0400 Subject: PyCon Announcement: Mitch Kapor is opening keynote speaker References: Message-ID: In article , Ville Vainio wrote: >PyCon Chair writes: >> >> and as a co-founder and the first chairman of the San Francisco-based >> Electronic Freedom Foundation, and has been an active entrepreneur in > >It's Electronic *Frontier* Foundation, I think. Oops. It was spelled correctly in my version, but got changed when someone else edited it. Oh, well. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From peter at engcorp.com Thu Sep 18 12:38:05 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Sep 2003 12:38:05 -0400 Subject: win32comm References: Message-ID: <3F69DF6D.5588E4E9@engcorp.com> > Alberto Vera wrote: > > Hello: > > Could you tell me How I can solve this problem? > > Regards > > import win32com.client > ImportError: No module named win32com.clieny Cut and paste the entire error message rather than retyping it, to avoid mistakes such as the above. Assuming that your error message doesn't say what you say it says, but rather a message about "win32com.client", then the next question is have you installed the win32all package? This is not included with Python, but must be downloaded separately unless you are using the ActiveState package. Go to the Python download page and follow the links to get the package, then run the installer. Afterwards the above code should work fine if you've done everything correctly. -Peter From knightsofspamalot-factotum at gvdnet.dk Fri Sep 5 02:06:23 2003 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Fri, 05 Sep 2003 08:06:23 +0200 Subject: Selecting elements from a list References: <87y8x4w6ym.fsf@gvdnet.dk> <2xR5b.354503$YN5.241285@sccrnsc01> Message-ID: <87fzjbu5uo.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "David" == David C Fox writes: David> B = filter(lambda x: x.property(), A) Now, if I'd paid better attention to the library documentation... :-) Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAj9YJ98ACgkQYu1fMmOQldVcoACg4UwLuvBfdx1aZV0qXJgomgQ4 5OkAnAgsf4fdEY0j9ekDPOrWytpKPqhJ =NcyH -----END PGP SIGNATURE----- From adam at gliwice.pl Fri Sep 5 13:14:28 2003 From: adam at gliwice.pl (Adam Przybyla) Date: Fri, 5 Sep 2003 17:14:28 +0000 (UTC) Subject: reading large file References: <9bd0dd3f.0309030400.7fa2dc0f@posting.google.com> Message-ID: guillaume wrote: > I have to read and process a large ASCII file containing a mesh : a > list of points and triangles. > The file is 100 MBytes. > > I first tried to do it in memory but I think I am running out of > memory therefore I decide to use the shelve > module to store my points and elements on disks. > Despite the fact it is slow ... Any hint ? I think I have the same > memory problem but I don't understand why > since my aPoint should be removed by the gc. > Have you any idea ? ... try PyTables;-) Regards Adam Przybyla From br_y at yahoo.de Fri Sep 5 04:26:00 2003 From: br_y at yahoo.de (Birgit Rahm) Date: Fri, 5 Sep 2003 10:26:00 +0200 Subject: compiling python Message-ID: Hallo newsgroup, because so many people helped me, I hope for help onesmore. If I compile a python py file to a pyc file, will there the paths of the included files (or other paths) hardly be written to the pyc file and why. (Does not find this import file without this path anymore?) Which sense is behind there? TIA,Birgit From max at alcyone.com Tue Sep 9 15:18:26 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Sep 2003 12:18:26 -0700 Subject: Jython class names References: Message-ID: <3F5E2782.6382BDC5@alcyone.com> Michael Chermside wrote: > Simple rule. ALWAYS use "==" for comparing strings, NEVER use "is". > The > only exception is if you are working on the internals of the string > class, or perhaps writing some subclass of string with wierd behavior. > The behavior of "is" is undefined for all immutable built-in types -- > not "undefined behavior" in the sense of the C standard (computer may > grow legs and wander out of the room if you do this), but "undefined" > in the sense that comparing two integers or two strings with "is" MAY > return True, or it may return False, and no promises are made as to > which way it will go. The usual Standard terminology for this is "unspecified"; as you point out, "undefined" means nasal demons. There's also a third possibility, "implementation defined," which is the same as unspecified except the implementation must document its choice of behaviors. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Silence is the most perfect expression of scorn. \__/ George Bernard Shaw From peter at engcorp.com Fri Sep 19 12:11:29 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Sep 2003 12:11:29 -0400 Subject: was: Re: looking for MOP documentation References: <3F62123C.F671D058@engcorp.com> <3F6319E9.4C7BAA0F@engcorp.com> <3F66F516.3D06D946@engcorp.com> <3F69AD0F.53D51719@engcorp.com> <3F69D215.5649AF66@hotmail.com> <3F69DFEB.5B05CED8@engcorp.com> <7h37k45j895.fsf@pc150.maths.bris.ac.uk> Message-ID: <3F6B2AB1.2D839EF5@engcorp.com> Michael Hudson wrote: > > Peter Hansen writes: > > > Alan Kennedy wrote: > > > > > > Peter Hansen wrote: > > > > Key phrase: "Metaobject protocols are interfaces to the language > > > > that give users the ability to incrementally modify the language's > > > > behavior and implementation...". Near as I can tell, part of the > > > > whole character of Python is that a user *cannot* do either of > > > > those things. > > > > > > Hmm, does this rephrasing hold any truth? > > > > > > "Metaclasses are interfaces to the python language > > > that give users the ability to incrementally modify the language's > > > behavior and implementation...". > > > > > > Isn't modifying standard behaviour the whole purpose of metaclasses? > > > > But it doesn't really modify the *language's* behaviour in the way > > implied by a simplistic reading of the above phrase. That is, the > > "obvious" interpretation is that syntax and grammar are being affected, > > not just the behaviour of one small slice of the language, specifically > > how classes behave. In some languages the two things are not so > > separate, but in Python they seem to be. > > Huh? Common Lisp's MOP doesn't change the language on that level, > either. No problem... I was deliberately taking a simplistic reading of the above, in an attempt to elicit discussion that would clarify whether it was an adequate description. Sounds like it's not. > Of course, there's a sense in which Common Lisp just doesn't have much > syntax, but Python's hardly overloaded with it, either. *The objects* > or to be more precise the *types* of objects themselves are what > determine really happens, and that's precisely the sort of thing > metaclasses let you play with. I guess this might get down to the question of whether Python is more about the syntax, grammar, keywords, and such, of the language or more about the standard types of objects which are provided with it. In my mind, it's very much the former and very little the latter, but maybe that's just me. Dicts and lists and integers are interesting and all, but I'm not sure it's their behaviour which makes Python Python. -Peter From mertz at gnosis.cx Wed Sep 24 21:09:25 2003 From: mertz at gnosis.cx (David Mertz) Date: Wed, 24 Sep 2003 21:09:25 -0400 Subject: Python Glossary References: Message-ID: |Thanks to people who submitted content for the Python Glossary: | http://manatee.mojam.com/python-glossary This glossary is quite nice to have. FWIW, my book also has a glossary, which may have some terms that would be useful also for the Python Glossary. Somehow it feels immodest to me to copy them over myself (an emotion I'm only occassionally struck by :-)); however, all permission is given for anyone else to do so, as they think is useful. The terms I define tend to be a bit less Python specific (despite being in a Python book)--and I confess it is a little bit of an oddball collection. Still, take a look at: http://gnosis.cx/TPiP/glossary.txt Yours, David... -- 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 newsgroups at jhrothjr.com Thu Sep 4 15:32:47 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 4 Sep 2003 15:32:47 -0400 Subject: basic language question References: Message-ID: "Michael Peuser" wrote in message news:bj820r$8up$05$1 at news.t-online.com... > > "Stephan Diehl" schrieb im Newsbeitrag > news:bj7ots$48j$06$1 at news.t-online.com... > > Once in a while, I get bitten by the fact, that mutating list methods such > > as 'append' or 'extend' return None instead of the (mutated) list itself. > > Is there a compelling reason for that? I googled around, but didn't find > > anything about this. > > There is a very old religious law saying: Thou shalt not cause side effects > by a function. > There is some wisdom in it but it is easily forgotten with languages which > do not differ between functions and routines. Like most "religious laws," it's a rule that has a multitude of exceptions. You can't do I/O without having side effects, something that the designers of functional languages have learned, sometimes the hard way. As far as I'm concerned, this is one of those things that Ruby did right. By convention, methods that modify the object as a side effect have names that end with an "!" (exclamation point.) Ruby usually supplies two methods in such cases, one that modifies the object, and one that creates a copy and then modifies the copy. Both methods return the modified or new object. It obeys the Principle of Least Surprise because if you forget the "!", you get the slow version that does a copy and leaves the original intact. Nice as the solution is, it's impossible to import it into Python cleanly without introducing catastrophic backward incomaptibilities. John Roth > > Kindly > Michael P > > From syver at inout.no Thu Sep 18 07:32:43 2003 From: syver at inout.no (Syver Enstad) Date: 18 Sep 2003 13:32:43 +0200 Subject: Closures in python References: <9caba98e.0309180208.692e9b68@posting.google.com> Message-ID: kbilsted at it-c.dk (Kasper B. Graversen) writes: > Having played with Smalltalk for the past month, I'm getting used to > passing code as arguments to methods... how easy is it to do this in > python? I haven't seen any recent postings on this subject here... It is fairly straightforward: import sys def funcThatTakesCallable(aCallable): aCallable('SomeString') class MyClass: def myFunc(): def myCallable(arg): print arg funcThatTakesCallable(myCallable) funcThatTakesCallable(self.anotherCallable) funcThatTakesCallable(lambda arg: sys.stdout.write('%s\n' % arg)) def anotherCallable(self, arg): print 'another', arg The major difference is that the anonymous form of a function (lambda) isn't allowed to contain statements, only an expression. This is rather crippling for Smalltalk/Ruby style coding and seems to lead to warts like list comprehensions instead of having simple methods in the collection interface that takes a block/lambda and calls this for each element of the collection. Example: newCollection = [each for each in collection if each != 'Sausage'] newCollection = collection.select(lambda each: each != 'Sausage') From uj797 at victoria.tc.ca Fri Sep 12 13:52:30 2003 From: uj797 at victoria.tc.ca (Arthur T. Murray) Date: 12 Sep 2003 09:52:30 -0800 Subject: Standards in Artificial Intelligence References: Message-ID: <3f61f9ce@news.victoria.tc.ca> "David B. Held" wrote on Wed, 10 Sep 2003: > "Arthur T. Murray" wrote in message > news:3f5f5dc3 at news.victoria.tc.ca... >> A webpage of proposed Standards in Artificial Intelligence >> is at http://mentifex.virtualentity.com/standard.html -- >> updated today. > [...] In one section, you define a core set of concepts (like > 'true', 'false', etc.), and give them numerical indexes. http://mentifex.virtualentity.com/variable.html#nen -- yes. > Then you invite programmers to add to this core by using > indexes above a suitable threshold, as if we were defining > ports on a server. [...] http://mentifex.virtualentity.com/newcept.html#analysis explains that Newconcept calls the English vocabulary (enVocab) module to form an English lexical node for any new word detected by the Audition module in the stream of user input. > [...] At one point, you address programmers who might > have access to a 64-bit architecture. Pardon me, but > given things like the "Hard Problem of Consciousness", > the size of some programmer's hardware is completely > irrelevant. [...] http://mentifex.virtualentity.com/standard.html#hardware (q.v.) explains that not "the size of some programmer's hardware" counts but rather the amount of memory available to the artificial Mind. The Mentifex AI Mind project is extremely serious and ambitious. Free-lance coders are morking on it in C++ and other languages: http://mentifex.virtualentity.com/cpp.html -- C++ with starter code; http://mentifex.virtualentity.com/java.html -- see Mind.JAVA 1 and 2; http://mentifex.virtualentity.com/lisp.html -- Lisp AI Weblog; http://mentifex.virtualentity.com/perl.html -- first Perl module; http://mentifex.virtualentity.com/prolog.html -- Prolog AI Weblog; http://mentifex.virtualentity.com/python.html -- Python AI Weblog; http://mentifex.virtualentity.com/ruby.html -- Ruby AI Blog (OO AI); http://mentifex.virtualentity.com/scheme.html -- Scheme AI Weblog; http://mentifex.virtualentity.com/vb.html -- see "Mind.VB #001" link. AI Mind project news pervades the blogosphere, e.g. at http://www.alpha-geek.com/2003/09/11/perl_ai.html -- etc. The Mentifex Seed AI engenders a new species of mind at http://sourceforge.net/projects/mindjava -- Mind2.Java -- and at other sites popping up _passim_ on the Web. AI has been solved in theory and in primitive, free AI source code. Please watch each new species of AI Mind germinate and proliferate. A.T. Murray -- http://www.kurzweilai.net/mindx/profile.php?id=26 - Mind-eXchange; http://www.amazon.com/exec/obidos/ASIN/0595654371/ -- AI Textbook; http://www.sl4.org/archive/0205/3829.html -- review by Dr. Ben G. http://doi.acm.org/10.1145/307824.307853 -- ACM SIGPLAN Notices. From llafba at gmx.net Mon Sep 15 09:59:56 2003 From: llafba at gmx.net (Tom) Date: Mon, 15 Sep 2003 15:59:56 +0200 Subject: list of lists Message-ID: Hi, I have a list that consists of lists. E.g. T=[[1, 2, 3], [4, 5], [6]] Is there a way to address the a specific component in the "inner" list directly? E.g. right now I want to get the second value of the first list. Unfortunately I have to save it to a variable first and then read it. a = T[0] print a[1] That kind of sucks, becaus I have to read a lot of values from a lot of lists! :-( Is there a faster way than my saving it to a "help variable" first? Thanks folks!! Regards, Tom From john at rygannon.com Wed Sep 10 14:19:16 2003 From: john at rygannon.com (John Dean) Date: Wed, 10 Sep 2003 18:19:16 GMT Subject: Problems with setting up mod_python and Apache Message-ID: <3f5f6b41$0$239$fa0fcedb@lovejoy.zen.co.uk> Hi I have set up httpd.conf according to installation and configuration instructions in the mod_python documentation. Yet when I enter the following URL http://localhost/test.py all I get is an Apache view of my htdocs directory. They if I click on test.py and open file dialog pops up. If I give the file a cgi extension and enter the following URL http://locathost/test.cgi it runs fine. I just can't figure out what I am doing wrong. -- Best Regards John From uce at ftc.gov Tue Sep 30 20:25:06 2003 From: uce at ftc.gov (Gordon Airport) Date: Tue, 30 Sep 2003 20:25:06 -0400 Subject: How do you use " " whe sending a command In-Reply-To: References: Message-ID: So close: \" or \' in a '' string. From fgeiger at datec.at Tue Sep 23 14:09:41 2003 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 23 Sep 2003 20:09:41 +0200 Subject: Mailbox cleaner on an IMAP basis? References: <3f6f2cfb@news.swissonline.ch> <3f6fdd8e@news.swissonline.ch> <1064298380.225028@yasure> Message-ID: <3f708c10@news.swissonline.ch> Ok, I came up with this so far, many thanks to all who contributed! Best regards Franz GEIGER import os.path, re from imaplib import * class Finder: def __init__(self, text): self._value = None results = self._rex.findall(text) if results: self._value = results[0] return def value(self): return self._value class UIDfinder(Finder): _rex = re.compile(r'UID (\d+)') class FileNameFinder(Finder): _rex = re.compile(r'\("application" ".+?" \("name" "(.+?)"\)') def ft(self): if not self._value: return None root, ft = os.path.splitext(self._value) return ft class SenderFinder(Finder): _rex = re.compile(r'From\: (.+)\r', re.M | re.I) class SubjectFinder(Finder): _rex = re.compile(r'Subject\: (.+)\r', re.M | re.I) class DateFinder(Finder): _rex = re.compile(r'Date\: (.+)\r', re.M | re.I) class MessageSummary: def __init__(self, uid, fileName, text): if not fileName: fileName = '' self._uid = uid self._fileName = fileName self._sender = '' self._subject = '' self._date = '' f = SenderFinder(text) if f.value(): self._sender = f.value() f = SubjectFinder(text) if f.value(): self._subject = f.value() f = DateFinder(text) if f.value(): self._date = f.value() return def __str__(self): return self.formatted() def formatted(self): return "From : %s\nSubject : %s\nAttachment: %s\nFile-Name : %s" % (self._sender, self._subject, self._date, self._fileName) def uid(self): return self._uid class Deleter: def __init__(self, server, messageSummaries): self._server = server self._messageSummaries = messageSummaries self._uids = [ms.uid() for ms in self._messageSummaries] return def run(self): uids = ','.join(self._uids) r = self._server.uid("STORE", uids, "+FLAGS.SILENT", "(\Deleted)")[0] if r in ("OK", "Ok", "ok"): return '' else: return "Error - Could Not Delete Messages" class Expunger: def __init__(self, server): self._server = server return def run(self): self._server.expunge() return print "Logging in." server = IMAP4("") server.login("", "") server.select() print "Begin to cleanup mailbox." messagesToDelete = [] i = 0 while (1): i += 1 r, d = server.fetch(i, "(UID BODY)") if r == 'NO' or d[0] is None: break uid = UIDfinder(d[0]).value() fnf = FileNameFinder(d[0]) fn = fnf.value() if not fn: print '.', continue ft = fnf.ft() r, d = server.fetch(i, "(BODY.PEEK[HEADER.FIELDS (Date From Subject)])") ms = MessageSummary(uid, fn, d[0][1]) if ft.lower() == ".exe": print '*', messagesToDelete.append(ms) else: print '.', if messagesToDelete: print "\n" * 4 print "%d messages are tagged to be deleted: " % len(messagesToDelete) for ms in messagesToDelete: print ms.formatted() print print if raw_input("Shall I delete them now (y/n)? ") == 'y': print 'Working...' d = Deleter(server, messagesToDelete) d.run() e = Expunger(server) e.run() print "Done. " else: print print "No messages to delete. " raw_input("Press any key to exit...") "Donn Cave" schrieb im Newsbeitrag news:1064298380.225028 at yasure... > Quoth "F. GEIGER" : > > | I've stopped here, because I could not figure out how to get at the ids of > | mails with attachments. And if I had that missing link, I'd run into the > | next hindrance: How can I delete a single message? IMAP4::delete() deletes a > | whole mailbox, not just a single mail. > | > | So my code really is only a few lines so far: > | > | i = IMAP4(myDomain) > | i.login(myUser, myPassword) > | i.select() # Select INBOX > | r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])") # Check 1st mail > | > | Seems I have to get a book about IMAP and how to use it... > > The IMAP4rev1 RFC of course covers these things, with examples. > 2060, I think it is. A message takes two steps to delete: first, > set a \Deleted flag on it, and then invoke expunge on the folder, > which will remove all delete-flagged messages in the folder. > > Donn Cave, donn at drizzle.com From vepxistqaosani at netscape.net Fri Sep 5 22:44:56 2003 From: vepxistqaosani at netscape.net (Vepxistqaosani) Date: Sat, 06 Sep 2003 02:44:56 GMT Subject: OT: best book in years In-Reply-To: References: Message-ID: <3F594A11.5020408@netscape.net> Patrick Useldinger wrote: > Hi All, > > I am going to stay in hospital for a week or so (nothing serious), and am > trying to find a book or two to read there. As I have not come across > anything spectacular recently (except Python in a Nutshell), I would like > to know what *you* consider to be the best book you have read in the last > few years, about Python or IT in general. > > -Patrick Patrick, I very much enjoyed one of Hofstadter's other books: Le Ton Beau de Marot: In Praise of the Music of Language. It is tangentially related to IT, since it's about languages. And language is worth thinking about, even by those of us who are reputed not to be able to use (human) languages well. (This last observation courtesy of my wife.) Fred From tim at remove_if_not_spam.digitig.co.uk Mon Sep 29 05:33:27 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Mon, 29 Sep 2003 10:33:27 +0100 Subject: Try/except vs. if/else References: <3F70598E.8020500@bu.edu> <8ef9bea6.0309270025.3c4d79ed@posting.google.com> Message-ID: On 27 Sep 2003 01:25:10 -0700, hungjunglu at yahoo.com (Hung Jung Lu) wrote: >Tim Rowe wrote in message news:... >> On Tue, 23 Sep 2003 11:10:49 -0400, Shu-Hsien Sheu >> wrote: >> >> >In my understanding, using try/except rather than if/else is more >> >pythonic. >> >> Rule of thumb: when the block of code is still doing what it's >> supposed to do, use if/else. If it's failing to do what it's supposed >> to do, use try/except. "except" should be an /exception/! >..... >> So try/except /only/ when something has gone wrong and you need to go >> into some sort of recovery or termination, /not/ for routine tests. > >You have a valid point of view, which nonetheless is not shared by >everyone. This is a recurring subject in the newsgroup. That's the nice thing about rules of thumb: they're not binding :-) Internal constructs don't bother me -- ultimately it all comes down to machine code which will be a mass of goto's. That doesn't mean that my code should be (could be!) a mass of goto's. And the last time I needed a goto for anything I was programming in BASIC; I don't need to use exceptions to emulate it in a language with decent flow control constructs (Python qualifies, of course!). From __peter__ at web.de Mon Sep 22 09:52:17 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Sep 2003 15:52:17 +0200 Subject: How to catch socket timeout? References: Message-ID: Achim Domma wrote: > "Bob Halley" wrote in message > news:mailman.1064178330.17024.python-list at python.org... >> So, all you need to do is put the socket.timeout except clause before >> any socket.error clause: >> >> try: >> self.data = self.page.read() >> except socket.timeout: ... >> except socket.error,e: ... > > Thanks, that works fine, but I don't understand why the exception was not > catched in my case. If I write it like this > > try: > self.data = self.page.read() > except socket.error,e: ... > except socket.timeout: ... > > the exception should be catched by the socket.error handler. Or am I > wrong? In my case it was not catched at all. Very mysterious from my point > of view, but it works now. > > Achim Achim, both you and me got it wrong the first time. The important part is to put both urlopen() and page.read() into the try clause, as Alan Kennedy has already shown. Both statements can throw a timeout exception, so it's sheer luck that it worked this time. And yes, if you put except socket.error: before except socket.timeout: the latter will never be executed. General structure: from urllib2 import urlopen import socket slowurl = "http://127.0.0.1/timeout?delay=100" socket.setdefaulttimeout(1) try: data = urlopen(slowurl) data.read() except socket.timeout: print "Timeout raised and caught" Peter From leonardbocock at yahoo.com Wed Sep 17 20:14:20 2003 From: leonardbocock at yahoo.com (lebo) Date: 17 Sep 2003 17:14:20 -0700 Subject: win32: 'Tailing' the NT event log using pipes? Message-ID: <63701d2f.0309171614.6efa1845@posting.google.com> Hi List I want to effectively 'tail' the NT event log - i.e. when a new event arrives in the log, parse it and decide whether to take an action. The track I've gone down is to create an event, and use event notify change; code snippet..... win32event.CreateEvent(.....) win32evtlog.NotfiyChangeEventLog(...) This works, but I can't get the very last (newest) record from the event log. Is it possible to open a named pipe to the event log. If so, how? This is new groud to me and examples or ways to do this would be appreciated. Thanks, Leonard From pulapaka at ligo.caltech.edu Mon Sep 8 18:41:58 2003 From: pulapaka at ligo.caltech.edu (Hari) Date: 8 Sep 2003 15:41:58 -0700 Subject: os.listdir Message-ID: <2ce42702.0309081441.5c73a772@posting.google.com> Hi, I have question regarding os.listdir() I wanted to know if this is a reliable way to check for files added to a directory?? files = os.lisdir(path) currentlen = len(files) // directory modified files = os.listdor(path) newlen = len(files) then the files in the range (currentlen -1) to (newlen -1) are all the files added to the directory. What I wanted to know was, is it guaranteed that between 2 calls os.listdir any files added to the directory are appended and the earlier order is maintained? thanks, Hari From mk at net.mail.penguinista Thu Sep 11 07:07:22 2003 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Thu, 11 Sep 2003 13:07:22 +0200 Subject: TTF fonts rendered in Python References: Message-ID: <3f60576a@news.mt.net.mk> > > One idea: > pygame can render with TTF fonts, > it can also save surfaces in tga format. > Then use PIL to convert to gif. The only > question is, can pygame do this without displaying > a window etc. > > Simon Burton. Perhaps python gdmodule will do? http://newcenturycomputers.net/projects/gdmodule.html -- ?????? (jabberID:damjan at bagra.net.mk) ISP techs know most computer problems are PEBKAC. (Problem Exists Between Keyboard And Chair) From daniel.dittmar at sap.com Thu Sep 25 11:23:09 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 25 Sep 2003 17:23:09 +0200 Subject: Stuck building a Python extension References: Message-ID: David Hughes wrote: > I'm nearly there building a Python extension module to access a set of > functions in a .dll, but I'm getting an unresolved external error for > one of the function calls (using MS Visual C++ V6). > > The function prototype is: > > extern short __stdcall SharewareLimit(char * s1, char * s2, short i); [..] > I would expect the code to be calling a function called > _SharewareLimit at 10 to match the size of the arguments (and which I > have called successfully from a Fortran program in the past), but the > unresolved external is _SharewareLimit at 12, implying that somewhere > the short 2-byte integer is being promoted to 4 bytes. > > I know this is probably a C compiler (settings?) not a Python > problem, but I'd appreciate some assistance as my knowledge in this > area is sketchy. C compilers are generally promoting shorts to ints and floats to doubles when passing them as arguments. This is reflected in the @12. #pragma pack (2) didn't work either, so I'm out of ideas. Do you know which language created the DLL? Daniel > > Thanks, David. From jepler at unpythonic.net Thu Sep 4 09:42:43 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 4 Sep 2003 08:42:43 -0500 Subject: Arguments of function as out In-Reply-To: <20030904125110.GC14960@unpythonic.net> References: <20030904125110.GC14960@unpythonic.net> Message-ID: <20030904134243.GD14960@unpythonic.net> On Thu, Sep 04, 2003 at 07:51:15AM -0500, Jeff Epler wrote: > I found this result when searching for 'omniorbpy "out parameter"': > http://www.omniorb-support.com/pipermail/omniorb-list/2000-April/015244.html > I don't know for certain that this is the way omniorbpy behaves today, > but it is a very pythonic way to work. [...] > | I recommend that you read the mapping specification, which you can > | download from > | > | http://www.omg.org/cgi-bin/doc?ptc/00-01-12 [Replying to my own post] The current version of that document can be retrieved from http://www.omg.org/technology/documents/formal/python.htm -> http://www.omg.org/cgi-bin/doc?formal/02-11-05 -> http://www.omg.org/cgi-bin/apps/doc?formal/02-11-05.pdf or http://www.omg.org/cgi-bin/apps/doc?formal/02-11-05.ps Page 1-12 discusses the treatment of "out" and "inout" parameters and the mapping onto Python return values: Operations of an interface map to methods available on the object references. Parameters with a parameter attribute of in or inout are passed from left to right to the method, skipping out parameters. The return value of a method depends on the number of out parameters and the return type. If the operation returns a value, this value forms the first result value. All inout or out parameters form consecutive result values. The method result depends then on the number of result values: . If there is no result value, the method returns None. . If there is exactly one result value, it is returned as a single value. . If there is more than one result value, all of them are packed into a tuple, and this tuple is returned. Assuming the IDL definition interface I{ oneway void stop(); bool more_data(); void get_data(out string name,out long age); }; a client could write names={} while my_I.more_data(): name,age = my_I.get_data() names[name]=age my_I.stop() Jeff From shane at zope.com Thu Sep 11 16:14:51 2003 From: shane at zope.com (Shane Hathaway) Date: Thu, 11 Sep 2003 16:14:51 -0400 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <1063310587.2069.247.camel@localhost.localdomain> References: <3F60C3DA.6070409@zope.com> <1063310587.2069.247.camel@localhost.localdomain> Message-ID: <3F60D7BB.2060104@zope.com> Jeremy Hylton wrote: > This sounds like POSH. There was a paper about it at PyCon. > > http://poshmodule.sourceforge.net/posh/html/ Excellent. Thank you for the pointer. Shane From ulope at gmx.de Thu Sep 18 08:41:27 2003 From: ulope at gmx.de (Ulrich Petri) Date: Thu, 18 Sep 2003 14:41:27 +0200 Subject: [NEWBIE] How to call an external program References: <2f9jmvcct6ai7dcg1ghhmm6bc7beuo18h0@4ax.com> Message-ID: "Philipp Neuhaus" schrieb im Newsbeitrag news:2f9jmvcct6ai7dcg1ghhmm6bc7beuo18h0 at 4ax.com... > Hi, > I want to convert an image file, so I have to call an external > program. > How can I do this? > > (i want to call "sfftobmp -tifs input tempfile" and "tiff2ps tempfile* > | ps2pdf [output]") > -----code---cut here---- import os def convertImage(infile, outfile): os.system('sfftobmp -tifs %s tempfile' % infile) os.system('tiff2ps tempfile* | ps2pdf %s' % outfile) convertImage('/home/user/in.tif', '/home/user/out.pdf') -----code---cut here---- HTH Ciao Ulrich From NO-MAIL at hotmail.com Tue Sep 16 17:52:04 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 21:52:04 GMT Subject: None, False, True References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> Message-ID: <8CL9b.13745$x21.7872@twister.southeast.rr.com> "Skip Montanaro" wrote in message news:mailman.1063744462.12059.python-list at python.org... > > >> If I remember it right, None is going to be promoted into keywords > >> soon. Therefore the warning. > > M-a-S> Will it be lower-case (together with false and true) like all > M-a-S> other keywords or is it just a start of mess? > > Python is a case-sensitive language. Variables named "none" and "None" are > different. It's unlikely that Python's case-sensitive properties will > change, so the SyntaxWarning will only be raised for "None". > > Skip That's why I feel that none, true and false must be literals and keywords (not variables). BTW this won't prevent True and False from staying in the language (till 3.0 :-) and behaving exactly as they do now: >>> True = False; False = not True >>> >>> False True >>> True False Only the output will be >>> False true >>> True false M-a-S From gh at ghaering.de Wed Sep 24 09:26:53 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 24 Sep 2003 15:26:53 +0200 Subject: newbie script In-Reply-To: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> Message-ID: <3F719B9D.5040703@ghaering.de> ataraxia2500 wrote: > I wanna do a script that launch a programm xyz and relaunch xyz if it > crashes. what kind of module do I need for such a task? Something like this: import os while 1: os.system("j:/UT2003/System/UT2003.exe") os.system executes a program and waits, until the program is terminated. But there's no way to know wether the program was terminated deliberately or wether it crashed. -- Gerhard From skip at pobox.com Thu Sep 4 08:54:39 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 4 Sep 2003 07:54:39 -0500 Subject: Quickie mail.python.org status In-Reply-To: References: <727daa7e.0309031140.1af820b2@posting.google.com> Message-ID: <16215.13839.220121.550541@montanaro.dyndns.org> Francois> I do not understand why the bad guys would have programmed Francois> such a deadline within their code, but I still wish this Francois> deadline story is true! The speculation I've read is that the author was paid (or is going to be paid) by spammers. The virus will propagate (and relay spam?) until the agreed upon deadline. Skip From skip at pobox.com Wed Sep 24 13:15:14 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Sep 2003 12:15:14 -0500 Subject: Python Glossary Message-ID: <16241.53538.40615.455582@montanaro.dyndns.org> Thanks to people who submitted content for the Python Glossary: http://manatee.mojam.com/python-glossary I just completed a first pass at folding it into the Python tutorial. It's now a separate appendix to that document. It will take awhile for the changes to show up on the website and in distributions, but if you have named CVS access to the Python distribution, you can get to it now. People with only anonymous CVS access or no CVS access at all will have to wait awhile for SourceForge to update the server. After a day or so it should be available here: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Doc/tut/ I would appreciate it if people could proofread it (if you're anxious to get to work, mail me and I'll send you a copy of the glossary.tex file). I made some changes to the definitions, but was focused more on getting the content into the tutorial than on wordsmithing. As a side-effect, the tutorial now also has an index. All but one or two of the entries it contains are from the glossary. The entire tutorial needs to be "indexified". If you would like to help with that, please feel free. In any case, any changes should be submitted as a documentation bug or patch (if you have some proposed context diffs) and assigned to me (SF username: montanaro). Please don't feel shy about adding new entries to the existing Wiki-based glossary either. I will notice updates and migrate new or corrected terms over as I have time. I don't plan to dismantle it, at least not for the forseeable future. At some point I may migrate it to the Python.org Wiki though. Skip From fortepianissimo at yahoo.com.tw Wed Sep 17 14:05:15 2003 From: fortepianissimo at yahoo.com.tw (fortepianissimo) Date: Wed, 17 Sep 2003 11:05:15 -0700 (PDT) Subject: fast way to filter a set? In-Reply-To: <16232.40145.813183.441676@montanaro.dyndns.org> Message-ID: <20030917180515.4765.qmail@web16913.mail.tpe.yahoo.com> Actually I like your idea most (out of other iterator approach) - now if we could do an in-place set filtering... (maybe have a different version of set.discard() which takes a lambda expression?) --- Skip Montanaro wrote: > > fortepianissimo> But this created two lists (keys and dummy)? > Compared > fortepianissimo> to the filter() method, which created a list and > a new > fortepianissimo> set, maybe your suggestion is still a bit > faster... > > You asked for alternatives. I offered one. I'll let you do the > performance > testing. ;-) > > Skip > > fortepianissimo> --- Skip Montanaro wrote: > >> > fortepianissimo> I know I can do things like > fortepianissimo> s=Set(range(1,11)) > fortepianissimo> s=Set(filter(lambda x:x%2==0,s)) > >> > fortepianissimo> But this seems a bit slow since filter returns a > >> list > fortepianissimo> which then must be converted back to a set. Any > >> tips? > >> > >> The only thing which comes to mind is: > >> > >> >>> s = sets.Set(range(1,11)) > >> >>> s > >> Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) > >> >>> keys = list(s) > >> >>> dummy = [s.discard(x) for x in keys if x%2] > >> >>> s > >> Set([2, 4, 6, 8, 10]) > >> > >> You still create a list, but don't create a second set. > >> > >> Skip > > > fortepianissimo> __________________________________ > fortepianissimo> Do you Yahoo!? > fortepianissimo> Yahoo! SiteBuilder - Free, easy-to-use web site > design software > fortepianissimo> http://sitebuilder.yahoo.com __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From NO-MAIL at hotmail.com Fri Sep 19 18:15:34 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Fri, 19 Sep 2003 22:15:34 GMT Subject: file position *tell()* works different References: <13a533e8.0309190137.2df0cc60@posting.google.com> Message-ID: "Richie Hindle" wrote in message news:mailman.1063967785.18911.python-list at python.org... > > M-a-S, are you sure you saved test_data.txt with Unix line endings? I > tested Peter's script under WinXP/Python2.3 as well, and it failed as > expected (though with slightly different results): > <......> > -- > Richie Hindle > richie at entrian.com > Oops! Stupid me! With '\n' it behaves really weird. Same values as yours. Filepointer: 0 Filepointer: 8 (-3 off the right value - M-a-S) Filepointer: 20 (-2) Filepointer: 31 (-1) Filepointer: 50 (-0) Filepointer: 0 Filepointer: 11 Filepointer: 22 Filepointer: 32 Filepointer: 50 For the file '0123456789\n'*12 it prints: Filepointer: 0 Filepointer: 0 (-11 off the right value) Filepointer: 12 (-10) Filepointer: 24 (-9) Filepointer: 36 (-8) Filepointer: 48 (-7) Filepointer: 60 (-6) Filepointer: 72 (-5) Filepointer: 84 (-4) Filepointer: 96 (-3) Filepointer: 108 (-2) Filepointer: 120 (-1) Filepointer: 132 (-0) Filepointer: 0 Filepointer: 11 Filepointer: 22 Filepointer: 33 Filepointer: 44 Filepointer: 55 Filepointer: 66 Filepointer: 77 Filepointer: 88 Filepointer: 99 Filepointer: 110 Filepointer: 121 Filepointer: 132 If I add another line, it breakes: Filepointer: 0 Traceback (most recent call last): File "C:\Home\Programming\Python\t\t.py", line 5, in ? print 'Filepointer:%4d' % fp.tell() IOError: (0, 'Error') M-a-S From cnetzer at sonic.net Tue Sep 2 07:20:38 2003 From: cnetzer at sonic.net (Chad Netzer) Date: Tue, 02 Sep 2003 04:20:38 -0700 Subject: Overloading objects In-Reply-To: <3f5469c4@news.comindico.com.au> References: <3f5469c4@news.comindico.com.au> Message-ID: <1062501638.1870.30.camel@adsl-209.204.179.133.sonic.net> On Tue, 2003-09-02 at 02:58, Tom Lee wrote: > Batista, Facundo wrote: > > I thought using defaults: > > > > def myMethod (self, name, age=None): > > self.name = name > > if age not None: > > self.age = age > > > > > > but I'm concerned about the scalability of this. In general, it isn't a problem. You really don't want methods with LOTS of arguments. If you need variable numbers of arguments, where the default value system doesn't help you, just use *args, and do things positionally by counting the length of the argument list. In Python, you can always use argument keywords when you call your method, so you don't need to remember the positions. Learn to rely on keyword arguments, and your life with Python will be happier. Also, you can use a dictionary to hold and pass your arguments around easily, and can have it automatically substitute the keyword values when you call the function (using **kwds). If you need LOTS of arguments, use a dictionary or class, and pass THAT to your method. > > What's the most pythonic way to do this? Using something like *args or > > **args? Yes. It is easy and powerful once you see some examples. [Tom Lee] > Scalability doesn't even come into this question - if you're really > worried about performance, don't use Python. I assume the original poster was concerned with the scaling of the number of arguments, and it becoming unmanagable to use and maintain. Not anything to do with speed (ie. a different kind of 'scaling') > Anyway, you have two or three choices: > > 1. Do it the way you're doing it. yep. > 2. Check parameter types at runtime using type() and the is keyword. e.g. > if type( somevar ) is int: > self.do_int_stuff( somevar ) > else: > self.do_other_stuff( somevar ) Rather than doing explicit type checks, it is somehat more robust to try to operate on the argument as if it were a valid type, and be prepared to handle exceptions. Only coerce to another to another type when you need to: try: self.do_int_stuff( int( some_int_like_var ) ) except TypeError: [handle the other cases or error] If you do want to have set types (as one often does), try to test based on behavior, since many objects can act similarly and interact together, without being the same type (and so type checking will always be overly restrictive and reduce the utility of your design) Anyway, it is a tangential, and somewhat more advanced topic than this thread was started to cover. > 3. Use similar names for similar methods. wxPython does this. e.g. yep. Although that's not my favorite design. Just makes it harder to learn things by introspection (requires more reference manual searching than using fewer methods with more option arguments, (IMO)) It's a tricky balance, sometimes. -- Chad Netzer From bokr at oz.net Sat Sep 20 18:04:53 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2003 22:04:53 GMT Subject: 2nd iteration of a character References: Message-ID: On Sat, 20 Sep 2003 23:27:23 +0200, Philippe Rousselot wrote: >Hi, > >How do I find the second iteration of a character in a string using python > >this gives me the first one >f1 = string.find(line,sub) > >this the last one >f2 = string.rfind(line,sub) > >but for the nth one ? > >Thanks in advance > >Philippe > >PS : any good book to recommend ? Online tutorials first ;-) >>> s='01x34x678x012345x789x' >>> def find_nth(s, ss, n): ... i = -len(ss) ... for j in xrange(n): ... i += len(ss) ... i = s.find(ss,i) ... if i<0: return i ... return i<0 and -1 or i ... >>> find_nth(s,'x', 1) 2 >>> find_nth(s,'x', 2) 5 >>> find_nth(s,'x', 3) 9 >>> [find_nth(s,'x', i) for i in xrange(5)] [-1, 2, 5, 9, 16] >>> [find_nth(s,'x7', i) for i in xrange(5)] [-1, 16, -1, -1, -1] >>> [find_nth(s,'01', i) for i in xrange(5)] [-1, 0, 10, -1, -1] >>> [find_nth(s,'34', i) for i in xrange(5)] [-1, 3, 13, -1, -1] >>> [find_nth(s,'xx', i) for i in xrange(5)] [-1, -1, -1, -1, -1] BTW, the above is not the fastest possible code, just a quick first prototype, and not tested beyond what you see above ;-) Regards, Bengt Richter From tim.parkin at pollenationinternet.com Mon Sep 8 04:13:45 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Mon, 8 Sep 2003 09:13:45 +0100 Subject: Comments on Python Redesign In-Reply-To: Message-ID: <005301c375e1$25da9800$0a00a8c0@JASPER> Bengt Wrote >It looks slick, but not really technically slick in a way >that would lead me to expectations about Python, just >eye-candy/we-spend-more-on-advertising-than-research >kind of slick (though for largely irrelevant photos, I >prefer pretty things and/or great photography ;-) What has amazed me throughout the pulling of a discussion Onto the Python list is the amount of furor that has been generated by the use of three photographs. The marketing content of the website takes only 7% of the space of the main page. The remaining is textual navigation content. If we're in a position where people hate photography then I think we have to accept that this is an irrational problem and that it shouldn't affect the promotion of Python in the computer industry. For those still commenting on the contrast issue, please understand that there are accessibility guidelines that suggest a use of 70% contrast in order to maximise readability for all users. These are my last comments on the comp.lang.python mailing list. If anyone wants to continue the disucssion and really help to create/promote Python, please move to either http://pythonology.org/mailman/listinfo/marketing-python or http://pythonology.org/mailman/listinfo/py-design-forum The second list if it's website or design related. Tim From alpot at mylinuxsite.com Sun Sep 7 23:02:58 2003 From: alpot at mylinuxsite.com (hostmaster) Date: 08 Sep 2003 11:02:58 +0800 Subject: Question on Standard Types In-Reply-To: References: Message-ID: <1062990178.13887.36.camel@mylinuxsite.com> > Actually, this bit *is* definitely out of date; Python 2.2 introduced > new-style classes, and all the standard types are now new-style classes. Well, I guess I have to find a new book then. Thanks everyone. Al From aahz at pythoncraft.com Sun Sep 7 15:52:15 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2003 15:52:15 -0400 Subject: Python memory management References: Message-ID: In article , Marcelo A. Camelo wrote: > >I've noticed that, from all their concerns, the most difficult to tackle >(for me, at least) is memory management. > >Currently, the most popular platform for game applications are videogame >consoles. Memory on these special purpose machines are a premium >resource and one should used it judiciously. Python's RTE footprint and >memory fragmentation issues make it a hard sell for game programmers >(many tend to prefer LUA). As Michael Hudson said, those are real issues. Nevertheless, the increasing power of game consoles renders the first issue less important, and PyMalloc (standard in Python 2.3) does much to alleviate the second issue. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From max at alcyone.com Tue Sep 9 16:55:26 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Sep 2003 13:55:26 -0700 Subject: How to instatiate a class of which the name is only known at runtime? References: Message-ID: <3F5E3E3E.9C31763F@alcyone.com> John Roth wrote: > As Nick said, you can use the exec statement. You can > also use the _import() function. >>> _import Traceback (most recent call last): File "", line 1, in ? NameError: name '_import' is not defined Do you mean __import__? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ But when I reached the finished line / Young black male \__/ Ice Cube From bram at nospam.sara.nl Tue Sep 23 04:59:03 2003 From: bram at nospam.sara.nl (Bram Stolk) Date: Tue, 23 Sep 2003 10:59:03 +0200 Subject: import pickle succeeds only after two tries?? Message-ID: <1064307542.783575@blaat.sara.nl> Hello, I am using python-2.2.2 on linux-ARM. Python itself works OK. However, importing pickle gives me *very* strange results: The first 'import pickle' fails with "ImportError: No module named StringIO" If I immediately do a second 'import pickle', it works???? See this log: Python 2.2.2 (#1, Mar 26 2003, 03:05:45) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pickle Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/pickle.py", line 971, in ? from StringIO import StringIO ImportError: No module named StringIO >>> import pickle >>> dir(pickle) ['APPEND', 'APPENDS', 'BINFLOAT', 'BINGET', 'BININT', 'BININT1', 'BININT2', 'BINPERSID', 'BINPUT', 'BINSTRING', 'BINUNICODE', 'BUILD', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DICT', 'DUP', 'DictProxyType', 'DictType', 'DictionaryType', 'EMPTY_DICT', 'EMPTY_LIST', 'EMPTY_TUPLE', 'EllipsisType', 'FLOAT', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GET', 'GLOBAL', 'GeneratorType', 'INST', 'INT', 'InstanceType', 'IntType', 'LIST', 'LONG', 'LONG_BINGET', 'LONG_BINPUT', 'LambdaType', 'ListType', 'LongType', 'MARK', 'MethodType', 'ModuleType', 'NONE', 'NoneType', 'OBJ', 'ObjectType', 'PERSID', 'POP', 'POP_MARK', 'PUT', 'PickleError', 'Pickler', 'PicklingError', 'PyStringMap', 'REDUCE', 'SETITEM', 'SETITEMS', 'SHORT_BINSTRING', 'STOP', 'STRING', 'SliceType', 'StringType', 'StringTypes', 'TUPLE', 'TracebackType', 'TupleType', 'TypeType', 'UNICODE', 'UnboundMethodType', 'UnicodeType', 'Unpickler', 'UnpicklingError', 'XRangeType', '_EmptyClass', '_Stop', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__version__', '_keep_alive', 'classmap', 'compatible_formats', 'dispatch_table', 'format_version', 'marshal', 'mdumps', 'mloads', 're', 'safe_constructors', 'struct', 'sys', 'whichmodule', 'x'] I find this extremely strange. What could be going on here? Thanks in advance, Bram Stolk From alan.gauld at btinternet.com Fri Sep 12 03:20:53 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Sep 2003 07:20:53 GMT Subject: safari (was Re: Writing solid code book) References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> Message-ID: <3f617389.593042620@news.blueyonder.co.uk> On Thu, 11 Sep 2003 19:14:05 -0600, Jules Dubois wrote: > However, seeing for the first time Python's syntax in _Nutshell_ was enough > to scare me away. Really? Can I ask why? I'd have thought seing Pythons syntax would be a breath of frsh air to most programmers, it certainly was for me. Why did you think it was scary? Curious, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From jobs at grapevinepartners.com Thu Sep 4 19:28:52 2003 From: jobs at grapevinepartners.com (Frank Steele) Date: Thu, 04 Sep 2003 23:28:52 GMT Subject: 2nd Post: Atlanta Python jobs Message-ID: The Transit Grapevine Atlanta, Georgia (Buckhead/Midtown) Job Description: Python developers - We're seeking Python developers to help us build and manage a network of electronic signs scheduled to be deployed in U.S. transit stations. Contract work, on a project-by-project basis. Job Requirements: - Ideal candidate will have experience interfacing Python with databases and/or with networked devices. - Must be comfortable working solo, or on a small team with minimal supervision. - Strong preference for metro Atlanta residents, because of the need to develop against specialized hardware. Contract position on a project basis. We will consider proposals from software development groups. We will begin interviewing as we receive resumes. Contact: Frank Steele E-mail contact: jobs at grapevinepartners.com Please send resume, link(s) to previous project(s), hourly salary requirements. From max at alcyone.com Sun Sep 7 18:09:57 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 07 Sep 2003 15:09:57 -0700 Subject: Comments on Python Redesign References: <3F5B8C51.6462BC38@alcyone.com> Message-ID: <3F5BACB5.E4F4734F@alcyone.com> Aahz wrote: > The current website has a number of navigation, structural, and > content > flaws resulting from the fact that it has grown organically for > roughly > a decade. It is also harder to maintain than we'd prefer. Finally, > it > looks a bit dated. That sounds like what's warranted is a reorganization, not necessarily a redesign. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I'm not worried about anything. I'm not fearing any man. \__/ Dr. Martin Luther King, Jr. (the evening before his assassination) From tayss_temp at yahoo.com Mon Sep 8 02:38:19 2003 From: tayss_temp at yahoo.com (Tayss) Date: 7 Sep 2003 23:38:19 -0700 Subject: Comments on Python Redesign References: Message-ID: <5627c6fa.0309072238.4f5bc965@posting.google.com> "Tim Parkin" wrote in message news:... > Please don't consider this, the majority of corporate users will find > the site themselves or through links in articles magazines, etc. so > they will still get first impressions from the main home page. If > anything we could provide a developer portal page which may be used > as a bookmark. [...] What is > wrong with the information architecture / navigation on the page > proposal. The new version is well-executed. Different elements contrast; most people like seeing faces (especially when they're flush with success)... But as a DEVELOPER, it doesn't work for me. I hate seeing happy-looking guys when I get out of bed with someone to bang out some code that struck me. Announcements are trapped in their safe boxes, which dominate their content. What I want as a developer is in conflict with what I'd want as a businessperson. A suit wants good /relevant/ info, that tells her Python isn't snake oil, that it's a good investment that also conforms to standards. Maybe a directory of consultants and supporting software to purchase. Every so often something new, like someone sharing Powerpoint slides that made his audience feel educated. If the sites aren't separated, the danger is noise. The best sites focus. Like apple.com and Google. Apple is pleasant to visit because there are a few sharp things to announce. If you can please two audiences with one page, you're very skilled. - Tayssir John Gabbour From newsgroups at jhrothjr.com Fri Sep 5 20:15:00 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 20:15:00 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <3f59014d$0$152$a1866201@newsreader.visi.com> <3f591d28$0$175$a1866201@newsreader.visi.com> Message-ID: "Grant Edwards" wrote in message news:3f591d28$0$175$a1866201 at newsreader.visi.com... > In article , John Roth wrote: > > >> So that there's no difference between a function and a method. > >> > >> Simplicity and orthogonality are good things -- despite what > >> C++ proponents thing. > >> > >> > Hence my comment that requiring it is more complex than not > >> > requiring it. > >> > >> No, it's more complex the Java/Ruby way, since you have to have > >> two sets of rules for what a name means depending on whether > >> you're inside a "normal" function or a method. In Python > >> there's just one set of rules -- mostly. > > > > As I said earlier, it's quite possible to define it so that there > > is always an instance of some kind; whether that's an instance > > a class or the module itself. > > I don't follow. You're talking about defining a keyword that > always refers to the first parameter passed to a function? And > the declared parameters would refer to the 2nd through Nth > parameters? What if the keyword isn't used in the function > definition, then do the delcared parameters refer to the 1st > through Nth? When Python invokes a function, it binds the operands in the function call to the identifiers named in the function / method header. If this is a method, it binds the instance (which is not in the invocation parameter list, btw.) to the first parameter in the method header. If you make "self" a reserved word, then all it has to do is bind the instance to "self," rather than the first identifier in the parameter list. In current python, there are two classes of functions (module level and embedded) and three classes of methods (instance, class and static.) Instance methods get the current instance, class methods get the class object as the instance, and the other three categories get nothing. As a separate suggestion, I'd have Python bind the module object to "self" for module functions and static methods. I haven't figured out what I want done with embedded methods and unbound methods yet. Notice that this eliminates the need for the global statement for module functions - all identifiers are accessible for rebinding through "self." > > I think my comments have shown that you can reduce the amount > > of scoping / name space rules noticably. > > Compared to what? It sure sounds like you're introducing more > rules than there are now. How would you propose reducing the > number of rules? If you don't have to write "self" as the first parameter of a method, that reduces the complexity. Everything else remains the same. John Roth > > -- > Grant Edwards grante Yow! Somewhere in Tenafly, > at New Jersey, a chiropractor > visi.com is viewing "Leave it to > Beaver"! From anton at vredegoor.doge.nl Sat Sep 20 15:58:00 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 20 Sep 2003 21:58:00 +0200 Subject: Problems with string and lists (searching and replaceing) References: Message-ID: "jblazi" wrote: >> from UserString import MutableString >> >> def test(): >> s = MutableString("helo world") >> print s >> x = 'helo' >> y = 'hello' >> i = s.find(x) >> s[i:i+len(x)] = y >> print s >> >> if __name__=='__main__': >> test() >> >> #output: >> #helo world >> #hello world > >Thx. >It would be quite diffcult to explain this akward procedure to beginners. >especially when they see that this can be done so simply in C. >It seems that I have stumbled upon one of the few cases when Python is >cumbersome and difficult to use. Interesting. Could you provide an example showing in which way it can be done so simply in C ? Maybe I could come up with better Python code if I knew what the problem is with my code. Anyway, it was just something I typed in without thinking much about it, to show that strings can be mutated. In Python everything is an object so if some functionality is needed it is pretty standard to use a subclass. In this case a fitting subclass already was present in the standard distribution so it seemed like a piece of cake. With respect to beginners I suppose it's possible to project ones own sense of what is easy, instead of really checking what would be easy for *them*. Beginners are not supposed to know about C, but possibly you are, and maybe you are thinking too much from your own perspective in judging what would be easy. Anton From peter at engcorp.com Tue Sep 9 18:31:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 09 Sep 2003 18:31:59 -0400 Subject: virtual inner classes in python? References: Message-ID: <3F5E54DF.8ED73922@engcorp.com> kasper graversen wrote: > > I've just started learning python. I see methods are declared virtual by > default as in Java. Nice. However, the inner class construct seems to be > even weaker as that of Java. Not nice! :-( Why are inner classes not > virtual? will they be in a near future? What other language can you > recomend, if python cannot provide what I need? > > My problem is that in the __init__ below, I cannot instantiate "Foo" but > have to explicate "Test.foo".. secondly, I want to instantiate the "Foo" in > test2 rather than in tester in the current example.. > > class Test: > def __init__(self): > lala = Test.Foo() > lala.show() > class Foo: > def show(self): > print "Test.foo.show" With the tabs that you used, the above formatting is what some of us saw. It seems you meant for "class Foo" to appear at the same level of indentation as the "def __init__", right? As for "declared virtual by default", I don't think this is quite correct for Python. All methods are always virtual in Python, unless one goes to extremes to simulate some other effect, I think. Anyway, I believe the problem you are experiencing stems from a lack of understanding of how Python finds things in its "namespaces". This is a key concept to issues such as the one you are investigating, and you won't get far if you assume Python is anything like Java or other static languages in this respect. First, you need to specify Test.Foo because otherwise you are asking for a Foo that is found in the global (module) namespace. You could also use "self.Foo" in this case, though it might be considered slightly less clear, but I have a feeling it would do roughly what you want, whatever that is. (You didn't really make it clear what you want, as near as I can tell.) -Peter From peter at engcorp.com Mon Sep 22 14:23:52 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Sep 2003 14:23:52 -0400 Subject: Slicing vs .startswith References: Message-ID: <3F6F3E38.5221D7E7@engcorp.com> Shu-Hsien Sheu wrote: > > I have a question about the comparison of efficiency of string slicing > and using string.startswith. > For example, which one of the following would be more efficient, or , > moreover, more pythonic? > > if aa[:3] == 'abc': > > vs > > if aa.startswith('abc'): The latter is clearly more readable. From peter at engcorp.com Sun Sep 21 21:23:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 21 Sep 2003 21:23:56 -0400 Subject: Exceptions in threads? References: Message-ID: <3F6E4F2C.592EFB77@engcorp.com> Roy Smith wrote: > > What is supposed to happen when an exception is raised and not caught in > a thread? The Reference Manual (section 4.2) states "When an exception > is not handled at all, the interpreter terminates execution of the > program, or returns to its interactive main loop", but it looks like > what really happens is the thread is terminated, not the whole program. The behaviour you observed is generally what seems to happen, though I'm not sure it's even remotely guaranteed what the behaviour will be across platforms. If you want your threads' termination to kill the whole program, I think you would need to do two things. One is wrap each thread with a generic exception handler which catches all exceptions that aren't otherwise caught and sends a signal to the main thread, which would be set up to wait for such a signal and terminate when it got one. The second would be to make all threads daemon threads, so that when the main thread tries to terminate it doesn't wait for the other threads to finish as it does by default. None of this will, of course, help you if you have a thread blocked in, say, a socket connection attempt or something like that. -Peter From jblazi at hotmail.com Sat Sep 20 15:08:40 2003 From: jblazi at hotmail.com (jblazi) Date: Sat, 20 Sep 2003 21:08:40 +0200 Subject: Problems with string and lists (searching and replaceing) References: Message-ID: "Anton Vredegoor" schrieb im Newsbeitrag news:bkhnpn$hgc$1 at news.hccnet.nl... > >Do I oversee something? > > Yes, UserString. The documentation is a bit sparse, but reading the > module itself provides additional information. Below is a quick test > script. > > from UserString import MutableString > > def test(): > s = MutableString("helo world") > print s > x = 'helo' > y = 'hello' > i = s.find(x) > s[i:i+len(x)] = y > print s > > if __name__=='__main__': > test() > > #output: > #helo world > #hello world Thx. It would be quite diffcult to explain this akward procedure to beginners. especially when they see that this can be done so simply in C. It seems that I have stumbled upon one of the few cases when Python is cumbersome and difficult to use. JB From fredrik at pythonware.com Fri Sep 26 17:33:26 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 Sep 2003 23:33:26 +0200 Subject: squeeze and package imports References: Message-ID: Mathias Waack wrote: > it works without squeezing and fails with squeezing. In the latter > case, the Buffer import statement named above fails. The traceback > shows, which import in which file is executed, but instead of the > directory names of each file it prints only question marks "?". Thus > I thought, if the import code doesn't know about the current > directory, it can't import the Buffer module, because it can't look > into the "same" directory. And so my second try: > > sys.path.append("/tmp") > sys.path.append("/tmp/DCOracle") > import DCOracle > > And everything works fine. But I'm still curious - there seems to be > something wrong with the import hooks in the squeeze module. BTW, > I'm using python 2.2.2. Python didn't have packages back in the early days when squeeze was written (Python 1.3 or so); afaik, nobody's ever gotten around to add true package support to the tool. for a modern replacement, see: http://www.mcmillan-inc.com/install1.html From __peter__ at web.de Mon Sep 15 12:10:00 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 Sep 2003 18:10:00 +0200 Subject: Multiple instances of modules References: Message-ID: Daniel Pryde wrote: > Hi there. > > I'm currently trying to learn Python, my aim being to create my final > year project at university using only Python instead of Java. I've run > into a problem though while trying to make multiple instances of > modules. > > For example, say I made a CD.py module which held details of an audio > compact dic (album name, track names, etc..), and wanted my Python > script to make a record collection using multiple CD's, I can't make > them seperately. I tried using the 'import module as name' format, but > any changes made to one instance affects the other. I assume this is > because Python is simply referencing the one instance of CD.py rather > than seperate ones. Is there a solution to this that doesn't involve > using cPython or Jython? Any help would be greatly appreciated. There is no connection between a class name and a module name enforced by the language. If you already know a programming language, I strongly recommend the tutorial that comes with the python distribution. Below is a minimalist CD class with an example usage to get you started. (In Python you say CD() instead of Java's new CD()) #module cd.py class CD: def __init__(self, composer, title): self.composer = composer self.title = title def __str__(self): return "%s: %s" % (self.composer, self.title) #end module cd.py #module main.py from cd import CD cdcoll = [] cdcoll.append(CD("Orff", "Carmina Burana")) cdcoll.append(CD("Bach", "Goldberg-Variationen")) for disk in cdcoll: print disk #end module main.py Peter From tim at remove_if_not_spam.digitig.co.uk Tue Sep 30 16:21:26 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Tue, 30 Sep 2003 21:21:26 +0100 Subject: where are the "class variables"? References: <62e9c66e.0309301057.65f24a3b@posting.google.com> Message-ID: <5apjnvspn7220pifp5b61cn762ml2joo6e@4ax.com> On 30 Sep 2003 11:57:17 -0700, dokaspar at student.ethz.ch (Dominik Kaspar) wrote: >i'm used to java and its strict way of defining variables. so how is >it possible to reach something like a class variable in python? >with the following code i didn't have much succes... > >class Server(threading.Thread): > running = 0 (??) > > def run(self): > running = 1 > while running: > print "do something here..." > > def exit(self): > running = 0 > >thanks >-- dominik Try: class Server(threading.Thread): running = 0 def run(self): Server.running = 1 while Server.running: print "Hello!" self.exit() def exit(self): Server.running = 0 If you want class /functions/, though, you need a recent version of Python. From jacek.generowicz at cern.ch Wed Sep 17 04:19:34 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Sep 2003 10:19:34 +0200 Subject: Anyone ever overridden a builtin by accident? References: Message-ID: ladasky at my-deja.com (John Ladasky) writes: > In one of my programs I wrote... > > c = max(a,b) > Then, I finally spotted the problem. At the beginning of my program I > had defined a variable called "max"! I had overridden the __builtin__ > function by mistake. voblia at centras.lt (Ignas Mikalajunas) writes: > Common Lisp solves this problem in a pretty simple way - functions > and variables are in separate namespaces But it doesn't really _solve_ the problem, does it? It solves the problem of overriding function bindings with data bindings (and vice versa), but does nothing to prevent overriding function bindings with other function bindings. Consider: def list(): print "list" and the Common Lisp equivalent (defun list () (print "list")) In both cases you're clobbering a built-in. The difference, however, is that, in Python you've merely shadowed the built-in -- the original is still there in Python's outermost scope (builtins), while in CL you are attempting to replace the built-in[*]. Common Lisp "solves" it, by forbidding it. But I do not think that implementations are required to enforce the rule, so some (eg clisp) complain: [1]> (defun list () (print "list")) ** - Continuable Error DEFUN/DEFMACRO(LIST): # is locked If you continue (by typing 'continue'): Ignore the lock and proceed 1. Break [2]> while others (eg CMUCL), let it pass silently: Loaded subsystems: Python 1.1, target Intel x86 CLOS 18e (based on PCL September 16 92 PCL (f)) * (defun list () (print "list")) LIST (Python, BTW, is the name of CMUCL's compiler :-) > all global variables are commonly named *booo* *bah* and etc. so if > you are overriding a global variable you are at least aware of it ... Although the real purpose of the asterisks is to warn you about the fact that the variable is dynamically bound[+], and that any local bindings that you may make for it, will also be dynamic. The asterisks are another form of namespace separation, but they address an orthogonal issue, and offer absolutely no protection against clobbering global _function_ definitions; global function names have no asterisks (because they are not dynamically bound[#]). [*] To be fair, Lisp distinguishes global function definitions from local ones, while in Python they are always local, so one can argue that the CL equivalent of Python's def is really flet or labels, which leave the built-in functions well alone, just as is the case in Python. [+] As opposed to lexically bound, which is the default in CL, and the only possibility in Python. [#] Though it has been suggested recently, that dynamic function binding subsumes AOP ... but that's getting waaaaay off-topic. From paul.moore at atosorigin.com Tue Sep 2 05:49:12 2003 From: paul.moore at atosorigin.com (Paul Moore) Date: 2 Sep 2003 02:49:12 -0700 Subject: Structured writing to console, such as a table References: Message-ID: <182bcf76.0309020149.638995bd@posting.google.com> Bob Gailer wrote in message news:... > In addition to other responses, consider this which uses nested % > formatting to make format strings for reuse: I like this one! Very simple, and the resulting code is easy to understand. Most of my code's complexity revolved around getting the column widths, which you don't address - this is good, as it makes the separation of issues clearer. One other issue which sometimes bites me, when I need to print database tables, is whether to truncate values which are too long for their field widths. It's another issue the OP didn't specify a preference over. No criticism there, it's just an illustration that for problems like this, knowing what you want is often the bigger issue than writing code to do it... (A friend of mine used to love quoting the example of functions to "ask for a yes/no response", where it's nearly always easier to write your own version than to work around the ways in which a canned version doesn't *quite* meet your needs...) In Python, reinventing wheels is often easy enough that it's not worth the design effort of making things like this into truly reusable library code. I can't work out if that's an advantage of Python :-) Paul. From martin at v.loewis.de Sat Sep 27 06:23:35 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 27 Sep 2003 12:23:35 +0200 Subject: unicode 3 digit decimal conversion References: Message-ID: Rune Hansen writes: > What I need is the converted string to read u'Gratis \248l' (* > How do I do this without going through each and every character of the > string? You can register an error callback, like this: import codecs def decimal_escape(exc): try: data = exc.object res = u"" for i in range(exc.start, exc.end): char = ord(data[i]) if char < 1000: res += u"\\%03d" % char else: # Unsupported character raise exc return res, exc.end except: raise exc codecs.register_error("decimal-escape", decimal_escape) print u"Gratis \xf8l".encode("us-ascii", "decimal-escape") Notice That your specification is a bit unclear as to what to do with characters > 1000; I assume they are not supported in your protocol. Regards, Martin From __peter__ at web.de Fri Sep 5 04:07:19 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Sep 2003 10:07:19 +0200 Subject: Comparing objects - is there a maximum object? References: <7bdbb1a6.0309041124.6801b755@posting.google.com> Message-ID: Chris Brew wrote: > Thing is, what happens at end of file? I'd like to > do it by making the streams that are finished > return some object (call it endmarker) such > that min(x,endmarker) always returns x. That way, > when all the streams are returning endmarker, we > would be done. And I'd like my code to work the same > no matter what kind of thing the streams are > returning, so I want endmarker to be a generic > maximum object. > Why not remove "streams" that have reached the end? You could do something like def gen(*seqs): seqs = [iter(seq) for seq in seqs] done = [] while True: result = [] for it in seqs: try: result.append(it.next()) except StopIteration: done.append(it) if len(done): for d in done: seqs.remove(d) done = [] if len(result) == 0: break yield result # produce sample data import random l1 = range(5) l2 = range(10) l3 = range(3, 6) for l in l1, l2, l3: random.shuffle(l) # demonstration for i, x in enumerate(gen(l1, l2, l3)): print i, x, "-->", min(x) There may be room for improvement in the gen() function, but the general idea is not to compare objects made up only for that purpose and when you already know the outcome. Peter From sholden at holdenweb.com Thu Sep 11 09:00:01 2003 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 11 Sep 2003 13:00:01 GMT Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> Message-ID: "Stephen Horne", using a ridiculous bogus email address, wrote... > On Wed, 10 Sep 2003 16:55:28 +0200, Peter Otten <__peter__ at web.de> > wrote: > > >Obviously, your example could easily be rewritten to > > > >def inc(p): > > return p + 1 > > > >x = inc(x) > > > >and a similar function with two by-ref parameters would still be readable: > > > >x, y = inc2(x, y) > > > >So here's my question. How many functions are there in your *real* code that > >could benefit from, say three or more by-ref parameters? > >Hint: for me it comes close to 0 :-) > > Its not an issue of whether the same effect can be achieved in Python. > It's more an issue of whether the method used expresses the > programmers intentions properly. > > If a function is defined as... > > def Inc (p) : > return p + 1 > > then that to me expresses an intention which is different to that > expressed by... > > def Inc (ref p) : > p += 1 > > The latter case expresses the intention to in-place rebinding of the > parameter. In doing so, it better expresses the purpose of some kinds > of functions (though not this noddy example, obviously). > > This is all very fuzzy, so let's examine an example which is based on > an issue in some real Python code (though this is simplified to make > the point). The problem is to insert an object into some container - > appending to a list will do here. However, the object being inserted > will typically be quite large, so we want to avoid copying it if > possible. > > No problem there, it seems... > > class c_Container : > f_List = [] > > def Add (self, p_Object) : > f_List.append (p_Object) > > The problem with this, however, is the risk of accidental > side-effects. If the caller goes on to modify the object that he > passed as a parameter, that will change the content of the container. > I don't see why this is any different, or worse, than having a function modify a single reference. You are setting your calling code up to fail due to the invisible side-effects of the function call. This is a Bad Idea. [...] > >By the way, this is strictly from a user perspective, I trust the Python > >developers to overcome the implementation issuses, *if* there is a > >significant usability improvement. > > And that is the big question. > > C# 'needs' ref parameters because it has no convenient way to return > multiple values from a function. Python does not. The question is > really whether this argument about expressing intentions and evading > errors is compelling or not. > You have still to convince me that there would be any gain whatsoever. Think of me as the forces of reaction ;-) regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Sep 11 07:27:46 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 11 Sep 2003 12:27:46 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <3F5F83B1.48763F85@alcyone.com> <3F5FD6D7.119F04A1@alcyone.com> Message-ID: On Thu, 11 Sep 2003 08:06:22 +0000 (UTC), Thomas Bellman wrote: >No, you *would* know. The above call would *not* be able to >rebind any of thisArgument or thatArgument. Thanks for the support. >(For the record, I do not support Stephen's proposal, nor any >other kinds of call-by-reference in Python. For one, I don't >think it meshes well with the rest of Python, and moreover, I >have yet to encounter a real-world example where this would >actually make code more readable - and I have been using Python >for eight years now, and Lisp (which has similar call semantics) >for a few years before that.) Yes, I do agree with this now - it was a poorly thought out idea which reveals nothing so much as the fact that I've got too comfortable with some other languages ways of working. From BjornPettersen at fairisaac.com Tue Sep 30 04:47:45 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Tue, 30 Sep 2003 03:47:45 -0500 Subject: Question: Inheritance from a buil-in type Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907B59D0F@stpmsg00.corp.fairisaac.com> > From: Asun Friere [mailto:afriere at yahoo.co.uk] > > Duncan Booth wrote in message > news:... > > > > > There are two rules. Generally, immutable objects get their > > initial values from the constructor (__new__) while mutable > > objects are constructed with a default value (e.g. empty > > list or dict) and are then set by the initialiser > > (__init__) method. A few types which you might expect to be > > immutable are actually mutable (e.g. property). > > > > What is the thinking behind that? I mean you /can/ pass initial values > to a mutable using __new__, eg > > class MyList (list) : > def __new__(cls, *args, **kwargs) : > return list.__new__(cls, *args, **kwargs) > > or __init__ to pass values to a newly created immutable, eg > > class MyTuple (tuple) : > def __init__(self, *args, **kwargs) : > return super(tuple, self).__init__(*args, **kwargs) > > can't you? What's the pitfall? Shart answer: you should call super as "super(MyTuple, self)". Long answer: http://www.python.org/2.2/descrintro.html#cooperation. -- bjorn From sross at connectmail.carleton.ca Tue Sep 16 11:21:54 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 16 Sep 2003 11:21:54 -0400 Subject: object.attribute vs. object.getAttribute() References: Message-ID: Hi. "Roy Smith" wrote in message news:roy-81B3E5.20291015092003 at reader2.panix.com... [snip] > 1) More typing (which implies more reading, which I think reduces the > readability of the finished product). > 2) Need to write (and test) all those silly little functions. If you only intend to create simple properties[*], then the following recipe may address issues 1) and 2) (except for the testing part): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157768 If you're going to create more complex properties, you may find this recipe(idiom) of interest: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183 Hope that's useful, Sean [*] By "simple properties", I mean something like the following: ''' assume we're inside a class definition and self.__foo has been initialized. ''' def get_foo(self): return self.__foo def set_foo(self, value): self.__foo = value def del_foo(self): del self.__foo foo = property(fget=get_foo, fset=set_foo, fdel=del_foo, doc="foo") From zanesdad at bellsouth.net Tue Sep 9 10:27:41 2003 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 9 Sep 2003 10:27:41 -0400 Subject: Codesample for xml/xslt transforming In-Reply-To: ; from axel@pizza.home.kosnet.com on Tue, Sep 09, 2003 at 02:45:54PM +0200 References: Message-ID: <20030909102741.A24609@cerberus.liberty> * Axel Straschil (axel at pizza.home.kosnet.com) wrote: > I've test.xml, test.xsl or two vars with the code > and wan't to transform it. > Google just helped me for C ... This code used to work (kinda ugly, though - sorry): from Ft.Xml.Xslt.Processor import Processor import Ft.Xml.InputSource ##I was working with a DOM object here xml_data = dom.toxml() processor = Processor() f = open("rmkr.xsl",'r') xsl_data = f.read() f.close() processor.appendStylesheet(Ft.Xml.InputSource.DefaultFactory.fromString(xsl_data, "uri")) result = processor.run(Ft.Xml.InputSource.DefaultFactory.fromString(str(xml_data), "uri")) processor.reset() result_html = os.path.join(result_dir, "%s.html" % outfile_prefix) htmlfile = open(result_html, "w") htmlfile.write(result) htmlfile.close() I haven't tested it recently to see if it still works. It worked with FT under Python 2.1. Jeremy Jones From gafStopSpamData at ziplink.stopallspam.net Mon Sep 8 15:54:29 2003 From: gafStopSpamData at ziplink.stopallspam.net (Gary Feldman) Date: Mon, 08 Sep 2003 19:54:29 GMT Subject: IDLE doesn't rerun PYTHONSTARTUP on restart Message-ID: I do some setup with a .pythonrc file executed via the PYTHONSTARTUP environment variable (on MS Windows). This works fine when I first start IDLE (contrary to some notes in the archives that indicate I need to use IDLESTARTUP instead). However, when I restart the shell, it isn't run. Are there any workarounds for this? Thanks, Gary From alan.gauld at btinternet.com Wed Sep 3 18:11:09 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Sep 2003 22:11:09 GMT Subject: Code complete electronic version ? References: Message-ID: <3f566672.342116427@news.blueyonder.co.uk> On Wed, 03 Sep 2003 09:03:57 -0500, "A.M. Kuchling" wrote: > On Wed, 03 Sep 2003 13:40:48 +0100, > > If it's too much, buy it second-hand. It's a good book, and although > > plenty of it is just common sense, it's the type of common sense that's > > easy to miss :) > > Isn't it mostly concerned with C, though? Not really, he gives examples in BASIC, ADA, Pascal and Fortran as well as C./C++ The latter pair dominate as a reflection on where the industry was in 1992. But the basic tenets apply regardless of language - code layout, variable naming, control structures etc. Code Complete is essential reading for any prpfessional programmer IMHO, but it may not be essential for non pros... Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From nid_oizo at yahoo.com_remove_the_ Fri Sep 26 13:30:20 2003 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 26 Sep 2003 13:30:20 -0400 Subject: Reduce need of backslash In-Reply-To: References: Message-ID: Peter Otten wrote: > Nicolas Fleury wrote: > > >>I was wondering if the need for \ could be reduce in the language. For >>example, could a line ending with = or + could be automaticly considered >>incomplete? > > > Did you know about (...)? Actually, no. But it's still not what I'm looking for. It's just that I'm used to languages where I can put my code on multiple easily to make lines shorter. As John pointed, it's possible to add () to print. I just discovered that it can be done with return also. I wonder how to remove the need for \ in that example: parser.StartElementHandler = \ lambda name, attrs: \ GenericParser.handleElementStart(self, name, attrs) Regards, Nicolas From aahz at pythoncraft.com Sun Sep 7 00:22:16 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2003 00:22:16 -0400 Subject: Redesign of Python site References: Message-ID: In article , rt lange wrote: > >came across this page searching feedster. >dont know whether this is the official resdesign or just a proposal; >but the mockups look very nice. Currently just a proposal. If you care about this subject, subscribe to the mailing list at http://mail.python.org/mailman/listinfo/pydotorg-redesign -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From lizard0000092 at yahoo.com Wed Sep 17 11:07:30 2003 From: lizard0000092 at yahoo.com (Gabby) Date: 17 Sep 2003 08:07:30 -0700 Subject: Python 2.1 Compilation error - can't find krb5.h Message-ID: <83bb8ac6.0309170707.6ab0e8ae@posting.google.com> I am attempting to compile python 2.1 from the source on a RedHat 9.0 system. The problem is that a openssl header file (kssl.h) requires krb5.h which isn't in the usual place (/usr/include). Instead krb5.h gets installed at usr/kerberos/include. The openssl version is 0.9.7a-2. When I build python, the ./configure works fine but the make' has problems building the _socket extension. The beginning of the error message is pasted below. How do I let python know where to find the krb5.h file? In file included from /usr/include/openssl/ssl.h:179, from /home/merlin/Python-2.1.2/Modules/socketmodule.c:196: /usr/include/openssl/kssl.h:72:18: krb5.h: No such file or directory In file included from /usr/include/openssl/ssl.h:179, from /home/merlin/Python-2.1.2/Modules/socketmodule.c:196: From aleax at aleax.it Sat Sep 6 10:28:46 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Sep 2003 14:28:46 GMT Subject: Why python??? References: <87fzjalogu.fsf@pobox.com> Message-ID: Michael Peuser wrote: ... > There is no linear scaling in these issues. It is of no importance whether > a word processor takes 0.1 sec instead of 0.01 for some operations. It is > when it takes 5 sec instead of 0.5. True, and exactly the same observation applies to most programs: there are thresholds of response time below which it's indifferent to go; if the program's response time becomes lower than the threshold, then in some cases the program will suddenly become useless, in others it will just decrease in usefulness gradually as it gets slower and slower. However, response time is roughly HALF of the picture: the other half is throughput -- amount of work done (perhaps in the background) per unit of time. This issue is most important for programs that can serve multiple users simultaneously, but even for a program and a machine dedicated to a single user it is still meaningful, as it may determine, for example, the overall size of document that the program is able to process in some way before the processing time hits the applicable threshold. Moore's Law, which was being discussed here, is crucial to both sides of the picture -- getting response time under that key threshold AND enhancing throughput. > The issues with hard real time > programs are obvious. They're not very different from those outlined above, except that (by definition of "hard") the time to consider must be a provable boundary rather than some central indicator such as 3 sigma -- a response 1 microsec too slow in one case in 100 makes a hard real time program totally unusable while it would minimally impact the usefulness of most "normal" programs. > Most code is not written for home applications or > some esoteric operating systems as windows but for telecomunication, > industry microcontrollers, car applications,.... Wrong, just like most assertions you make. Where do you get your numbers from?! Business software expenditure in the UK in 2001, for example, was for 42% in services, 38% in transportation and communication, only 16% in manufacturing and construction (sorry, not sure where the remaining 4% ended up -- check it out on the UK government official statistics site, www.statistics.gov.uk). And note that even for the sectors of communication and manufacturing only a _fraction_ can possibly have been spent on hard real-time development -- such business sectors use databases, word processors and the like just like any othere. So, offhand, I'd put HRT at *MAYBE* 25% of business software expenditures, generously. When you consider consumer software expenditure, AND all the software that is not accounted for as "expenditure" (such as most open source software), I think you'll be lucky to find that as much as TEN PERCENT of software development falls into those areas which you grandly proclaim include "most code". HA. I hope this helps readers of this thread assess the overall reliability of your many unsupported assertions. >> Python is an order of magnitude easier to learn than C++, but it >> brings really significant programmer-efficiency benefits. As a >> result, the argument about training simply doesn't stand up: the costs >> are lower than the benefits even on a short timescale. > > I know this argument well and have repeated it myself in the days of > Pascal and Algol68. Few have listened..... On Algol68, I would hope so -- that's basically how Pascal was born, by Wirth slamming the door on the Algol standardization committee as he realized they'd gone bonkers, and going back to simplicity. On Pascal, they may well not have listened to YOU (unsurprising, given the quality of your assertions as above evidenced), but they did look at reality and it did matter -- for a while, Turbo Pascal was the leading software development environment for PC's, and it segued right into the Object Pascal that underpins Delphi, still quite a viable tool (including its Kylix incarnation for Linux). Pascal hobbled itself by not developing viable standards, so that choosing Pascal basically meant chaining yourself to one supplier, and by not growing up towards application development needs (by the addition of such indispensable features for the field as garbage collection). But it still got its niche and is anything but forgotten. Turbo Pascal was the tool used to teach some programming to both of my kids in elementary school, for example (it did bring back fond memories of the early '80s, when I was considered the foremost expert of Turbo Pascal 1.0 on IBM's internal VNET usenet-like network;-). > Programmers are generally not trained in their compyna, thea are hired > including their special language skills. Most often they're hired -- for reason that may include special skills -- then (in Europe, at least) they stay on and do get training (there are lots of gov't and EU subsidies to encourage companies to offer training to their employees, incidentally). But it doesn't much matter if the training is provided by their company (with or without gov't help), by the government directly through extended schooling, by the employee himself investing time and/or money in his or her own skills: in any case, a programmer these days WILL be using different languages between the time they start working in their '20s and the time they retire in their '60s, far more often than not. >> Total costs are exactly the issue -- the contention is that use of >> languages like Python really does have a significant impact on that. > > This argument had been used by the most ambitious software tool project of > the last century, which was DoD's Ada. Very few people will ever believe > something like that again ;-) Once again a false assertion: if lots of people had not believed (for example) about that promise for Java, then Java would never have taken off (well after Ada's disappointments). Sure, in the SW industry more than in most others people have formed a callus against wild promises for still-on-paper tools. Python's advantage is that it's a mature, stable language, and has already been around enought to prove itself many times over, as the Python Success Stories begin to document. >> > This is an important factor. However all investigations show that >> > programmer's productivity is an unmeasurable quantity. >> >> How would an empirical investigation show such a thing? > > Alex gave a hint to a German study. I think he was refering to: > http://www.ipd.uka.de/~prechelt/Biblio/jccpprtTR.pdf Yes, that's one presentation of Prechelt's study, and it shows exactly the reverse of your claim: language choice DOES affect programmer productivity. Alex From robin at jessikat.fsnet.co.uk Fri Sep 26 03:44:46 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 26 Sep 2003 08:44:46 +0100 Subject: Bottleneck? More efficient regular expression? References: <3f7069db_4@corp.newsgroups.com> <3f71ad83_4@corp.newsgroups.com> <3f736cad_4@corp.newsgroups.com> <%nNcb.3635$RW4.47@newsread4.news.pas.earthlink.net> Message-ID: In article <%nNcb.3635$RW4.47 at newsread4.news.pas.earthlink.net>, Andrew Dalke writes >Tina Li: >> The lag is *perceivable* (this is what I meant; sorry) by a human user so >it's slower. > >Yup, that's what I meant. Too many people make theoretical >arguments for why to choose one (complicated) approach >over a simpler one on the basis of performance, when it turns >out performance isn't the issue. My appreciation goes out to you >for doing it the right way. > >You may also want to look at pyRXP from ReportLab. >However, there seems to be some drastic problems on their >site -- links on reportlab.com fail and reportlab.org goes >to pair.com's site placeholder page. yup we're reassembling everything again .... sigh :( New more dynamic confusion ...... > >It's a very fast XML parser for Python. > >> I in fact tried that before but the over-limit error still happened. So >it's >> not just the non-greedy .*? that's causing the problem. Hmm. > >No, I don't think it is. The stack space increases by one for >each ambiguity and the .*? should only produce one ambiguity. >Usually there's a stack problem only if you have an ambiguity >or empty match inside a repeat, and I didn't see that in your >pattern. > >If you get really interested in tracking this down, you might look >around for some of the GUI regexp debugging tools. There's >one in ActiveState's product, as I recall. Err, but it's based on >Perl's regexp parser and won't handle (?P<>) > >(I do have an experimental pure-Python regexp engine that >I would offer for debugging, but it doesn't handle .*? yet and >needs a rewrite before it does.) > >> It only handles tags without space because all tags are >> guaranteed to be generated without space. > >Sure. All I was saying was that if you're going to code for >a specific layout then you don't need to be as general. > >You might even consider using "[^\n]*\n{5}" if you just >want to skip 5 lines. > > Andrew > dalke at dalkescientific.com >P.S. > If you are doing anything open-sourceish, or using >open source in bioinformatics, structural biology, and >related fields, and will be at ISMB in Edinborough next >year, you might consider attending the Bioinformatics >Open Source Conference. > > -- Robin Becker From rdsteph at earthlink.net Thu Sep 11 22:08:18 2003 From: rdsteph at earthlink.net (Ron Stephens) Date: 11 Sep 2003 19:08:18 -0700 Subject: Learning Python, 2'nd Edition, O'Reilly References: <8e6e8e5d.0309101814.393a8ed0@posting.google.com> Message-ID: <8e6e8e5d.0309111808.762db6f7@posting.google.com> Thank you so much for your kind reply, Mr. Lutz. I look forward to the new edition of Learning Python eagerly. I know it will become a classic snapshot of a most significant time in Python's history, and will help to further popularize the language. Of course, Python in a Nutshell also, already, documents most of Python's newer features, and I am most profitably continuing to peruse both my copy of the Nutshell and my copy of the Cookbook, so I will not be wasting my (little but precious) free time until the Learning 2'nd Edition arrives. From alessandro at sephiroth.it Mon Sep 22 05:11:32 2003 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Mon, 22 Sep 2003 09:11:32 GMT Subject: py2exe: dynamic module does not define init function Message-ID: <81zbb.99124$hE5.3508075@news1.tin.it> hi, i have already problems using py2exe.. i'm using python 2.2, wxPython and audiere for a little mp3 player.. once I've build the exe with py2exe, when launching the application: Traceback (most recent call last): File "", line 9, 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 ImportError: dynamic module does not define init function (initaudiere) Sincerely I don't understand the error message.. can someone explain me the message and if there's a solution? -- Alessandro Crugnola [sephiroth] Flash | PHP Developer http://www.sephiroth.it Team Macromedia Volunteer for Flash http://www.macromedia.com/go/team Flash-php mailing list http://www.flash-php.it/index.php?ml=fpcoders&action=subscribe From hungjunglu at yahoo.com Sat Sep 27 05:01:19 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 27 Sep 2003 02:01:19 -0700 Subject: Try/except vs. if/else References: <3F70598E.8020500@bu.edu> Message-ID: <8ef9bea6.0309270101.65a69a38@posting.google.com> Shu-Hsien Sheu wrote in message news:... > catching multiple errorrs. However, problems occur if the criteria is > composed of "or" rather than "and". For instance: > > if (a in b) or (c in b): > *do something > > try: > b.index(a) > b.index(c) > *do something > except ValueError: > pass For the "or" case, actually the exception trick works rather well. Usually people raise events by hand: class Found(Exception): pass try: if a in b: raise Found if c in b: raise Found except Found: do something Of course, one can supply additional information, as in: try: if a in b: raise Found('a in b') if c in b: raise Found('c in b') except Found, e: print str(e) Hung Jung From gventer at africonnect.com Tue Sep 2 07:47:30 2003 From: gventer at africonnect.com (Gerhard Venter) Date: Tue, 02 Sep 2003 12:47:30 +0100 Subject: win32all for 2.3 Message-ID: <3F548352.7040408@africonnect.com> Hi I need to get *win32all* for 2.3 quite urgently. It should be at http://starship.python.net/crew/mhammond/win32/Downloads.html However, the starship site seems to have disappeared, even from DNS. Is there any other way I could get the file? Best regards Gerhard From lutz.horn at fiz-karlsruhe.de Fri Sep 5 03:17:49 2003 From: lutz.horn at fiz-karlsruhe.de (Lutz Horn) Date: 5 Sep 2003 07:17:49 GMT Subject: Text file extract References: <1PudndLL4fUZWMqiU-KYuA@kconline.com> Message-ID: Hi Andy, * "Andy" [05 Sep 2003]: > RECORD 1) ABCD,666,TOM,4.00,9/1/03 > RECORD 2) TYTY,666,TIM,4.00,9/1/03 > RECORD 3) ABCD,666,BILL,4.00,9/1/03 > RECORD 4) XXXX,666,TOM,4.00,9/1/03 > > All the fields will be comma separated and the 3rd field will > contain the record I will use to split. To split a string use it's split() method. If the records are in a file named "records.txt" and for each distinct value of the third field all matching records should be written to a file file named as the value with ".txt" appended, I'd do something like: # read all records from the input file records = open("records.txt").readlines() # create a dict to hold the output files. value => file outfiles = {} # loop over all records for record in records: # split the record and extract the third field (index 2) field3 = record.split(",")[2] # if the value of the field hasn't been encountered before, # open an output file and store it in the dict using # the value as the key. if field3 not in outfiles.keys(): outfile = open(field3 + ".txt", "w") outfiles[field3] = outfile # write the record to the proper output file outfiles[field3].write(record) # clos all output files for outfile in outfiles.values(): outfile.close() With your data this produces three files: BILL.txt, TIM.txt, and TOM.txt containing 1, 1, and 2 records. I leave it to you to open the files in proper subdirectories :-) Regards Lutz -- no sig From webmaster at beyond-thoughts.com Tue Sep 23 18:26:32 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Wed, 24 Sep 2003 00:26:32 +0200 Subject: a little OT: how to handle this email list? In-Reply-To: References: Message-ID: <3F70C898.9080700@beyond-thoughts.com> Hi Matthew Wilson, I have a pop3-mailbox and finally store the whole Python-List locally on my Computer hoping that the Mozilla-Maiil can handle this amount of emails. Maybe there's a feature in your IMAP-Client to "store local and del from server". Just killing threads (as mentioned in other answers) seems OK to me, because you can stil get those threads on gmane.org Christoph Becker-Freyseng From glingl at aon.at Mon Sep 8 08:45:02 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon, 08 Sep 2003 14:45:02 +0200 Subject: GIFs Using Tkinter Message-ID: <3f5c7a2f$0$13788$91cee783@newsreader02.highway.telekom.at> I'm trying to use recipe 9.5 from Python Cookbook, which suggests to read gifs from files using base64.encodestring in order to embed those images into my sourcecode. I've prepared some 20 gifs with Photoshop which are all merely rotated versions of some "master"-gif. (They all are produced in exactly the same way and have (255,255,255) as transparent color.) They all can be used as Tkinter PhotoImages with the file-option perfectly well. However, if I try to use the data-option with strings constructed from those same gifs according to the recipe mentioned above, I observe, that among those gif-images (1) some can be displayed correctly (more than 50%) (2) some are corrupted and are displayed with stripes or other artefacts. (3) and some result in strings only a few characters long which cannot be interpreted as image-data at all. What could be the reason for this annoying behaviour and how can I avoid it. Thanks in advance Gregor From jepler at unpythonic.net Wed Sep 17 08:08:48 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 17 Sep 2003 07:08:48 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <3F67D36B.80709@sci.fi> References: <3F632226.2010607@earthlink.net> <5CH9b.81$2k.16@reader1.news.jippii.net> <20030916211148.GD29089@unpythonic.net> <3F67D36B.80709@sci.fi> Message-ID: <20030917120842.GA5446@unpythonic.net> On Wed, Sep 17, 2003 at 06:22:19AM +0300, Harri Pesonen wrote: > But wouldn't it be better if Python had real multitasking? Comments like > the above mean that you accept Python as it is, fine. But usually people > want to make things better when they see that something can be improved. > If my roof is leaking, I have two choices: fix it or accept it. If I am > able to fix it, then I'll probably do it. > > The old code base really is the problem here. If Python threads really > run at the same time in the future, how many current applications stop > working because they depend on the fact that only one thread runs at any > given time, and do not acquire and release locks as needed? On the other > hand, my suggestion probably means that we couldn't have a threading > module compatible with thread or threading anyhow (we could have > freethreading, with specific functions for inter-thread communication). I don't think "the roof is leaking". In the current situation, users can write threads in the cases where they make sense (and easily share any data without jumping through hoops) and even derive a performance benefit when the threads' work is done without the GIL held. Or, they can use multiple processes with explicit data sharing, and derive a performance benefit even when each process does its work with the GIL held. In your situation, the first paradigm becomes impossible, and the second paradigm has been modeled with a "shared nothing" approach which adds complexity to Python to achieve with threads what the operating system already offers using processes! Keep in mind that probably more than of 99.9% of machines out there have only one CPU anyway, so all you re-claim is the GIL overhead if you remove it. Yay, a 2%* performance increase for a huge loss in flexibility. And processes still win, because you can probably easily hack out the thread/threading modules, turn the GIL operations into no-ops, and use fork() to get that 2%* performance increase. Let me know when you have benchmark figures to the contrary. Jeff * Number picked out of the air From nid_oizo at yahoo.com_remove_the_ Fri Sep 26 13:19:35 2003 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 26 Sep 2003 13:19:35 -0400 Subject: Reduce need of backslash In-Reply-To: References: Message-ID: John Roth wrote: > "Duncan Booth" wrote in message > And you can parenthesize a surprisingly large number of places. One > that I learned just recently was that the entire operand string of the > print statement can be put into parenthesis. I'm not sure what you mean exactly. print (1,2) prints a tuple while print 1,2 prints a different thing. Regards, Nicolas From max at alcyone.com Tue Sep 9 15:15:48 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Sep 2003 12:15:48 -0700 Subject: Jython class names References: Message-ID: <3F5E26E4.EE26660C@alcyone.com> Robin Becker wrote: > I just tried [in Jython] and wow > > >>>> class C: pass > >... > >>>> C().__class__.__name__ is C.__name__ > >True > > it doesn't work The obvious question might be why you're expecting it to work. Why are you testing string equality with the is operator? Test it with the equality operator, ==. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Silence is the most perfect expression of scorn. \__/ George Bernard Shaw From vivek at cs.unipune.ernet.in Fri Sep 12 07:38:28 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Fri, 12 Sep 2003 17:08:28 +0530 Subject: python program not running from different folders In-Reply-To: <001701c3791f$e80fea10$3aa2e7c1@integrasoft.ro>; from jboti@integrasoft.ro on Fri, Sep 12, 2003 at 02:20:43PM +0300 References: <001701c3791f$e80fea10$3aa2e7c1@integrasoft.ro> Message-ID: <20030912170828.A4664@cs.unipune.ernet.in> On Fri, Sep 12, 2003 at 02:20:43PM +0300, Jozsa Boti wrote: > Hi! > > I have a strange problem: I wrote a program in python, and I get an error: ImportError: dynamic module does not define init function (initESSClientAPI) but only if I run the program in certain folders. The same program runs without any error from other folders. Any ideas? > As u have described it seems that the folder from which u are trying to run the script contains some dll/so which have the same name as one of the modules u are using in your script. eg. like in your script u have: import xyz #call some function from xyz xyz.funct() here xyz is some python module u are using. but as the error message says it may be that the particular folder from which the script gives ImportError contains some dll/so with the same name i.e. xyz.dll or xyz.so. Still it is just a wild guess :-) Regards Vivek Kumar From tjreedy at udel.edu Mon Sep 22 19:57:49 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2003 19:57:49 -0400 Subject: Slicing vs .startswith References: Message-ID: "Shu-Hsien Sheu" wrote in message news:mailman.1064245938.12315.python-list at python.org... > Hi, > > For example, which one of the following would be more efficient, or , > moreover, more pythonic? > > if aa[:3] == 'abc': This creates and deletes a temporary object. > if aa.startswith('abc'): This makes a function call. As Bob showed for his system, the two overheads are about the same for a three char prefix. If one were checking a 30000 byte prefix, the call might win. Terry J. Reedy From mitchchapman at earthlink.net Sat Sep 13 09:16:01 2003 From: mitchchapman at earthlink.net (Mitch Chapman) Date: Sat, 13 Sep 2003 07:16:01 -0600 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <16226.9487.204094.248590@montanaro.dyndns.org> Message-ID: <6BB6268D-E5EC-11D7-A7C2-000393D443CE@earthlink.net> On Friday, September 12, 2003, at 01:57 PM, Skip Montanaro wrote: > Mitch> At IPC8 Greg Wilson, then of the Software Carpentry project, > Mitch> noted that the GIL made it hard to write multi-threaded > Python > Mitch> apps which could take advantage of multi-processor systems. > He > Mitch> argued that this would limit Python's appeal in some > segments of > Mitch> the scientific community. > > This is a known issue. For example, it was discussed at IPC8 ;) > Thusfar, it hasn't seemed to slow down Python's > acceptance by the scientific community all that much. Good point. > Mitch> Perhaps those who find the subject important have left the > Mitch> community? Perhaps they've adopted kludgey workarounds? > > Or perhaps they are happy to have tools like scipy and MayaVi to make > their > jobs easier. No doubt. I'm among those happy to have access to scipy.weave, for example. But I also wish for better thread scalability to make my job easier. Unlike Andrew I don't think the lack of maintenance for 1.4's free threading packages is due to any perception that threading performance is unimportant. It seems more likely that the packages were not updated because they proved not to solve the performance problems, and that no alternatives have emerged because the problem is hard to solve. So, if Harri Pesonen has ideas for achieving better thread scalability, I want to encourage him to develop them rather than to suggest such an effort is unimportant to the community. > Nobody has claimed that it isn't a problem for some people. I read Andrew's comment as meaning that he believed nobody in the community thought scalable threading was particularly important. In order for that to be true, something like Greg Wilson's prediction, that many who would otherwise have found Python appealing would have turned to other solutions, would have to have come to pass. ("Perhaps those... have left the community?") Or else, as I noted, people might have found kludgey workarounds. Or as had happened in my company, they might have deferred some performance problems which could have been addressed by scalable threading. Both of which are consistent with your observation: > It's maybe less > of a problem than it appears at first though. Having said all of that, it looks like this thread originated on python- dev, rather than on c.l.py where I found it. So I'm probably missing some reasons for what appears to be a dismissive attitude toward Harri's efforts. I'll go read the python-dev archives. -- Mitch From fredrik at pythonware.com Tue Sep 2 03:48:28 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 Sep 2003 09:48:28 +0200 Subject: printer friendly python tutorial References: <5.2.1.1.0.20030901234513.02e92120@66.28.54.253> Message-ID: Bob Gailer wrote: > >>does anyone know where i can find a printer friendly version of the > >>python tutorial release 2.3? > >never mind i found it? > > Where? We'd like to know too. http://www.python.org => Documentation => Download Current Documentation (first link on page) => http://www.python.org/doc/current/download.html where the table on the top of the page contains download links for HTML, PDF, Postscript, GNU info, iSilo, and LaTeX versions of the docs, in ZIP, GZip, and BZip2 archives. From jjl at pobox.com Wed Sep 3 19:02:11 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Sep 2003 00:02:11 +0100 Subject: Extracting TIFF from emails References: <87y8x654qk.fsf@pobox.com> Message-ID: <87llt5fpcc.fsf@pobox.com> ryan at ryanswift.com (Ryan Swift) writes: > I have found the email module, I'm not 100% sure you have. My 'the email module' I meant 'the module named "email" from the Python standard library'. > I am using 2.2.2. > > This is my code: No it's not -- where are the imports? This isn't C, we don't like to guess these things :-) [...] > AttributeError: 'list' object has no attribute 'walk' > > Am I not properly using walk? lists have no walk method! Presumably you thought you had something other than a list, but you don't. John From john at rygannon.com Tue Sep 23 07:52:19 2003 From: john at rygannon.com (John Dean) Date: Tue, 23 Sep 2003 11:52:19 GMT Subject: ANN: Rekall V2.1.0 beta2 Message-ID: <3f703401$0$10975$fa0fcedb@lovejoy.zen.co.uk> Hi We are please to announce that we have just started beta testing Rekall V2.1.0 beta2. You can download a demo version from either http://www.totalrekall.co.uk or http://www.rygannon.com . If we don't come across any major bugs in this beta release then a full stable version will be put out within the next two to three week. All planned new features are now complete and working What is Rekall? Rekall is a programmable database independant GUI database client, which can be considered a cheaper alternative to MS Access Rekall runs on all the major Linux distributions and Windows. A version for Mac X is being worked on. Rekall includes plugin drivers for xBase, PostgreSQL, and MySQL as standard. Additional native code drivers are available for DB2, Oracle9i and ODBC -- Best Regards John From pythonguy at Hotpop.com Thu Sep 11 06:05:44 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 11 Sep 2003 03:05:44 -0700 Subject: My future Python IDE article References: Message-ID: <84fc4588.0309110205.c885e29@posting.google.com> > David Mertz wrote: > > So c.l.py readers... make the case for your favorite one getting on the > > list. GNU Emacs + python-mode is my favorite. Apart from that I use: 1. XEmacs + python-mode, (not as good as Emacs + python-mode) 2. IDLE -Anand From nomail at nomail.com Wed Sep 10 11:10:13 2003 From: nomail at nomail.com (Michael Schmitt) Date: Wed, 10 Sep 2003 17:10:13 +0200 Subject: Reportlab Image object opens filehandles References: <3f5f36de$1@news.highway1.com.au> Message-ID: Tim Hoffman wrote: > Have a look at limit (or in csh ulimit) > > 256 open files is the default limit for a user/process. (all about > conserving resources) you can make this bigger (much bigger ;-) assuming > you have permissions. > > Rgds > Hello Tim. unfortunately changing this limit is not an option for me. Thanks. Regards, Michael From paulpaterson at users.sourceforge.net Tue Sep 9 01:41:05 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Tue, 09 Sep 2003 05:41:05 GMT Subject: ANN: vb2Py 0.2 - VB to Python Conversion Message-ID: Version 0.2 of vb2py has been released. What is vb2py? ============== vb2py is a toolkit to aid in the conversion of Visual Basic projects to Python. The aim of the conversion is to match, as closely as possible, the original VB applications both in terms of code and form behaviour. Version 0.2 comprises a basic layout converter (converting to PythonCard) with a comprehensive code translation. The project roadmap (http://vb2py.sourceforge.net/roadmap.htm) shows the project's development timeline. Converting VB to Python turns your VB projects into cross platform developments and allows full access to all Python's extensive library of modules. What's new in v0.2 ================== The key development in v0.2 is the inclusion of the full VB code parser and converter. Whereas v0.1 was just a form layout converter, v0.2 parses all the VB code and translates it to the equivalent Python code. All major code constructs from VB are covered (Sub, Fn, If, While, For, Select, With, Classes, Properties, Types, etc) and most instrinsic functions and constants are implemented as Python equivalents. The other major addition to v0.2 is the inclusion of a GUI to enable the progress of the conversion to be monitored and tweaked using the options system. The GUI is a PythonCard application running on top of the main vb2py library. The GUI is not required to convert VB code, a fully functioning command line alternative is available. Linux is now supported (this was badly broken in v0.1!) Limitations of v0.2 =================== - Form layout translation is still at the v0.1 level. (target v0.3) - Control event mapping is still primitive (target v0.3) - Error handling, ByRef argument passing, Iterable classes are not currently supported (target v0.4) Getting the Software ==================== * The main website: http://vb2py.sourceforge.net * Download this version: http://vb2py.sourceforge.net/downloads.htm * Documentation: http://vb2py.sourceforge.net/documentation.htm Requirements ============ * Python 2.2 or greater * PythonCard (0.7 or greater), wxWindows * simpleparse (2.0.1a2 or greater), mxTools * Visual Basic is *not* required (although it would help if you had some VB code ...) Licence ======= vb2py is released under the BSD licence. Release History =============== 0.1 (July 9, 2003) - The first release from the project - a basic form layout translator 0.1.1 (August 1, 2003) - A bugfix release for 0.1 0.2 (September 8, 2003) - This release Contributors Welcome ==================== This project would not be possible without the help and support of many people. Anyone who wants to get involved is more than welcome to participate in coding, testing, giving advice, etc. Some particular areas of interest right now are, - testing on large VB projects - testing on Mac - testing out with VBScript, VBA In the meantime I would like to thank all those who supported and contributed towards the v0.2 release. ---- Paul Paterson vb2py :: A Visual Basic to Python Conversion Toolkit http://vb2py.sourceforge.net From gh at ghaering.de Fri Sep 26 08:46:20 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 26 Sep 2003 14:46:20 +0200 Subject: Where to import modules? In-Reply-To: References: Message-ID: <3F74351C.8050507@ghaering.de> Andreas Neudecker wrote: > Hi. > > I have a "style" question: Sometimes, modules will only be used in a > particular, optional, part of a program (function, class), that will not > always be used when the application is run. So I think it is better to > import them only there, not on the top of the file (together with the > other imports). Is that okay, or are there good reasons for not doing so? That's perfectly ok, if you want/need to optimize your program startup time. It might also save a byte or two of memory, depending on how large the module is. -- Gerhard From peter at engcorp.com Mon Sep 22 19:17:26 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Sep 2003 19:17:26 -0400 Subject: Slicing vs .startswith References: <3F6F12A1.3010702@bu.edu> <6e7b9822.0309221439.6dea760e@posting.google.com> Message-ID: <3F6F8306.1ABCC6D@engcorp.com> Paul wrote: > > However, what if you don't want case sensitivity? For example, to > check if a file is a jpg, I do name[-3:].lower() == 'jpg'. This will > work with both foo.jpg and foo.JPG. > > Is this slower than name.lower().endswith('jpg')? Is there a better > solution altogether? Yes, of course. :-) import os if os.path.splitext(name)[1].lower() == 'jpg': pass That also handles the problem with files named "ThisFileIs.NotAjpg" being mistreated, as the other solutions do. ;-) -Peter From mwh at python.net Fri Sep 26 11:34:57 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Sep 2003 15:34:57 GMT Subject: 64-bit EPIC and some modules References: <7h3smmm2m0w.fsf@pc150.maths.bris.ac.uk> <0ck3nvoicm45kb0oon2etsucttatc3aob7@4ax.com> <7h3ad8t2k6q.fsf@pc150.maths.bris.ac.uk> <89d6nv85qdrvegiehk25rpkpirogvqspgi@4ax.com> Message-ID: <7h3k77vo9ea.fsf@pc150.maths.bris.ac.uk> Christos "TZOTZIOY" Georgiou writes: > On Thu, 25 Sep 2003 11:20:27 GMT, rumours say that Michael Hudson > might have written: > > >PS: hp-ux/itanium appears to be utterly horked... > > Thank God this is not a HP/UX then... presumably. See PS. > > PS: What is horked??? "broken". I tried to build 2.3.1 on the HP testdrive itanium/hp-ux machine, and the results were far from encouraging. Cheers, mwh -- [2. More type system hacking --- text/plain; type-argh.diff] -- csr on sbcl-devel From richie at entrian.com Tue Sep 9 08:56:39 2003 From: richie at entrian.com (Richie Hindle) Date: Tue, 09 Sep 2003 13:56:39 +0100 Subject: Ternery operator In-Reply-To: <7uhrlvoduqfcg64nvccua3ee0hklrc4lb1@4ax.com> References: <1063110398.3f5dc6fe94f18@mcherm.com> <7uhrlvoduqfcg64nvccua3ee0hklrc4lb1@4ax.com> Message-ID: <9bjrlvg1jkhtt5sd9gi4rlm18cfvsoce81@4ax.com> [Me] > >>> def one(): > print 1 > return 1 > > >>> def two(): > print 2 > return 2 > > >>> (True and [one()] or [two()])[0] > 1 > 1 > >>> (False and [one()] or [two()])[0] > 2 > 2 > >>> > > So it's lazy in the sense of "will not execute the branch not taken", > which is I'm sure what Uwe meant. But it's also over-eager in the sense > of "may execute the taken branch multiple times." Duh, sorry, I still have my Monday head on. Ignore that second sentence. This would have been a better demonstration: >>> def one(): print "One" return 1 >>> def two(): print "Two" return 2 >>> print (True and [one()] or [two()])[0] One 1 >>> -- Richie Hindle richie at entrian.com From tzot at sil-tec.gr Tue Sep 16 10:19:50 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 16 Sep 2003 17:19:50 +0300 Subject: Datetime utility functions References: <182bcf76.0309150707.3a8c0482@posting.google.com> Message-ID: On Mon, 15 Sep 2003 20:44:08 +0100, rumours say that Paul Moore might have written: [find the end of the month] >The best solution I could find was > >def month_end(dt): > # Get the next month > y, m = dt.year, dt.month > if m == 12: > y += 1 > m = 1 > else: > m += 1 > > # Use replace to cater for both datetime and date types. This > # leaves the time component of a datetime unchanged - it's > # arguable whether this is the right thing. > > return dt.replace(year=y, month=m, day=1) - datetime.timedelta(days=1) I sent my own version without having seen your own --and mine might seem obfuscated, compared to yours. Only a minor suggestion: don't use dt.replace, use dt.__class__ instead, since you wouldn't want your function to have side-effects (that is, don't destroy the actual object that dt is bound to.) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From python at sarcastic-horse.com Mon Sep 15 11:51:27 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Mon, 15 Sep 2003 11:51:27 -0400 (EDT) Subject: unique unions of several dict keys Message-ID: <59256.199.169.240.132.1063641087.squirrel@svr1.turboweb.net> Hi- I have several different dictionaries. I want to make a unique list of all the keys in all the dictionaries. What would be the best way of doing that? Thanks. From bokr at oz.net Wed Sep 10 10:49:05 2003 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2003 14:49:05 GMT Subject: Redesign of Python site References: <3F5E0171.B68BDE2F@engcorp.com> <_WydnXPHCO6oksOiRTvUqA@speakeasy.net> Message-ID: On Tue, 9 Sep 2003 14:06:22 -0500, Skip Montanaro wrote: > > amk> I envision people wanting information on a specific version first, > amk> only later going to the more generic items under "documentation". > amk> Do other people think this would be a good idea? > >I think docs are more important than specific versions. Sure, the first >time they come to the site they'll be looking for "Python 2.3". But most >times after that they'll want documentation. The most frequent page I visit >on the site is > > http://www.python.org/dev/doc/devel/modindex.html > >That far outpaces any other page on the site, even the home page, so I >bookmarked so it's one click away. > For the most part, I use downloaded HTML docs from my HD. And a command line hack to search with regex the index page for links to the individual module docs and/or launch the browser to a particular doc. E.g., (the opts handling code is a bit weird, just a quick experiment, not meant as a model ;-) [ 7:36] C:\pywk\clp>modoc Usage: modoc.py [-h] [-re | -ire ] [-href] pattern Without opts, pattern is taken as a module name to start browser showing docs for. With opt(s): -re: pattern is taken as regex to print available matching doc names -ire: same as -re but case insensitive -href: prints doc href paths along with names found. -h: print this Doc info is retrieved from the html file defined by environment name PY_DOC_INDEX, e.g., modindex.html and this is located (along with pages therefrom referenced) by prefixing the string defined by PY_DOC_PREFIX, e.g., D:/Python23/Doc/ (note forward slashing and ending slash). The ref_name_patt regex may need change if generated documentation links change format. [ 7:37] C:\pywk\clp>modoc -ire os MacOS TERMIOS macostools os os.path ossaudiodev posix posixfile termios [ 7:37] C:\pywk\clp>modoc -re os macostools os os.path ossaudiodev posix posixfile termios [ 7:37] C:\pywk\clp>modoc os.path (browser pops up with os.path doc). Oh, I forgot: [ 7:39] C:\pywk\clp>modoc -re os -href macostools: 'mac/module-macostools.html' os: 'lib/module-os.html' os.path: 'lib/module-os.path.html' ossaudiodev: 'lib/module-ossaudiodev.html' posix: 'lib/module-posix.html' posixfile: 'lib/module-posixfile.html' termios: 'lib/module-termios.html' I was thinking of expanding it to cover more of the doc hierarchy, but never got a round tuit. In case someone want to use/improve it: (Note the PY_DOC_PREFIX = os.environ.get('PY_DOC_PREFIX', r'D:/Python23/Doc/') PY_DOC_INDEX = os.environ.get('PY_DOC_INDEX', r'modindex.html') lines, which you may want to change for your system setup). ----< modoc.py >--------------------------------------------------------------------------- # modoc.py -- quick way to get to module docs from command line """ Usage: modoc.py [-h] [-re | -ire ] [-href] pattern Without opts, pattern is taken as a module name to start browser showing docs for. With opt(s): -re: pattern is taken as regex to print available matching doc names -ire: same as -re but case insensitive -href: prints doc href paths along with names found. -h: print this Doc info is retrieved from the html file defined by environment name PY_DOC_INDEX, e.g., modindex.html and this is located (along with pages therefrom referenced) by prefixing the string defined by PY_DOC_PREFIX, e.g., D:/Python23/Doc/ (note forward slashing and ending slash). The ref_name_patt regex may need change if generated documentation links change format. """ __version__ = '0.10a' # Original code by Bengt Richter, offered for free use, with no warranty of any kind. # v0.1a: 20030813 13:29:40 # + docs and untested env variable defs for doc locs # + using webbrowser module to start browser instead of os.system # handy to run from c:\util\modoc.cmd wrapper, e.g., # @python c:\pywk\ut\modoc.py %* import re, os, webbrowser PY_DOC_PREFIX = os.environ.get('PY_DOC_PREFIX', r'D:/Python23/Doc/') PY_DOC_INDEX = os.environ.get('PY_DOC_INDEX', r'modindex.html') def dispmod(namex='', **opts): """Display module doc via browser or search names for match. See module doc.""" page = file(PY_DOC_PREFIX+PY_DOC_INDEX).read() ref_name_patt = r'
([^<]+)' #XXX brittle rx = re.compile(ref_name_patt) modict = dict([(name, ref) for ref,name in rx.findall(page)]) names = modict.keys() names.sort() if opts: regex = namex # default case sensitive match if 're' in opts: pass elif 'ire' in opts: regex = '(?i)'+namex elif 'all' in opts: regex = None if regex: rx = re.compile(regex) names = list(filter(rx.search, names)) names.sort() for i, name in enumerate(names): if 'href' in opts: print '%19s: %r' % (name, modict[name]) else: if i and not i%4: print print '%-19s' % name, else: namex = namex.lower() for name in names: if name.lower() == namex: webbrowser.open_new('%s%s' % (PY_DOC_PREFIX, modict[name])) return raise SystemExit, 'Module "%s" not found.' % namex if __name__ == '__main__': import sys args = sys.argv[1:] if not args or '-h' in args: raise SystemExit, __doc__ callargs=[]; callkw={} while args: arg = args.pop(0) if arg.startswith('-'): callkw[arg[1:]]=True else: callargs.append(arg) dispmod(*callargs, **callkw) ------------------------------------------------------------------------------------------- Regards, Bengt Richter From cmkleffner at gmx.de Fri Sep 26 06:31:28 2003 From: cmkleffner at gmx.de (cmkl) Date: 26 Sep 2003 03:31:28 -0700 Subject: Compiling informxidb-1.3 on python2.2? References: Message-ID: <3b091a1c.0309260231.54e8ef5@posting.google.com> Hi Mick, a while ago I managed the compilation of informixdb 'manually' without help of Makefiles or configure scripts or distutils for Python-2.2.1. Basically all you need is to compile dbi.c as well as _informixdb.c and to link it to a shared library. informixdb.py and _informixdb.so then has to be copied to the proper places. What you need as well is the help of th esql script provided with the informix sdk and the information provided in the lib/config/ folder of your Python installation (used compiler switches, libraries for linking ...). Run: esql -e -G -libs _informixdb.ec or esql -e -G -thread -libs _informixdb.ec to get a list of the informix libraries and objectfiles needed for linking. Of course you need to specify the path to the informix include files and the path to the library files as well as the library files for compilation and linking. There are other issues with informixdb as well: 1) DBI 1-0 interface: dates are limited to EPOCH (aka unix time) due to limitations of the DBI-1.0 specification. 2) all Informix warnings raise an error in the informixdb layer. In many cases this is not wanted. I can send you the patches I got from different people/places. Carl cmkleffner at gmx.de msajec at ieee.org (Mike S.) wrote in message news:... > Well I managed to get the configure script to run: > > ./configure > loading cache ./config.cache > checking whether make sets ${MAKE}... (cached) yes > checking for python... (cached) /usr/bin/python > checking for --with-informix... /opt/informix > checking for esql... (cached) /opt/informix/bin/esql > checking for --enable-thread... no > checking for --enable-shared... yes > creating ./config.status > creating Makefile > creating ext/srcdir > creating ext/Setup > creating ext/Makefile > > But got a ton of errors when trying step 5 in Robin's list: > > >>esql _informixdb.c > > _informixdb.ec:48:20: Python.h: No such file or directory > _informixdb.ec:49:24: longobject.h: No such file or directory > In file included from _informixdb.ec:50: > dbi.h:13: parse error before '*' token > dbi.h:14: parse error before '*' token > dbi.h:15: parse error before '*' token > dbi.h:18: parse error before '*' token > dbi.h:18: parse error before '*' token > dbi.h:18: warning: data definition has no type or storage class > dbi.h:19: parse error before '*' token > dbi.h:19: parse error before '*' token > dbi.h:19: warning: data definition has no type or storage class > dbi.h:20: parse error before '*' token > dbi.h:20: parse error before '*' token > dbi.h:20: warning: data definition has no type or storage class > dbi.h:21: parse error before '*' token > dbi.h:21: parse error before '*' token > dbi.h:21: warning: data definition has no type or storage class > dbi.h:35: parse error before '*' token > dbi.h:35: warning: data definition has no type or storage class > > > Make sense to anyone?? > > > msajec at ieee.org (Mike S.) wrote in message news:... > > > 2. Untar, run configure > > Unfortunately, the trouble starts here at step 2. By any chance do > > you have both python1.5 and python2.2 installed? > > > > root at pe informixdb-1.3]# ./configure > > loading cache ./config.cache > > checking whether make sets ${MAKE}... (cached) yes > > checking for python... (cached) /usr/bin/python > > checking for --with-informix... /opt/informix > > checking for esql... (cached) /opt/informix/bin/esql > > checking for --enable-thread... no > > checking for --enable-shared... yes > > creating ./config.status > > creating Makefile > > creating ext/srcdir > > creating ext/Setup > > cp: cannot stat `/usr/lib/python1.5/config/Makefile.pre.in': No such > > file or directory > > creating ext/Makefile > > make: ./Makefile.pre.in: No such file or directory > > make: *** No rule to make target `./Makefile.pre.in'. Stop. > > [root at pe informixdb-1.3]# > > : > > > > Robin Munn wrote in message news:... > > > Mike S. wrote: > > > > Hello, > > > > > > > > Has anyone had success compiling the informixdb-1.3 module under > > > > python 2.2? It seems the absense of makefile.pre.in in python 2.2 > > > > causes the break under py2.2. Is there an easy way around this. I've > > > > heard rumors of a manual method, but have been unable to track down > > > > details. Any help is very much appreciated. > > > > > > > > Thanks in advance, > > > > Mike > > > > > > Here's the step-by-step notes I wrote for myself when I had to do > > > exactly that back in May: > > > > > > Steps in installing the informixdb module: > > > > > > 1. Download informixdb source from > > > http://starship.python.net/crew/sturner/informixdb.html > > > 2. Untar, run configure > > > 3. Edit ext/Makefile: change CFLAGS (line 100) to include > > > -I${INFORMIXDIR}/incl/esql > > > 4. Cd into ext directory > > > 5. Run "esql _informix.ec" to generate _informix.c file > > > 6. Cd back into parent directory > > > 7. Run make > > > 8. Copy informixdb.py and ext/_informixdb.so into > > > /usr/lib/python2.2/site-packages/ > > > > > > I hope this helps. I did this install on a Red Hat machine that had the > > > Informix SDK installed, so I had the esql command available. If you > > > don't have esql available, then I'm not sure what you'll need to do. > > > > > > Good luck! From PeterAbel at gmx.net Thu Sep 25 16:27:24 2003 From: PeterAbel at gmx.net (Peter Abel) Date: 25 Sep 2003 13:27:24 -0700 Subject: Newbie: Changing a string to a class attribute. References: <33fbf9ec.0309241210.7acfddb9@posting.google.com> Message-ID: <21064255.0309251227.76336087@posting.google.com> jacobsmail at gmx.net (Jacob H) wrote in message news:<33fbf9ec.0309241210.7acfddb9 at posting.google.com>... > This is a very simple problem and I'm sure the answer is a no brainer. > However my brain can't see the answer. ;) > > Given code like this: > > def exec_method(object, method): > # object is an instantiated object, e.g. log > # method is a string that matches a method of object, e.g. > "update" > # code stuff here that calls object.method, e.g. log.update() > > What is the best way to turn method, a string, into a valid reference > to the actual class method? My first thought was eval(). But I can't > do this: > > eval("class.method()") > You're quite close! > Eval will look for a method actually called method() and there isn't > one. What's a good solution for this? Heck, for all I know, Python > implicitly provides functionality to solve this problem. Can anyone > help? :) > > Jake >>> class LOG: ... def up_date(self): ... print 'update' ... >>> log=LOG() >>> >>> def exec_method(object, method): ... eval('object.'+method) () ... >>> exec_method(log,'up_date') update >>> >>> Hope that helps. Regards Peter From max at alcyone.com Sat Sep 6 17:26:29 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 06 Sep 2003 14:26:29 -0700 Subject: Newbiequestion about lists and arrays.... References: <9193c0d1.0309061320.a0f430f@posting.google.com> Message-ID: <3F5A5105.66F55B20@alcyone.com> Michael wrote: > I would like to use an multidimensional matrix (3D or more) with > numbers (int:s and float:s). Could i use lists or arrays? How can i > retrieve a single element out of a list thats already in an other list > thats already in an other list (and so on...) It's because Python doesn't have copy semantics. You're building a list of lists of lists, some of whose elements are references to the same list. To ensure that these lists are all distinct objects, and thus giving you the expected behavior, don't use references to previous objects; create new ones instead: >>> c = [] >>> for x in range(3): ... xs = [] ... for y in range(3): ... ys = [] ... for z in range(3): ... ys.append([1, 2, 3]) ... xs.append(ys) ... c.append(xs) ... >>> c [[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]], [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]], [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]] >>> c[1][1][1] = 888 >>> c [[[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]], [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], 888, [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]], [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]]] There are other ways to do the job, of course, involing say list comprehensions. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You're wasting time / Asking what if / You linger on too long \__/ Chante Moore From jan at jandecaluwe.com Thu Sep 11 03:43:11 2003 From: jan at jandecaluwe.com (Jan Decaluwe) Date: Thu, 11 Sep 2003 09:43:11 +0200 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> <3F5F8742.C1C66903@engcorp.com> <3F5F95B9.A8CB5786@easystreet.com> Message-ID: <3F60278F.7EB2FC30@jandecaluwe.com> achrist at easystreet.com wrote: > > Peter Hansen wrote: > > > > > > Queue.Queue.get() ... > > > > That looks good. But that needs a thread to block, right? > A generator manages to run without being a thread (at least > overtly). If we have the suck() statement, we also need > something that's the opposite of a generator (a Sucker?) > and something that's the opposite of an iterator (a Suckee?). > I'm starting to get an idea why this is completely not all > there. > > The main question this raises is "How lightweight are threads?" > Can I program with dozens or hundreds of python threads in a > program (for example under Windows) and not notice that this is > an inefficient or inept coding style? > > Al You may want to check out how such things are done with my MyHDL package. The target application is hardware design, but the idea is more probably general. http://jandecaluwe.com/Tools/MyHDL/manual/model-obj.html Jan -- Jan Decaluwe - Resources bvba - http://jandecaluwe.com Losbergenlaan 16, B-3010 Leuven, Belgium Bored with EDA the way it is? Check this: http://jandecaluwe.com/Tools/MyHDL/Overview.html From newsgroups at jhrothjr.com Sun Sep 7 07:21:40 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 7 Sep 2003 07:21:40 -0400 Subject: Anyone ever overridden a builtin by accident? References: Message-ID: "John Ladasky" wrote in message news:c09b237b.0309061922.10d74b39 at posting.google.com... > Hi there, > > Just wanted to share a frustrating programming bug that, when I > figured it out, made me gasp, and then laugh. > > In one of my programs I wrote... > > c = max(a,b) > > ...and I was getting the most annoying, frustrating error message: > "type 'int' is not callable." > > What the heck? I wasn't calling an integer, I was calling the > __builtin__ function, max()! > > I dropped out of my regular editor (SciTE), opened IDLE, and tried > typing in bits of my code, including the call to max(). Everything > seemed to work fine. > > Then, I finally spotted the problem. At the beginning of my program I > had defined a variable called "max"! I had overridden the __builtin__ > function by mistake. > > Is there ever a good reason to override something in __builtin__? > It's powerful, but potentially quite confusing. Can the interpreter > be instructed to give a warning message when you do it? I believe that that's in the plan somewhere. The difficulty is that it would undoubtedly break a lot of existing code, so it isn't going to show up in 2.4 in its full glory. A warning might be feasible, though. There's a program (pychecker? I think that's the name) that should be able to tell you whether you accidentally shadowed a built-in. > Yes indeed, *everything* in Python is an object. Let the newbie > beware! John Roth > > -- > John J. Ladasky Jr., Ph.D. > Department of Biology > Johns Hopkins University > Baltimore MD 21218 > USA > Earth From NO-MAIL at hotmail.com Wed Sep 10 02:42:37 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Wed, 10 Sep 2003 06:42:37 GMT Subject: CGI -- generating images -- \x0A always added! References: Message-ID: > >>> print "foo",;sys.stdout.softspace = 0 This doesn't work. \x0A is added anyways. And from what I've read it shoudn't work -- it influences only the blank BEFORE each print that doesn't go after NL. > sys.stdout.write( "Content-type: image/gif\n\n" ) > sys.stdout.write( data ) > sys.stdout.close() # or flush() Doesn't work at all. Server error. Premature end of script headers. From hwlgw at hotmail.com Wed Sep 3 08:20:24 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 3 Sep 2003 05:20:24 -0700 Subject: Python REST framework? References: Message-ID: > [Jack Diederich] > Practicality beats purity, if the only piece of state you keep is > "this guy is logged in and he authenticated as 'Bob'" then you still > get 99.99% of the cleanliness of REST. If the workarounds to make > it 100% REST-ful actually make the solution harder to use and implement > then I'll gladly be [a little bit] non REST-ty. > > The point of REST is to make things easier to do and cleaner to > understand, not just so you can name drop "REST", right? > I thought REST was about "interoperability", a stupid word and I would like another but my English is bad. The idea is that HTTP + XML is so much standard that everybody can use your services. But for some, think about people in the industry, the strongest argument for REST is scalability. The web and email are the only examples of *really* scalable application, where the numbers are dozens of millions. And REST is the web's architecture. -- If Windows is the answer, it must have been a stupid question. From aleax at aleax.it Thu Sep 25 10:03:55 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Sep 2003 14:03:55 GMT Subject: newbie script References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> <3f719ed5$0$14824$79c14f64@nan-newsreader-03.noos.net> <3f72eb7c$0$29964$79c14f64@nan-newsreader-02.noos.net> Message-ID: ataraxia2500 wrote: > hey Ed, > I get that weird error when I tried to run the little loop, this is what > it says: > > sys:1: DeprecationWarning: Non-ASCII character '\xa0' in file myloop.py on > line 3, but no encoding declared; see http://www.python.org/peps > pep-0263.html for details > File "myloop", line 3 > os.system('/home/joe/src/myprog/myprog') > ^ > SyntaxError: invalid syntax > > does it mean anything to you? Sure! You have a weird character, of hex code A0, somewhere on your line 3. How it got there, I dunno. Anyway, what you need to do is remove it -- a good editor should be able to show you exactly where it is, otherwise just use a small Python script to find that out. Alex From calderano at sgaspa.it Mon Sep 15 06:55:15 2003 From: calderano at sgaspa.it (Luca Calderano) Date: Mon, 15 Sep 2003 12:55:15 +0200 Subject: R: caching the sql queries In-Reply-To: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> Message-ID: <002901c37b77$d8903540$410100a4@utente65> The Only way is using Com S.G.A S.p.A. Nucleo Sistemi Informativi Luca Calderano -----Messaggio originale----- Da: python-list-admin at python.org [mailto:python-list-admin at python.org]Per conto di JZ Inviato: lunedi 15 settembre 2003 12.49 A: python-list at python.org Oggetto: caching the sql queries Is there any equivalent of caching sql queries for Python like ADOdb for PHP? (For those who did not hear about ADODb and its feature : http://phplens.com/adodb/caching.of.recordsets.html) -- JZ -- http://mail.python.org/mailman/listinfo/python-list From s.keim at laposte.net Thu Sep 25 03:47:06 2003 From: s.keim at laposte.net (sebastien) Date: 25 Sep 2003 00:47:06 -0700 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> Message-ID: <7da8d8f8.0309242347.48c2f31e@posting.google.com> The PEP has the following sentence in the rejected alternatives: > * Add a builtin function, reverse() which calls a magic method, __riter__. > I see this as more overhead for no additional benefit. I believe that this is the better choice because it is the way forward iteration work in python: you have the iter() function which call a __iter__ special method. So, I'd expect to have a riter() function which would call the __riter__ special method. I like riter as name to all other alternative because (iter, riter) looks really like (find, rfind) or (index, rindex) .... And I still think you don't need it often enough to put it in the builtin namespace, so the function should go in the itertools module. From rh4170056 at juno.com Tue Sep 23 05:37:52 2003 From: rh4170056 at juno.com (rhmd) Date: 23 Sep 2003 02:37:52 -0700 Subject: Help me choose a C++ compiler to work with Python References: <616fccba.0309210907.1e35b92d@posting.google.com> <3dd5593c.0309211615.747ba123@posting.google.com> <3F6E4D02.7868D52C@easystreet.com> Message-ID: <616fccba.0309230137.586ddea5@posting.google.com> Thanks to all who have responded. Your information was very helpful, I'm very impressed with the quality and thoughtfulness of the responses. Below find brief excerpts of some of the responses (which I hope will be useful for others who search for info on this topic), followed by more detail on my question. BEGIN EXCERPTS Have you considered and investigated Numeric Python or similar products? Look at the enthought Python installation (one is available for each of 2.2 and 2.3) -- they not only install a slew of the packages you might need for calculation heavy Python use, but (to support weave, I believe), they also include a mingw32 compiler (minimal gnu win32) which you can use for C++. If you get to the point where you are optimization-bound on your compiler (which you should determine by measuring, not intuiting), you could do worse than the Intel compiler. I suggest you look at various Python libraries to do whatever numerical processing you might need to do. They are mostly written in C anyway so their performance is excellent. For instance, I use SciPy for Fourier analysis and PIL for image processing, getting good performance on these numerically intensive tasks without ever leaving the ease and comfort of good old Python....The .NET compiler has a very good debugger and much better standard compliance than the old 6.0 compiler, but I haven't used lot of different recent vintage C++ compilers...I generally use COM objects written in Python to connect to Excel. I am very pleased with that technique. Koenig & Moo's book (Accelerated C++) is the best I've seen for [learning C++ for a few applications]..Python work with MSVC is much less of a pain for most things than gcc (aka mingw). Writing everything in Python then porting the 'hot spots' is often the best strategy. Use the profiler. Also (apart from Numeric / numarray), remember (or discover) Pyrex and psyco. Probably Pyrex is more useful to you than psyco. Don't apply either to your whole program. Just pick the bottlenecks. If you insist on using C++, make sure to look at Boost.Python(including pyste). gcc ... If you don't mind that it takes forever to compile C++ source code, until version 3.4 is released (it will support pre-compiled header). It is equally trivial to connect Python to Delphi using ctypes. Delphi can easily make a DLL that looks to the outside world like C. I have found Delphi to be maybe a little bit slower than MS C, but a little faster than gcc. They are all pretty close on speed, so you can't really pick a winner a priori. If you are doing VBA now, can't you buy the entry-level version of VB for around 100 bucks and create C-callable DLL's? END EXCERPTS MORE DETAIL ON MY QUESTION VB.NET was another option I considered, have heard it produces binary that runs "almost" as fast as that produced by C++, but am not sure if that is true. VB would be very convenient for me, but can it produce DLLs that Python can use? The reason I was considering using Python/C++ combination is that I use Python already (as scripting language for the Blender animation program) and thought I could also use it with Excel to overcome certain Excel limitations, such as Excel's ridiculous limitations on chart markers (i.e., could make better charts with Python-- this would not be a time bottleneck so Python's slowness is not an issue there), etc. I also thought that, despite Python's reputation for being a bit slow, it would at least be faster than Excel VBA interpreter, but this may not be the case. At any rate, there are some calculations where I need a LOT of speed, e.g. generating billions (with a B) of random numbers with the Mersenne Twister algorithm (which is available in C++), for statistical problems (mulitple undefined boundary conditions which can only be extracted with a Monte Carlo method). For this, even doubling or quadrupling Python binary's speed would not be enough. From newsgroups at jhrothjr.com Thu Sep 25 12:02:55 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 25 Sep 2003 12:02:55 -0400 Subject: "for" with "else"? References: Message-ID: "Mark Jackson" wrote in message news:bkv2je$5fs$1 at news.wrc.xerox.com... > "John Roth" writes: > > > > "Mark Jackson" wrote in message > > news:bkuru4$532$1 at news.wrc.xerox.com... > > > Invalid User writes: > > > > > (This happens to be the *reverse* of what my intuition expects - it > > > would seem more natural if the syntax meant "do this for loop to > > > completion, else do this extra stuff," but this is the way it is and > > > one must simply remember it.) > > > > There's a certain amount of justification, though. You can > > already put whatever amount of logic you need in the if > > statement that ends with the break. You don't otherwise > > have that ability for normal termination of the sequence. > > Sure - I wasn't arguing the other meaning was needed, clearly it is > not. It's the use of the keyword "else" which creates the [purely > mental] problem for me. Good point. John Roth > > -- > Mark Jackson - http://www.alumni.caltech.edu/~mjackson > There are no foolish questions and no man becomes a fool > until he has stopped asking questions. > - Charles P. Steinmetz > > From JoeyTaj at netzero.com Wed Sep 3 13:50:15 2003 From: JoeyTaj at netzero.com (Paradox) Date: 3 Sep 2003 10:50:15 -0700 Subject: **kwds behavior? References: <924a9f9c.0309020652.212c54eb@posting.google.com> Message-ID: <924a9f9c.0309030950.73fe8118@posting.google.com> Thanks for the replies. basically what I was trying to accomplish was to be able to load a script text file with python syntax into a class and have it be able to cleanly reference the properties and methods. I have currently accomplished it with something like this code = compile(scriptText, '','exec') exec code in self.__dict__ From newsgroups at jhrothjr.com Fri Sep 5 13:39:31 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 13:39:31 -0400 Subject: Automated code generation References: <3f58ba15$0$97267$edfadb0f@dread12.news.tele.dk> Message-ID: "Max M" wrote in message news:3f58ba15$0$97267$edfadb0f at dread12.news.tele.dk... > Yesterday there was an article on Slashdot: > http://books.slashdot.org/article.pl?sid=03/09/04/1415210&mode=flat&tid=108&tid=126&tid=156 > > It is about automatic code generation. > > I got interrested in the subject, did a web search, and it seems kind of > powerfull. > > My main interrest is web development in Zope/CMF/Plone, where there is a > lot of repeated code in the products. So automated code generation seems > like a natural fit. > > But every time I think of a use case, I immediately think of a way to do > it with encapsulation instead. > > Does anybody have any experience using Python and automated code > generation where it actually make sense? > > Or os it useless in a language as dynamic as Python? There are a few places where automated code generation makes sense, but these are mostly trivial time savers. For example, the propery() function could be extended to automatically generate trivial getters, setters and deleters, saving some coding and making things clearer in the majority of cases. John Roth > > > regards max M > From adalke at mindspring.com Tue Sep 30 02:18:34 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 30 Sep 2003 06:18:34 GMT Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> <3f7918e1-cebe25d5-ba02-4762-ae3e-ad3bb70874cb@news.szn.dk> Message-ID: <_e9eb.9852$NX3.7090@newsread3.news.pas.earthlink.net> Lulu of the Lotus Eaters: > > So I only expect around 5,428,681 primes less than 10^8 to occur. > > Well, that's not SO much less than 7.8M. Klaus Alexander Seistrup > I found 5,761,455 primes < 1E8. http://www.utm.edu/research/primes/howmany.shtml has the same number. (found by googling for "5,761,455" - 3rd hit. :) That's using Proof by Consensus, http://www.isip.msstate.edu/about_us/misc/humor/proofs/ Andrew dalke at dalkescientific.com From cnetzer at sonic.net Sun Sep 7 05:39:12 2003 From: cnetzer at sonic.net (Chad Netzer) Date: Sun, 07 Sep 2003 02:39:12 -0700 Subject: OT: best book in years In-Reply-To: References: <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <3F5868BA.85F506B4@engcorp.com> <87oexyls54.fsf@pobox.com> Message-ID: <1062927552.1856.35.camel@adsl-209.204.179.133.sonic.net> On Sun, 2003-09-07 at 01:06, Alex Martelli wrote: > Me, I'd recommend "Dawkins vs. Gould: Survival of the Fittest", > by Kim Sterelny. Thanks, I had just been wondering if there was a book on this subject, after a recent discussion about this topic with my girlfriend. > Gould is a great writer, even though in his later works he often gives in to > unstructured rambling (I can of course well sympathize with THAT > temptation:-) -- Dawkins, IMHO, isn't, even though in "The selfish gene" he > does manage (by a mix of his powerful ideas and his dry direct prose) to > be truly riveting. Agreed about Dawkins. I read "The Selfish Gene" while travelling, and found it fascinating, but even I (uninformed as I am in this area) thought the ideas presented (and often originated) by Dawkins needed deeper presentation, or a richer justification. A good presenter, but not a great one. Still, a great starting book, with fascinating ideas if you've never progressed beyond the basic teachings of genetics, and an important piece of work. I haven't yet read Gould, though. I've heard him in interviews enough to not yet try to read his books. He seems to have a "deeper" (for lack of a better word) presentation style than Dawkins (ie. less intuitive at first, but perhaps ultimately more satisfying). I didn't quite feel prepared for him in the past, and should now try. Probably I'm doing them both an injustice with these characterizations. > If you do want to see (essentially) Dawkins' ideas > presented by a truly great writer, try Matt Ridley -- "Genome", "Origins of > Virtue", "Red Queen", all superb writing (haven't read "Nature via Nurture" > yet -- I'll wait for the paperback). Yes! I heard him talk about "Nature via Nuture", and immediately ordered all his books. I haven't gotten to "Nature via Nurture" yet, but the others have been fascinating reading (I'm proceeding from oldest to newest). I'm also reading "Guns, Germs, and Steel" by Jared Diamond. It is fantastic, and a great companion to any of the above. A very ambitious work (the history of pre-modern humankind), with some powerful questions raised and tackled. There are many reviews on the web, so I'll just leave it at that. -- Chad Netzer From skip at pobox.com Wed Sep 17 13:41:37 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Sep 2003 12:41:37 -0500 Subject: fast way to filter a set? In-Reply-To: <20030917164148.12135.qmail@web16903.mail.tpe.yahoo.com> References: <16232.35495.501167.780179@montanaro.dyndns.org> <20030917164148.12135.qmail@web16903.mail.tpe.yahoo.com> Message-ID: <16232.40145.813183.441676@montanaro.dyndns.org> fortepianissimo> But this created two lists (keys and dummy)? Compared fortepianissimo> to the filter() method, which created a list and a new fortepianissimo> set, maybe your suggestion is still a bit faster... You asked for alternatives. I offered one. I'll let you do the performance testing. ;-) Skip fortepianissimo> --- Skip Montanaro wrote: >> fortepianissimo> I know I can do things like fortepianissimo> s=Set(range(1,11)) fortepianissimo> s=Set(filter(lambda x:x%2==0,s)) >> fortepianissimo> But this seems a bit slow since filter returns a >> list fortepianissimo> which then must be converted back to a set. Any >> tips? >> >> The only thing which comes to mind is: >> >> >>> s = sets.Set(range(1,11)) >> >>> s >> Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) >> >>> keys = list(s) >> >>> dummy = [s.discard(x) for x in keys if x%2] >> >>> s >> Set([2, 4, 6, 8, 10]) >> >> You still create a list, but don't create a second set. >> >> Skip fortepianissimo> __________________________________ fortepianissimo> Do you Yahoo!? fortepianissimo> Yahoo! SiteBuilder - Free, easy-to-use web site design software fortepianissimo> http://sitebuilder.yahoo.com From bgudorf at neurokode.com Tue Sep 23 18:45:41 2003 From: bgudorf at neurokode.com (Bryan J Gudorf) Date: Tue, 23 Sep 2003 18:45:41 -0400 Subject: Python Database Objects (PDO) 1.0.1 Released Message-ID: We at NeuroKode Labs, LLC, are proud to announce the release of Python Database Objects (PDO) 1.0.1. The current release adds support for PostgreSQL via the pgdb Module. As released previously: Python Database Objects (PDO) provides an easy to use Object Oriented API for database developers. PDO utilizes DB-API modules for database access, but allows for a Common Object Oriented API across RDBMS. Thus, PDO can be thought of as a 'wrapper' around the DB-API and database specific modules. PDO offers a unique interface which includes such features as column access by name, forward and backward movement through a result set and much, much more. Downloads for Python Database Objects are available on SourceForge.Net or for more information please visit http://pdo.neurokode.com. ~Bryan J Gudorf NeuroKode Labs, LLC From aleax at aleax.it Sat Sep 27 11:46:48 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Sep 2003 15:46:48 GMT Subject: Now that rexec is gone... References: Message-ID: Rainer Deyke wrote: > Now that rexec is gone, is there any code or information available on > executing Python in a restricted environment? And before I roll my own > solution, exactly where the security holes in rexec anyway? > > (I know one way of getting a restricted environment: butcher the Python > interpreter by removing everything that's even remotely dangerous, use > Python only for restricted execution, and do everything else in a C++ > program that embeds the butchered Python interpreter. I'd like to avoid > doing that, for obvious reasons.) Actually, such a "butchered" Python interpreter might be a fun and useful project indeed. You would have to add programmable limits on resource consumptions -- e.g., memory allocatable by the script[s], time (CPU or maybe elapsed) usable thereby, etc. And you should rename everything, say to use Qy instead of Py, so that a normal and a butchered interpreter could easily be embedded in the same program. Once the hard work of "butchering" is done, you might in fact quite easily expose "the butchered interpreter" via an extension module for Python proper -- no need to do "everything in C++", you'd just have two separate Pythons, a full-function one and a seriously-hobbled one. Not *QUITE* as good as running untrusted code in a separate "jail"'d process, perhaps, but probably the closest you can come to that on such environments as Windows. Note that the need to add resource limitations is crucial (and was never addressed by rexec, making it pretty useless to ward against denial-of-service kinds of attacks!). Alex From gerrit at nl.linux.org Tue Sep 23 11:45:36 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 23 Sep 2003 17:45:36 +0200 Subject: Try/except vs. if/else In-Reply-To: <3F706279.9000203@bu.edu> References: <3F70598E.8020500@bu.edu> <3F706279.9000203@bu.edu> Message-ID: <20030923154536.GA4166@nl.linux.org> Shu-Hsien Sheu wrote: > In my understanding, using try/except rather than if/else is more > pythonic. However, sometimes it is difficult to use the later. > For example, I want to search for a sub string in a list composed of > strings. It is considered "possitive" if there is a match, no matter how > many. > > my_test = ['something', 'others', 'still others'] > > case 1: try/except > > hit = 0 > for i in my_test: > try: > i.index('some') > hit = 1 > except ValueError: > pass > case 2: if/else > > hit = 0 > for i in my_test: > if 'some' in i: > hit = 1 Much faster would be: def check(): for elem in my_test: if 'some' in elem: return True ...this way, it immediatly stops checking all following values once it finds a single match. > It seems to me that in a simple searching/matching, using if might be > better and the code is smaller. Try/except would have its strengh on > catching multiple errorrs. Agreed. > However, problems occur if the criteria is > composed of "or" rather than "and". For instance: > > if (a in b) or (c in b): > *do something > > try: > b.index(a) > b.index(c) > *do something > except ValueError: > pass > > The above two are very different. It would be more similar to use 'if (a in b) and (c in b)', because that is what the try/except block does. If so, I think it has the same effect. I would absolutely prefer the former, because I don't like function calls who neither change an object whose return value is thrown away. regards, Gerrit. -- 243. As rent of herd cattle he shall pay three gur of corn to the owner. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From peter at designtheory.org Wed Sep 3 12:55:18 2003 From: peter at designtheory.org (Peter Dobcsanyi) Date: 3 Sep 2003 16:55:18 GMT Subject: ANN: An XML format for block designs Message-ID: A standard format for block designs and their properties ======================================================== (A proposal and an invitation for public debate) At DesignTheory.org we are developing a web-based Design Theory Resource Server for combinatorial and statistical design theory. These resources will include an online database of designs, an Encyclopaedia of Design Theory, and software packages for the generation and analysis of designs. We hope to address the needs of both researchers and practitioners of design theory. One critical element is our XML format to represent designs and their properties in a standard platform-independent manner. This will allow for the straightforward exchange of designs and their properties between various computer systems, including databases and web servers, and combinatorial, group theoretical and statistical packages. The XML format will also be used for outside submissions to our design database and to store designs in perpetuity. Our initial development is in the area of block designs, and we invite you to read and comment on our proposal for the External Representation of Block Designs, available online at: http://designtheory.org/ Please send your comments (and follow-ups) exclusively to: developers at designtheory.org This is a mailing list to which you are welcome, although not required, to join. Alternatively, you can follow the discussions through the public archives of the list. For further details, please visit: http://designtheory.org/mailing.html We will finalize the XML format for block designs after sufficient public debate, after which we shall release GAP [1], R [2], and Python [3] software for block designs. We are committed to the open source model and all products of our development will be released to the public free of charge. We shall also start developing a database of block designs, and look forward to your contributions (in the XML format) to this database. Please feel free to forward this announcement to anyone you think may be interested. References: [1] GAP - Groups, Algorithms and Programming http://www.gap-system.org/ [2] The R Project for Statistical Computing http://www.r-project.org/ [3] The Python programming language http://www.python.org/ From skip at pobox.com Wed Sep 10 12:52:36 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 10 Sep 2003 11:52:36 -0500 Subject: problem with tabnanny In-Reply-To: <1063210194.3f5f4cd29c11c@mail.dei.unipd.it> References: <1063210194.3f5f4cd29c11c@mail.dei.unipd.it> Message-ID: <16223.22228.720552.597770@montanaro.dyndns.org> Pier> #---------8<---- test.py ------------- Pier> if 1: Pier> print "error" Pier> #---------8<------ end test.py ------- Pier> $ python /usr/lib/python2.2/tabnanny.py -v test.py Pier> '/home/pier/test.py': Clean bill of health. Pier> for tabnanny it's correct!? Tabnanny doesn't try to find indentation syntax errors in your code. It identifies indentation which mixes spaces and tabs in such a way that the file might not execute properly because of differing interpretations about how a TAB indents. In your case there's no ambiguity because there is no leading whitespace at all. Skip From tjreedy at udel.edu Sun Sep 28 02:29:06 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2003 02:29:06 -0400 Subject: Meta programming question References: Message-ID: "Bruce Dickey" wrote in message news:vnce64dgqj047c at corp.supernews.com... > I've read a number of the meta progamming articles. I have not found > what I am looking for. I want to override assignments to variables which > are in the module namespace (not object members -- no classes involved). > Can this be done? Yes -- by rewriting the appropriate section of the source code. Since it is clearly written, open source, and freely recompilable, this is doable by a competant and motivated C programmer. But given how intertwined current assignment semantics are with the rest of the language, I have trouble imaging an alternative that would make sense. Terry J. Reedy From Stephen.Boulet at no.spam.motorola.com Wed Sep 3 11:49:32 2003 From: Stephen.Boulet at no.spam.motorola.com (Stephen Boulet) Date: Wed, 03 Sep 2003 10:49:32 -0500 Subject: Trouble with script fetching site In-Reply-To: <873cfe6je4.fsf@pobox.com> References: <3Zadnamljsa-dMiiXTWc-w@speakeasy.net> <3F55ECD2.48F0BB0B@engcorp.com> <873cfe6je4.fsf@pobox.com> Message-ID: You guys are probably right. If you have a hammer ... John J. Lee wrote: > Peter Hansen writes: > > >>Stephen Boulet wrote: >> >>>I'm trying to parse a url to set my hardware & system clock (linux). >> >>I can't help with the problem at hand, but I also don't see the >>reason to do it. Why not just access an NTP server and grab the >>time the "proper" way? Using a web page is a roundabout way of >>doing it. > > > Right. > > >>There's a nice setclock.py script which Google can >>point you to which does the job much more easily. > > > On my system, the ntpdate command works nicely. I run it my PPP > scripts. > > > John From newsgroups at jhrothjr.com Wed Sep 24 06:29:15 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 24 Sep 2003 06:29:15 -0400 Subject: Pre-PEP: reverse iteration methods References: Message-ID: "Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:f4b2nv8vs81v6egonckq7935jmh6a8gku6 at 4ax.com... > On Wed, 24 Sep 2003 00:30:31 GMT, "Raymond Hettinger" > wrote: > > >Proposal > >======== > > > > >* Should file objects be included? Implementing reverse iteration may not > > be easy though it would be useful on occasion. > > IMO no - doing this essentially needs the whole file to be read into > memory, in which case you may as well read the whole file into a list > and then iterate the list backwards. Actually, it doesn't. It does require that the file be read into the buffers backwards, but from there it's simply a matter of doing a reverse scan for the line ending characters. The difficulty is that the entire algorithm would have to be done in C, without any significant help from the standard library. John Roth > > > > -- > Steve Horne > > steve at ninereeds dot fsnet dot co dot uk From jhefferon at smcvt.edu Sun Sep 21 11:19:18 2003 From: jhefferon at smcvt.edu (Jim Hefferon) Date: 21 Sep 2003 08:19:18 -0700 Subject: Has psycopg moved? Message-ID: <545cb8c2.0309210719.2a1c554c@posting.google.com> Hello, I want to try psycopg, the module for Postgres access. I'm having trouble reaching the site for four or five days now. For example, the link on the Python web site's DB Modules page http://initd.org/Software/psycopg times out, as do some other links that Google gives me. Am I looking in the wrong place, or is it just that the site is experiencing some difficulties? Thanks, Jim From stefan.fleiter at web.de Wed Sep 3 05:50:41 2003 From: stefan.fleiter at web.de (Stefan Fleiter) Date: Wed, 03 Sep 2003 11:50:41 +0200 Subject: Difference of hash and __hash__() In-Reply-To: References: <338366A6D2E2CA4C9DAEAE652E12A1DEAD454A@au3010avexu1.global.avaya.com> Message-ID: Hi, Jeff Epler wrote: > No, it's apparently deliberate that slices don't hash (so that > {}[1:2] raises an error). I think that slice(None).__hash__ is from > object.__hash__, but this is rightfully(?) ignored by PyObject_Hash() > which looks at tp_hash (NULL for slice objects) and tp_compare (non-NULL > for slice objects) with the result that the object is treated as > unhashable. So, should I write a bugreport or not? Are you sure it is "rightfully ignored" or not? Somewhat puzzled, Stefan From ulysses_dm at yahoo.com.cn Wed Sep 17 20:33:48 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 17 Sep 2003 17:33:48 -0700 Subject: PyQt: Can't show PY variable in QT filedialog as initially parameter References: <43e3984e.0309110814.7d759662@posting.google.com> Message-ID: <43e3984e.0309171633.c8ae3e5@posting.google.com> Phil Thompson wrote in message news:... > On Thursday 11 September 2003 5:14 pm, ulysses wrote: > > Hi, > > > > I use PyQt 3.8 non-commercial version in win32. I get a big question. > > I Can't show PY variable in QT filedialog as initially parameter. > > > > Code sample is following: > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > fileName="test.avi" > > > > def saveSomething(aString): > > dl = QFileDialog.getSaveFileName(aString, "*.*", self, "FileDialog") > > or > > dl = QFileDialog.getSaveFileName(QString(aString), "*.*", > > self, "FileDialog") > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > these code can't show corrent string. > > > > If I use string constant. > > dl = QFileDialog.getSaveFileName("test.avi", "*.*", self, "FileDialog") > > > > Dialog show it correctly. > > > > Thanks. > > > > Ulysses > > Have you got a complete (but small) example that demonstrate's the problem? > > Phil Above code is a example. I do a little application for free. main form will arrive 1XXX line. So I can't post it all. BTW: I can't show getExistingDirectory Dialog in a python thread. it's will halt whole program. From spatel at landrum-brown.com Fri Sep 12 16:53:13 2003 From: spatel at landrum-brown.com (Samir Patel) Date: Fri, 12 Sep 2003 15:53:13 -0500 Subject: Simples examples for standard libraries Message-ID: <200309121553.13096.spatel@landrum-brown.com> Python comes with huge number of build in libraries. Best way to start python is to understand this libraries and what it provides by running simple examples for each libraries. Does anybody know if this is done by anybody? If not, is test modules are best way to accomplish this? I am interested in doing something like this in wxPython. My concept is something like demo example of wxpython where you have tree structure containing different libraries and inside contains different examples. Please post your suggestions. From SPAMtbone at freegates.be Mon Sep 22 17:40:24 2003 From: SPAMtbone at freegates.be (Philip) Date: Mon, 22 Sep 2003 23:40:24 +0200 Subject: DB2 driver for windows References: <3f6cc89b$0$1122$6c56d894@feed0.news.be.easynet.net> Message-ID: <3f6f6c4c$0$1115$6c56d894@feed0.news.be.easynet.net> Dave Benjamin wrote: > In article <3f6cc89b$0$1122$6c56d894 at feed0.news.be.easynet.net>, Philip > wrote: >> i'am looking for a db2 driver for windows >> the DB2 servers runs on as400 if that makes any difference. > > I don't know if you're looking for a native driver, but if you can work > with ODBC, I was able to get DB2's ODBC driver (the one that comes with > the DB2 client installation) to talk to the mx.ODBC module. > > http://www.egenix.com/files/python/mxODBC.html > Currently i'am using jython for database administration (because didn't find an native driver) I like the java jdbc driver because you don't need to install anything especialy interesting when sharing code) But the downside is that you have the java tiresome api. the obvious reason way i have choicen python/jython. Well, prefer a native one but if it's easy to install the odbc driver that would be fine too. Thanks, Philip From alkirke1 at comcast.net Thu Sep 11 01:23:08 2003 From: alkirke1 at comcast.net (Al Kirke) Date: Wed, 10 Sep 2003 22:23:08 -0700 Subject: OT: Americans love their guns References: <16223.15950.299463.959577@montanaro.dyndns.org> Message-ID: <000b01c37824$c972de10$3a0ff10c@teaset> ----- Original Message ----- From: "Skip Montanaro" Newsgroups: comp.lang.python To: "Al Kirke" Cc: Sent: Wednesday, September 10, 2003 8:07 AM Subject: Re: OT: Americans love their guns > > >> Counter-test: Imagine your seven-year-old son finding your gun and > >> shooting and killing your five-year-old daughter while you're working > >> in your study. > > Al> Impossible. The son had been taught safe gun handling on the pistol > Al> range w/ a .22 starting at aged five, and would come and tell you > Al> that firearm had not been safely stored. > > This sort of thing still happens (it hits the news whenever such a shooting > occurs), You're correct in that this sort of thing hits the news. What doesn't hit the news are the instances when handguns are used for personal defense. John Lott wrote a whole book about liberal news bias aganst those instances. http://www.wmsa.net/people/john_lott/030822_bias_star.htm > so clearly all seven-year-olds who live in houses with guns are not > being trained to handle and respect firearms. MY children were taught to handle firearms safely beginning age 5. Are yours? My son got his mini-size .22 bolt-action atage 9. The son and one daughter expect to apply for a Texas CHL when they reach their twenty first birthdays. But the biggest difference that household firearms make in society is in the hot burglary statistics. A "hot" burglary is one that occurs when the family is home. . In England more than half of the burglaries are "hot". In the U.S. that statistic is about 13 percent. The U.S. burglars tell that they go to great pains to avoid householders, not because the police will be summoned, but because of the risk of getting shot. English buglars don't care much whether you're home or not. http://www.newsmax.com/articles/?a=2000/1/17/105209 A current judicial move concerns the 2nd Amendment. 5th Circuit in New Orleans says its an individual right to keep and bear arms, 9th Circuit in San Francisco (where else?) says the right belongs to the national guard. This conflict will reach the SCOTUS in the next year or so. Cheers, Al From duncan at NOSPAMrcp.co.uk Wed Sep 10 04:13:39 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 10 Sep 2003 08:13:39 +0000 (UTC) Subject: super confused References: <63qrlv8p4sqt7mossa6kimfloa0au416f5@4ax.com> Message-ID: Daniel Klein wrote in news:63qrlv8p4sqt7mossa6kimfloa0au416f5 at 4ax.com: > In Smalltalk, a message send to 'super' simply means to send a message > to self but start looking in the superclass first for the method. I > realize Smalltalk is a single-inheritance language, but doesn't > explain why, in Python, you need to specify the class name as a > parameter. The problem is that super needs two classes to operate. It has to know the type of the object (which is why you pass it 'self'), but it also has to know where to start in the inheritance hierarchy. If super was a keyword with some magic properties, then it might be able to pick up the correct class automatically, but its actually just a boring ordinary function, so you have to tell it. > > As an aside, you will notice in the 'append' method, there are two > ways to do the same thing, and either way could be used in the other > methods as well. Which brings up my second question: Is one way more > correct/efficient/better/pick your adjective? I'm very inclined to use > the 'super' method cos that means I won't have to worry about changing > things in the future. > Actually these do slightly different things: > class ValidatedList(list): > ... > def append(self, objekt): > _validate(objekt) > # list.append(self, objekt) > super(ValidatedList,self).append(objekt) If you were to subclass ValidatedList, and the subclass also inherits from another subclass of list, then the call through super might not call list.append directly. class List2(list): def append(self, objekt): return super(List2, self).append(objekt) class Painful(ValidatedList, List2): pass ouch = Painful() ouch.append('oops') Calling ouch.append invokes ValidatedList.append which passes the call up to List2.append, which then calls list.append. If ValidatedList.append called list.append directly then a call to ouch.append would never pass through List2.append. So when to use super, and when to call the base class directly? If you don't expect diamond inheritance hierarchies, and you aren't writing a general purpose library for other people, then I would probably want to invoke the base class directly. It's faster (if you care), but also clearer to read. If those conditions don't hold, then use super. Either way use plenty of unit tests so that if at some time your assumptions no longer apply you'll find out about it quickly. -- 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 Fri Sep 19 15:41:55 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 19 Sep 2003 12:41:55 -0700 Subject: How do I learn operator overriding? References: Message-ID: <3F6B5C03.77D5E947@alcyone.com> python at sarcastic-horse.com wrote: > The only problem is that I have no idea how to override operators in > python. Can anyone give me a few trivial examples of how it is done? Just override the __sub__ method: >>> class Date: ... def __init__(self, year, quarter): ... self.year = year ... self.quarter = quarter ... def quarters(self): ... return self.year*4 + self.quarter ... def __sub__(self, other): ... return self.quarters() - other.quarters() ... >>> Date >>> q1 = Date(2001, 1) >>> q4 = Date(2001, 4) >>> q4 - q1 3 > And, on a completely unrelated note, I am getting a truly amazing > amount > of spam today. Anyone else? Yep. I've gotten 262 MB since 2 am this morning. Another worm is out and about, I'd presume. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You and I / We've seen it all / Chasing our hearts' desire \__/ The Russian and Florence, _Chess_ From bokr at oz.net Mon Sep 8 18:40:26 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Sep 2003 22:40:26 GMT Subject: win32com: create email message in windows default app? References: Message-ID: On Mon, 8 Sep 2003 13:51:28 +0200, Harald Massa wrote: >>run the >>default email application, create a new message, and let me populate it >>with subject, body, and attachments? > >if you do not need attachements... > > >import webbrwoser > >webbrowser.open("mailto:guido at python.org?subject=PyPy and >stacklass&body=please support theses projects") > > That seems to work nicely under NT4 with Python2.3 and Eudora. And it doesn't send the email (a Good Thing IMO), so it should be possible to continue in Eudora with more text etc., and attach something if desired. Regards, Bengt Richter From tjreedy at udel.edu Fri Sep 12 12:06:29 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Sep 2003 12:06:29 -0400 Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> Message-ID: "Ubaidullah Nubar" wrote in message news:17d520f6.0309120509.491e4d7c at posting.google.com... > Hi, > > How well is Python suited for developing database based applications? > I am new to Python so please bear with me if some of the questions are > too simple. I specifically have the following questions: > > 1. Is there an example of a simple data-entry application written in > Python using a GUI interface? Something like a simple address book app > with a listbox displaying all addresses with the ability to > add/modify/delete. I hope someone else answers this. > 2. There seem to be a number of GUI frameworks available? Which one is > good for use on Windows and Linux? Most people prefer the one they use. No surprise. Use google to find previous threads on this topic. > 3. Can Python apps be compiled to an exe? No, Python code cannot currently be compiled to a native code .exe in the way you probably mean. Yes, Python bytecode (including included modules) can be combined with a copy of the interpreter in a distributable .exe, Googling 'Python executable' perhaps with 'McMillan' (spelling?) should get you previous posts with links. > Can the resulting executable be distributed commercially? Yes. > 4. What types of applications are not suitable to be written in Python? Hmmm. Terry J. Reedy From querdenker69 at mtsi.de Mon Sep 1 17:03:09 2003 From: querdenker69 at mtsi.de (querdenker69) Date: Mon, 01 Sep 2003 23:03:09 +0200 Subject: IIS 6.0/Python problem In-Reply-To: <51bb029f.0308280110.7fa1709b@posting.google.com> References: <51bb029f.0308280110.7fa1709b@posting.google.com> Message-ID: Chung Jiho wrote: > Hello, > > We have been deploying our web application over win2k servers. It is > written in Python and uses Active Scripting to meet our requirements > that it must be ASP application. So far, it was O.K. > > But recently we discovered our application doesn't work on Windows > 2003 server. Even simple page such as below results in 500 Server > Error. > > <%@Language="Python"%> > <% > Response.Write("Hello, world?") > %> > > Have any of you experienced similiar problem in Windows 2003 > server/IIS 6.0 settings? VBScript and JScript ASPs are working well. I > already allowed ASP scripting and checked "use parent path" on > configuration dialog box. > > Here's my IIS log. ASP_0147 error number is too generic to give us any > hint and the page above is not doing any real work. Python version is > 2.3 and win32all version is 155 (both are latest.) > > 165.246.66.32, -, 8/26/2003, 16:57:33, W3SVC1, MULTI-SRV, > 165.246.66.32, 15, 362, 368, 301, 0, GET, /drlistening, -, > 165.246.66.32, -, 8/26/2003, 16:57:33, W3SVC1, MULTI-SRV, > 165.246.66.32, 0, 363, 198, 500, 0, GET, /drlistening/Default.asp, > |-|ASP_0147|500_Server_Error, > 165.246.66.32, -, 8/26/2003, 16:58:12, W3SVC1, MULTI-SRV, > 165.246.66.32, 0, 362, 368, 301, 0, GET, /drlistening, -, > 165.246.66.32, -, 8/26/2003, 16:58:12, W3SVC1, MULTI-SRV, > 165.246.66.32, 0, 363, 198, 500, 0, GET, /drlistening/Default.asp, > |-|ASP_0147|500_Server_Error, > 165.246.66.32, -, 8/26/2003, 16:58:12, W3SVC1, MULTI-SRV, > 165.246.66.32, 0, 362, 368, 301, 0, GET, /drlistening, -, > 165.246.66.32, -, 8/26/2003, 16:58:12, W3SVC1, MULTI-SRV, > 165.246.66.32, 15, 363, 198, 500, 0, GET, /drlistening/Default.asp, > |-|ASP_0147|500_Server_Error, > > TIA digging in the deep i remember something like: IIS only supports .Net-technologies I'd read an chat-script on the msdn-forum about the new features in IIS6 , where some of the guests hava asked for support like PHP and Python. And, as i remember, the answer was clearly: No, we won't support 3rd-Part-Libraries (at the moment). The only way th handle dynamic data is to use ASP.NET syl, Marcus From fritz at expires-200309.rodent.frell.eu.org Thu Sep 11 06:55:29 2003 From: fritz at expires-200309.rodent.frell.eu.org (Fritz Wuehler) Date: Thu, 11 Sep 2003 12:55:29 +0200 Subject: 1.5 vs. 2x - build problem Message-ID: <7af2fd5c1a70e3c6ce4fe1f8eee39b9b@remailer.frell.eu.org> I downloaded a tarball which doesn't compile. The error message says I need python 2x but all I have is 1.5. Can I fix the compatability problem and get it to work on 1.5? From mcherm at mcherm.com Tue Sep 9 08:05:56 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 9 Sep 2003 05:05:56 -0700 Subject: What does the keyword 'global' really mean Message-ID: <1063109156.3f5dc2245d452@mcherm.com> John Dean writes: > I have looked [...] for a full explanation of what > 'global' really means. Would I be > correct in assuming that any variable prefixed with the keyword global would > allow that variable to be accessible across translation units, in other > words global is equivalent to the 'C' keyword 'extern' ? It's a reasonable assumption, but no, that's not what global does in Python. In Python, a "global" variable is accessible throughout a single module (file), instead of throughout the entire program. It's normally just those things (variables, functions and classes) that are defined at the "top level" in the file. Of course, although these are only "global" in the module, they can still be accessed from other modules via import. For instance, "stdin" and "stdout" are two globals from the sys module, and if you use "import sys", you can later read from "sys.stdin". But if you were writing a function INSIDE the sys module, you could just use "stdin" anywhere... inside a function, a method, anywhere. That's why it's called "global". There is, however, one exception: you are allowed to shadow a variable by using another with the same name. Consider this code: # WARNING: Code not tested. Could have bugs. x = 7 # defines global variable def func_using_global(): print 'x = %i' % x # prints 7 # notice that there are now two globals: "x" and "func_using_global" def outer_func(): print 'start outer' def inner_func(): print 'x = %i' % x # ALSO prints 7 inner_func() y = 8 # now 3 globals, we added "outer_func". "y" and "inner_func" are # NOT global. def func_using_x_for_other_purposes(): x = 99 print 'x has been defined as %i' % x # prints 99 In the function "func_using_x_for_other_purposes", the name "x" is used for some other purpose, totally unrelated to the global variable of the same name. That's ALLOWED, which is nice, because it means you don't have to know about global variables you are writing a function (except for those that you plan to use). But what if you wanted to write a function that CHANGED the global x? Well, that's what the "global" statement is for. Python assumes that if you just USE a variable, without assigning to it, then it's the global variable of that name (if there is one!). But if you assign to it anywhere in the function, then it assumes you have a local variable that just happens to share the same name. If you really wanted to CHANGE the global variable, then you add a "global" statement, like this: def func_changing_global_x(): global x x = x + 1 # changes the global "x" > Also, does Python have the equivalent of the 'C' keyword 'static'? If you really mean 'C''s "static" (not C++, which re-used it for some wierd stuff), then the answer is "global"! Just create a global variable, and choose to use it only within a particular function, and BOOM! there you go... a "static" variable. Any thread safety issues (if your program uses threads) are your own responsibility (same as in C). Hope this helps! -- Michael Chermside From jdhunter at ace.bsd.uchicago.edu Thu Sep 11 16:32:09 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 11 Sep 2003 15:32:09 -0500 Subject: getting ttf font/family name; fontTools? Message-ID: I would like to extract the font and family name from a TTF file. I have been looking at fontTools ttLib, which parses the ttf file and provides lots of helpful information, but cannot find the name. >>> from fontTools import ttLib >>> tt = ttLib.TTFont("cour.ttf") tt['head'] seems like a good place to find it, but I can't. The data appear to be in the 'name' field >>> s = tt.getTableData('name') >>> s.find('Courier') 4197 But I still don't know how to extract this information if I don't know the family/font name in advace. Any ideas on how to best extract this info using fontTools or otherwise? What I am trying to do is find the best ttf font file for a given fontname, fontangle, and fontweight. I plan to write my own font finder given a font name and font family from the ttf file, but if there is a better way to find ttf fonts let me know. Eg, what I want to do is ttfile = findfont('Courier', 'Italic', 'Bold') and have findfont search some PATH containing TTF files and return the closest match, or a default if no good match is found. Thanks, John Hunter From jblazi at hotmail.com Sat Sep 20 06:51:39 2003 From: jblazi at hotmail.com (jblazi) Date: Sat, 20 Sep 2003 12:51:39 +0200 Subject: Problems with string and lists (searching and replaceing) Message-ID: I should like to search certain characters in a string and when they are found, I want to replace other characters in other strings that are at the same position (for a very simply mastermind game) for my pupils. This very simple thing does not seem simple at all. If I use strings, I cannot replace their parts (though I can use string.find for the searching). I think it is a bad idea that strings are not mutable, but I suspect that this has been discussed here for ages. I can use sequences instead, but then first I have to 'split' and 'join'. Additionally, there is no 'find' for sequences (who knows why not) and so I can choose between using 'index' that raises an exception (and we have not covered exceptions yet) or I can ask whether the character is in the string before using 'index' which is a bit artificial from the point of view of my pupils. (It is all right with me.) Do I oversee something? TIA, JB ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From eppstein at ics.uci.edu Fri Sep 26 12:18:18 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 26 Sep 2003 09:18:18 -0700 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> Message-ID: In article , "Sean Ross" wrote: > How about > > from itertools import ireverse > for i in ireverse(xrange(n)): > # suite > > ireverse(), like imap(), izip(), etc., suggests that the operation is > iterative, and that no modification of the original sequence will be > performed. Others have suggested riter() (right iteration), in order to form > an association with the iter() builtin. As a matter of taste, I prefer > ireverse(). ireverse, like imap(), izip(), etc., suggests that the operation happens without the memory overhead of copying the whole sequence into a list before reversing it. Do you have some plan for how to do that e.g. with simple generators? Or easy to understand explanation for which things can be ireversed and which can't? -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From lupan at zamek.gda.pl Thu Sep 18 17:18:40 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Thu, 18 Sep 2003 23:18:40 +0200 Subject: Python ISPs References: <924a9f9c.0309181224.374a5bef@posting.google.com> Message-ID: <877k45aj7z.fsf@psi.lupan.zamek.gda.pl> JoeyTaj at netzero.com (Paradox) writes: > Does anyone know of some ISPs that have Mod_Python installed. Most > seem to allow Python CGI but not things like Mod_Python or Spyce. Is > this a viable solution or should I just learn PHP. I would prefer to > leverage my Python knowledge but I also would like a fast robust > solution. > > Thanks Joey. I know only one commercial webside: http://www.python-hosting.com/, they have mod_python, Spyce and many more (Zope, Plone, Nuxeo CPS, Silva, Webware, Twisted, CherryPy, SkunkWeb, Quixote, 4Suite Server, Spyce, Albatross, Cheetah, mod_python, Straight CGI) for free testing of CherryPy consider http://www.freecherrypy.org/ newer used, just know it exist -- =*= Lukasz Pankowski =*= From gh at ghaering.de Tue Sep 30 11:22:01 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 30 Sep 2003 17:22:01 +0200 Subject: can i implement virtual functions in python ? In-Reply-To: References: Message-ID: <3F799F99.10105@ghaering.de> Prabu wrote: > Hi, > > I'm new to python, so excuse me if i'm asking something dumb. > Does python provide a mechanism to implement virtual functions? [...] What do you mean with "virtual function"? If you mean virtual methods in the C++ sense, all methods are "virtual" in Python. -- Gerhard From gafStopSpamData at ziplink.stopallspam.net Tue Sep 30 17:51:05 2003 From: gafStopSpamData at ziplink.stopallspam.net (G.A.) Date: Tue, 30 Sep 2003 21:51:05 GMT Subject: Running python from eclipse/pyeclipse Message-ID: <2hujnvk0a4lmv992v0rf2k91dicmg29nee@4ax.com> I've installed Eclipse 3.0 and the latest pyeclipse. I can get the editor run - at least I think so, because it seems to do reasonable syntax highlighting. However, I can't get the Python console window to appear (Unable to instantiate view: org.python.pyeclipse.views.ConsoleView), nor can I get python to run to completion. The MSWindows Task Manager shows that eclipse has successfully started python.exe (at least a process by that name shows up), but eclipse just shows 0% progress. Any suggestions, even if they're just on how to debug this? Thanks, Gary From tjreedy at udel.edu Tue Sep 2 12:04:05 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 2 Sep 2003 12:04:05 -0400 Subject: **kwds behavior? References: <924a9f9c.0309020652.212c54eb@posting.google.com> Message-ID: "Paradox" wrote in message news:924a9f9c.0309020652.212c54eb at posting.google.com... > Why does the following attempts to pass in keywords arguments not > work. What do you mean 'not work'. What was your output and what did you expect? >It would be alot cooler if there was a way to not have to have > the function defined with the variable name. I don't understand your meaning here. It really seems to me > that the 3rd function should work. Does anyone know how to accomplish > something like this. Again, what is 'this'? > def testKeywords1 (**kwds): > print x If you want posted code to be read with indents by everybody, use space instead of tab to indent. It's your choice to limit readership or not. > > def testKeywords2 (**kwds): > locals().update(kwds) Above line has same effect as 'pass' for reason John Roth quoted. > print x > > def testKeywords3 (**kwds): > locals().update(kwds) > def testNested(): > print x > testNested() > > dict = {} > dict['x'] = 5 > # doesn't work I usually expect 'doesn't work' to apply to the line above that I just read -- just as this response applies to the line quoted above. I suspect you meant 'below doesn't work', whatever 'doesn't work means. The alternative way to reverse the 'pointer' is to leave a space above and none below. > testKeywords1(**dict) > # doesn't work > testKeywords2(**dict) > # doesn't work > testKeywords3(**dict) If you don't get your question answered with above, try again with different words. Terry J. Reedy From martin at v.loewis.de Tue Sep 23 17:39:59 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 23 Sep 2003 23:39:59 +0200 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> <299f1138.0309230818.22bc9bf6@posting.google.com> Message-ID: jallan at smrtytrek.com (jallan) writes: > A: No. The UnicodeData.txt file includes all of the 1:1 case mappings, > but doesn't include 1:many mappings such as the one needed for > uppercasing ?. Since many parsers now expect this file to have at most > single characters in the case mapping fields, an additional file > (SpecialCasing.txt) was added to provide the 1:many mappings. For more > information, see UTR #21- Case Mappings [MD] > >> > > Python specifications make an implied claim of full support for > Unicode and an implied claim that the function upper() uppercases a > string properly. This is a contradiction: SpecialCasing contains 1:n mappings, whereas .upper() can only return a single result. So how do you think SpecialCasing should be considered in the implementation of .upper()? > Users should not have to know such details. They may wish to know > where a particular function does not do what might be expected of it. Things are more difficult than they appear to be. Regards, Martin From brian at sweetapp.com Thu Sep 25 18:19:00 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 25 Sep 2003 15:19:00 -0700 Subject: Another Python rookie trying to port to C/C++ question. In-Reply-To: Message-ID: <030d01c383b3$053e27d0$21795418@dell1700> > Well, since I'm not worried about "flexible", have my doubts about the > "much slower" part, Your implementation is O(n) with the number of entries while the Python implementation is O(log(n)). If n is small then your implementation might be acceptably fast. Can't you just use the STL hash_map template class? Cheers, Brian From hutsonken at ev1.net Mon Sep 22 21:38:01 2003 From: hutsonken at ev1.net (Kenneth Hutson) Date: Mon, 22 Sep 2003 20:38:01 -0500 Subject: Connect to VBA Objects? Message-ID: Hi, I wonder if Python can connect to the object models exposed by Excel or Word. Thanks in advance, Ken Hutson San Antonio, Texas From martin at v.loewis.de Sat Sep 27 06:09:41 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 27 Sep 2003 12:09:41 +0200 Subject: 64-bit EPIC and some modules References: Message-ID: Christos "TZOTZIOY" Georgiou writes: > The problem is that I am at a loss with the configure mechanism, and I > can't figure why audioop, imageop and _tkinter were not configured in > from the beginning (it's a linux system, after all; libraries and > includes are in the standard places, ie /usr/lib and /usr/include). I > am ATM browsing old posts in Google groups searching for pieces of a > 'python-configure-how-to', but any hints would be appreciated. _tkinter built fine for me, with Python 2.3.1, on a Debian/ia64 system. If it was not built for you, most likely, you forgot to install the header files. audioop and imageop are not build because of this code in setup.py: # Multimedia modules # These don't work for 64-bit platforms!!! # These represent audio samples or images as strings: # Disabled on 64-bit platforms if sys.maxint != 9223372036854775807L: # Operations on audio samples exts.append( Extension('audioop', ['audioop.c']) ) # Operations on images exts.append( Extension('imageop', ['imageop.c']) ) # Read SGI RGB image files (but coded portably) exts.append( Extension('rgbimg', ['rgbimgmodule.c']) ) Regards, Martin From martin at v.loewis.de Thu Sep 4 18:38:15 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 05 Sep 2003 00:38:15 +0200 Subject: Comparing objects - is there a maximum object? References: <7bdbb1a6.0309041124.6801b755@posting.google.com> <1SN5b.8786$tw6.4739@newsread4.news.pas.earthlink.net> Message-ID: "Andrew Dalke" writes: > Shouldn't there also be a > > def __rcmp__(self, other): > return -1 > ? No, this would not be used. cmp(a,b) == -cmp(b,a) Regards, Martin From holiver at ieee-occs.org Mon Sep 8 17:28:20 2003 From: holiver at ieee-occs.org (James F. Lu - Publicity Chair) Date: Mon, 8 Sep 2003 14:28:20 -0700 Subject: Upcoming Symposium - COSST Message-ID: <00a201c37650$20bc52e0$220110ac@FLUFFY> ======================================================= Coast Open Source Software Technology (COSST) Symposium by IEEE Computer Society - Orange County Chapter ======================================================= WHAT: Applying Open Source Web Technologies COSST Symposium WHEN: Saturday Oct. 18. 9am-6pm WHERE: Jazz Semiconductor auditorium, Conexant Systems Overview -------- Our technical focus will be on using LAMP and Java open-source technologies. The LAMP acronym is used to describe a typical open-source platform "stack" for web applications: * Linux operating system * Apache web server * MySQL/PostgreSQL databases * Perl/PHP/Python languages The symposium will open with foundation talks providing an overview of open-source software and Linux as an open-source web application platform. A series of application-tier talks will provide insight from the point of view of widely used web application development languages: Perl, PHP, Python, and Java. The final session will be an experience panel, which will provide an opportunity for experience reports from actual development projects to illustrate real-life problems and opportunities of OSS. Target Audience --------------- The target audience for the symposium is professional software engineers and technical management. The audience is expected to have a diverse background involving many operating systems and languages, with experience in software system development for a variety of industrial, military and commercial purposes. Attendees will include experienced professionals who have had little or no exposure with open-source software and are looking for a good introduction. Symposium Goals --------------- The goal of the symposium is to provide participants with a high-level, technically sophisticated overview of major open source software (OSS) technologies for web application development. The symposium will provide information about technology, resources, and supporting tools and processes of the OSS community. The attendee will take away from the symposium a basic understanding of the available technologies, information about how to acquire and learn more about the various packages, and insight that will enable them to make informed decisions about using and deploying specific OSS technology in web applications. The technical sessions will address: * overview - what is it, what does it do, what problems does it solve * key features - description of key features with short examples * application examples - a few simple examples of doing something useful or where/how to apply the technology * applicability - when should you use it? [or when not!] * resources - where to get it, who maintains it, where to find help, documentation, assistance, mailing lists Sessions -------- 9:00 Symposium Welcome 9:10 Introduction to open-source software Walt Scacchi Sr Research Scientist. UCI Institute of Software Research 10:00 Linux and OSS in Enterprise Development Bill Hilf Sr Architect and Linux Technical Leader. IBM 11:00 Web Application Development with Perl Eric Hammond Director of Technology. Rent.com 12:00 Lunch (Included for paid registrants) 1:OO Introduction to PHP and PEAR Jesus Castagnetto Co-author of "Professional PHP Programming" (Wrox Press) 2:00 Python-Powered Web Application Development Chuck Esterbrook Software Consultant and Creator of Webware for Python 3:00 Mid-afternoon break 3:15 Java OSS Web Technologies Dave Ford Java Consultant and Trainer. SmartSoft. 4:15 Experiences in OSS Web Application Development Panel Facilitated by Prakash Malani Principal Software Engineer. eBuilt.com 5:15 Closing Closing remarks and symposium wrapup. Cost and Registration --------------------- Your registration fees will be discounted according to your IEEE and/or Computer Society membership, as shown below: Standard $75 IEEE Member $60 IEEE Student Member $30 Student $45 You may register online at https://www.regonline.com/Checkin.asp?EventId=9769 If you are one of the first 75 paid registrants, you will get a chance to win one of two Oreilly's "Linux Server CD Bookshelf" (retail value: $119.95), or one of many other LAMP related Oreilly reference books. COSST Volunteers will get in free. There may also be T-Shirts. To volunteer, contact Sebastian: seguti at ics.uci.edu or call 1-949-509-9628 Direction --------------------- Conexant Systems-Jazz Semiconductor 4321 Jamboree Road Newport Beach, CA 92660 A map of the area may be found at http://www.jazzsemi.com/docs/jazz-directions.pdf For more information, please visit us at http://cosst.ieee-occs.org or call Toll Free 1-888-548-1969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mpeuser at web.de Thu Sep 11 13:27:06 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 11 Sep 2003 19:27:06 +0200 Subject: Import question References: Message-ID: "Fred Lionetti" > If I have a file at C:\Python23\myfolder\mymodule.py > > why can't I say (from python prompt or anywhere else): > import myfolder.mymodule ???? It might help to put an empty file named __init__.py into 'myfolder' Kindly Michael P From ulope at gmx.de Thu Sep 18 16:38:56 2003 From: ulope at gmx.de (Ulrich Petri) Date: Thu, 18 Sep 2003 22:38:56 +0200 Subject: Python ISPs References: <924a9f9c.0309181224.374a5bef@posting.google.com> Message-ID: "Paradox" schrieb im Newsbeitrag news:924a9f9c.0309181224.374a5bef at posting.google.com... > Does anyone know of some ISPs that have Mod_Python installed. Most > seem to allow Python CGI but not things like Mod_Python or Spyce. Is > this a viable solution or should I just learn PHP. I would prefer to > leverage my Python knowledge but I also would like a fast robust > solution. You could go for one of those virtual servers all for yourself... Ciao Ulrich From eppstein at ics.uci.edu Sun Sep 21 17:58:11 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 21 Sep 2003 14:58:11 -0700 Subject: math.exp(complex) References: Message-ID: In article , "Tim Peters" wrote: > > >>> math.e**(1j*math.pi) (-1+1.2246467991473532e-16j) > > Or, in this case, use the builtin pow(), which looks for a __pow__ method, > which is the same thing "**" does. Math libraries in general can return a > better result for exp(x) than e**x, though, since the latter form uses a > machine approximation to e as the base. Doesn't look especially different to me, for the numbers I'm currently interested in applying this to (small pure imaginary): >>> from cmath import * >>> exp(1j*pi) (-1+1.2246467991473532e-16j) >>> e**(1j*pi) (-1+1.2246467991473532e-16j) -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From leo.broska at NOSPAM.isys.com.au Wed Sep 3 01:34:19 2003 From: leo.broska at NOSPAM.isys.com.au (Leo) Date: Wed, 3 Sep 2003 15:34:19 +1000 Subject: just a beep References: Message-ID: thanks a lot! that's what i want: an platform independend beep! and indeed i want to read more about functions vs methods! but my quick browse through the docu did not show me that there is sth in beetween Tkinter and bell... cheers, leo "Fredrik Lundh" wrote in message news:mailman.1062489605.3888.python-list at python.org... > "Leo" wrote: > > > i want python to do a beep. > > > > in the docu i found in tkinter the method > > bell() > > but the script: > > import Tkinter > > Tkinter.bell() > > gives the error: > > AttributeError: 'module' object has no attribute 'bell' > > you might find it easier to use Python if you spend some time reading > up on functions vs. methods; in the meantime, here's one way to call > the "bell" method in Tkinter: > > >>> import Tkinter > >>> Tkinter.Tk().bell() > > > > > > From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Sep 26 15:43:10 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 20:43:10 +0100 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> <5L%cb.13662$yD1.1524835@news20.bellglobal.com> Message-ID: On Fri, 26 Sep 2003 14:42:28 -0400, "Sean Ross" wrote: > >"David Eppstein" wrote in message >news:eppstein-AF4213.10592426092003 at news.service.uci.edu... >> Your proposed name has an implication for the semantics. > >Do the implied semantics of ireverse() differ from those implied by the >names iter_backwards(), reverse_view(), riter(), etc.? >Because, to me, they' re just different words for the same idea. So far as I can see, it is having the function rather than the method that creates the issues - that originated with David Abrahams post (at least tracing back through this thread - it had been suggested before). However, your reply was implicitly supporting the use of a function rather than a method. If 'ireverse' is imported from 'itertools' then it cannot be a method of the object being reversed. I think some wires have been slightly crossed - David Eppstein raised a good point, but should perhaps have aimed it at David Abrahams. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From uce at ftc.gov Fri Sep 12 14:14:10 2003 From: uce at ftc.gov (Gordon Airport) Date: Fri, 12 Sep 2003 14:14:10 -0400 Subject: Printing a Tk canvas under windows Message-ID: <_tGdnRIQmtdtkf-iXTWJiQ@comcast.com> I was surprised that I couldn't find enough information out there to get this to work. Just enough to make a mess ;-). The code below just starts spitting out what I guess is postscript code, seperated by line feeds but not carrage returns, so they run right off the page. Certainly nothing graphical. ... printerName = win32print.GetDefaultPrinter() printerHandle = win32print.OpenPrinter( printerName ) win32print.StartDocPrinter( printerHandle, 1, ("test", None, "raw" ) ) win32print.WritePrinter( printerHandle, canvas.postscript() ) win32print.EndDocPrinter( printerHandle ) win32print.ClosePrinter( printerHandle ) I got the same result with None instead of "raw". The printer's an HP deskjet 930, if that helps. From __peter__ at web.de Wed Sep 17 13:13:09 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Sep 2003 19:13:09 +0200 Subject: fast way to filter a set? References: Message-ID: Nicola Mingotti wrote: > fortepianissimo at yahoo.com.tw (Fortepianissimo) writes: > >> I know I can do things like >> >> s=Set(range(1,11)) >> s=Set(filter(lambda x:x%2==0,s)) >> >> But this seems a bit slow since filter returns a list which then must >> be converted back to a set. Any tips? Thanks! > > Can you ? > I tried python2.3 and 2.2 and it replies > : "NameError: name 'Set' is not defined" . In 2.3 it works if you do from sets import Set first. Peter From newsgroups at jhrothjr.com Tue Sep 30 11:37:44 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Sep 2003 11:37:44 -0400 Subject: intercepting smtp email References: Message-ID: ".r!kard" wrote in message news:blc6f3$3si$1 at green.tninet.se... > Now you got me corious, is that possible in python? > Possibly by extending it with som C of course... I've got no idea where you would put that kind of hook in Windows. John Roth > > .r!kard > > > "John Roth" wrote in message > news:vnj6j3dv1di62b at news.supernews.com... > > > > ".r!kard" wrote in message > > news:blc1kt$ooe$1 at green.tninet.se... > > > I'm no star at this but maybe you can check the code in > > > http://www.gnu.org/software/mailman > > > > > > .r!kard > > > > I think he's asking for a mini-firewall. In other words, is something > > he doesn't know about sending messages on port 25? > > > > John Roth > > > > > > > > "Scott Hathaway" wrote in message > > > news:c6354815.0309300518.4acb87b2 at posting.google.com... > > > > I want to write an NT service that will intercept any outgoing smtp > > > > traffic, like Norton Antivirus does. Can anyone tell me how I can do > > > > something like this in Python? I do not know how to intercept the > > > > outgoing traffic, specifically. > > > > > > > > Any help is greatly appreciated. > > > > > > > > Thanks, > > > > Scott > > > > > > > > > > > > From timothy.williams at nvl.army.mil Mon Sep 15 11:45:31 2003 From: timothy.williams at nvl.army.mil (Tim Williams) Date: 15 Sep 2003 08:45:31 -0700 Subject: stripping a string References: Message-ID: Jeff Epler wrote in message news:... > If you want to remove all digits from the string, then use > str.translate, not regular expressions: > import string > identity_transformation = string.maketrans('', '') > > def remove_digits(s): > return s.translate(identity_transformation, string.digits) > > >>> s = 'ANL LN32' > >>> remove_digits(s) > 'ANL LN' > > If you want to remove digits from the end of the string, then use > str.strip(), not a regular expression: > >>> s.rstrip(string.digits) > 'ANL LN' > > Jeff I don't understand. What's wrong with >>> import re >>> s = 'ANL LN32' >>> s=re.sub('[0-9]', '', s) >>> print s ANL LN From linuxlists at chargedideas.com Mon Sep 15 06:10:44 2003 From: linuxlists at chargedideas.com (Andres Montiel) Date: Mon, 15 Sep 2003 06:10:44 -0400 (EDT) Subject: pyc2py In-Reply-To: <3F656561.6070701@ghaering.de> References: <3F656561.6070701@ghaering.de> Message-ID: <39324.202.175.228.157.1063620644.squirrel@webmail.chargedideas.com> Hmmm... does this mean that any Python compiled can be decompiled? What if someone was selling compiled Python programs. decompyle seems to be able to decompile them. Is there a way to make sure that compiled python code cannot be decompiled? - Andres > Thomas Guetttler wrote: >> Hi! >> >> Is there a script which converts compiled python code >> to human readable code? >> >> Google found no result for "pyc2py". > > Try this keyword: decompyle > > -- Gerhard From indigomoonBLINDERS at bonbon.net Sat Sep 20 00:35:32 2003 From: indigomoonBLINDERS at bonbon.net (Indigo Moon Man) Date: Fri, 19 Sep 2003 22:35:32 -0600 Subject: py2exe web site Message-ID: What has happened to the py2exe web site? I'm getting a 'Cannot find server' error when I try to go there. It was working just the other day I'm pretty sure. This is the address I have for it... http://starship.python.net/crew/theller/py2exe/ Do I have the wrong somehow? Thanks! -- Remove BLINDERS to email me. Audio Bible Online: http://www.audio-bible.com/ From webmaster at python.org Sat Sep 20 15:47:09 2003 From: webmaster at python.org (Aahz) Date: 20 Sep 2003 15:47:09 -0400 Subject: starship.python.net DNS problems Message-ID: There seems to be some kind of problem with Starship's DNS. Until it's fixed, please use the direct IP of 217.160.219.194 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From mike at nospam.com Thu Sep 25 16:59:51 2003 From: mike at nospam.com (Mike Rovner) Date: Thu, 25 Sep 2003 13:59:51 -0700 Subject: Getting C++ object from PyObject * References: Message-ID: Nikolai Kirsebom wrote: > I'm using BOOST to integrate Python into our application. Could Usually *.python.c++ is a better place to discuss boost.python issues. > someone tell me how I get hold of the C++ object (pointer to the > object instance) from a PyObject *. > > Example: > I have defined and exposed two C++ classes: > > class MyObjectA > { > public: > MyObject(); > }; > > class MyObjectB > { > public: > MyObjectB(); > void SetInput(PyObject *o); > }; > > In Python I'm able to write: > > pa = MyObjectA() > pb = MyObjectB() > > to create an instance of each of the classes. > > Then using the exposed SetInput method of class MyObjectB: > > pb.SetInput(pa) Unless you have a variety of different inputs to SetInput() you probably want void MyObjectB::SetInput(MyObjectA const&) In that case boost.python will be able to do extract(object(pa)) by itself along with some error checking you discuss later: > How would I code the SetInput method: > > void MyObjectB::SetInput(PyObject *o) > { > //Check that type of 'o' is an (instance) object of class 'MyObjectA' > //Fetch the pointer (reference) to the actual instance of MyObjectA > MyObjectA * ca = ..... > } Also you might want some lifetime control with_custodian_and_ward<1,2>() to prevent pa from garbage collection while it's used in pb. HTH, Mike From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 11:37:16 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 16:37:16 +0100 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <8RScb.169633$R32.5449258@news2.tin.it> <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> <0acdb.128801$hE5.4391247@news1.tin.it> <1Xhdb.130593$hE5.4445587@news1.tin.it> <9tabnvgbc4etnpp1hm3oh5dkffkru9pv0d@4ax.com> Message-ID: On Sat, 27 Sep 2003 16:35:10 +0100, Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: >set of standard protocols (forward, bidirectional, random etc) which >all include subscripting. Oops - I've got subscripting on the mind just now. I meant dereferencing of course. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From __peter__ at web.de Thu Sep 25 08:17:42 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2003 14:17:42 +0200 Subject: adodbapi / string encoding problem References: Message-ID: Achim Domma wrote: > I read a webpage via urllib2. The result of the 'read' call is of type > 'str'. This string can be written to disc via > file('out.html','w').write(html). Then I write the string into a Memofield > in an Access database, using adodbapi. If I read the text back I get a > unicode string, which can not written to disc via file(...) due to > encoding problems. How do I have to decode the unicode string to get my > original data back? You have to know the encoding of the original file. Assuming (1) you had western european characters including the euro sign, (2) they were correctly translated into unicode and (3) you want them back that way: >>> s = u"??????".encode("iso-8859-15") >>> s '\xe4\xf6\xfc\xc4\xd6\xdc' >>> print s ?????? >>> type(s) >>> Or more general: unicodeFromAccess.encode(targetEncoding) Peter From _remove_jones57 at swbell.net Wed Sep 17 01:05:57 2003 From: _remove_jones57 at swbell.net (sj) Date: Wed, 17 Sep 2003 05:05:57 GMT Subject: Can Python Module Locate Itself? Message-ID: I have written several small shell utilities in Python and typically use comments at the start of the source file as documentation. A command line option allows the user to read this documentation. The problem is that I have to explicitly code the source files location within the source which is not very portable. Is there anyway for a python module to locate its own source ? Thanks From wtrenker at shaw.ca Sun Sep 14 12:33:49 2003 From: wtrenker at shaw.ca (William Trenker) Date: Sun, 14 Sep 2003 16:33:49 +0000 Subject: Huh?!?!? What is it that I'm seeing here? In-Reply-To: References: Message-ID: <20030914163349.03e187a6.wtrenker@shaw.ca> On Sun, 14 Sep 2003 21:45:16 +0000 (GMT) Don Bruder wrote regarding Huh?!?!? What is it that I'm seeing here?: > if __name__ == '__main__': > run(argv[1:]) The above code reads something like this: if the name of the current module is __main__, then invoke the run method with the parameter to run() being a list of the remaining arguments on the command line, excluding the argument that is the name of the python script to be executed. The name of a module is set by Python to the value __main__ when the module is invoked from the command line. So if I have a command line like this: python boink.py arg1 arg2 arg3 then the code for boink.py will be loaded and run. Since boink.py was loaded from the command line it will be given the module name __main__ and so the if statement will succeed. The run method will be invoked with argv[1:] expanded like this: run(['arg1', 'arg2', 'arg3']) (argv[0] is the value 'boink.py' from the above command line example.) Hope that helps, Bill From duncan at NOSPAMrcp.co.uk Fri Sep 12 05:14:41 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 12 Sep 2003 09:14:41 +0000 (UTC) Subject: dumb q: repeated inheritance in python? References: Message-ID: corey.coughlin at attbi.com (Corey Coughlin) wrote in news:a8623416.0309111319.14334945 at posting.google.com: > What I'd really like to do is inherit this same object > twice, but the second time rename the objects so that I get 'name2' > instead of 'name'. (And somehow rename the functions, and so on.) I'm not sure if I exactly understood what you want, but does this help? I think you are asking for two properties that access differently named attributes but perform the same type checking in each case. That sounds to me like you want a specialised property which can be done by subclassing it: ---- begin test.py ---- class Name(property): def __init__(cls, attrname): def setnm(self, nm): if isinstance(nm, str): setattr(self, attrname, nm) else: raise TypeError("Name passed to %s isn't a string" % self.__class__.__name__) def getnm(self): return getattr(self, attrname) property.__init__(cls, getnm, setnm) class TwoNamed(object): def __init__(self, iname='', jname=''): self.iname, self.jname = iname, jname name = Name('iname') name2 = Name('jname') x = TwoNamed('ivalue', 'jvalue') print "name, name2 =",x.name, x.name2 x.name = 'www' x.name2 = 'xxx' print "name, name2 =",x.name, x.name2 print "iname, jname =",x.iname, x.jname x.name = 42 # Blows up print x.name # Never reached. ----- end of test.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 mpeuser at web.de Sun Sep 21 05:41:59 2003 From: mpeuser at web.de (Michael Peuser) Date: Sun, 21 Sep 2003 11:41:59 +0200 Subject: Tkinter cursor question References: Message-ID: "Gary Richardson" schrieb im Newsbeitrag news:vmq6a09ffl4c4 at corp.supernews.com... > I would like to define a new cursor for use on a Canvas (other than one of > those listed in Appendix F of "Python and Tkinter Programming"). A search on > Google turned up one bit of code that seemed promising. A slightly > simplified version is shown below. This code attempts to eliminate the > cursor by defining an invisible one, which is not what I want, but I thought > it might be a start. However, it doesn't run; the statement t = Text(...) > generates an error message: TclError: bad cursor spec "@testcursor white". > The testcursor file is being created in the current directory. This is rather tricky - you will have to look through Tcl manuals, e.g.: http://dev.scriptics.com/man/tcl8.3/TkLib/GetCursor.htm You find there: @sourceName maskName fgColor bgColor In this form, sourceName and maskName are the names of files describing cursors for the cursor's source bits and mask. Each file must be in standard X11 or X10 cursor format. FgColor and bgColor indicate the colors to use for the cursor, in any of the forms acceptable to Tk_GetColor. This form of the command will not work on Macintosh or Windows computers. @sourceName fgColor This form is similar to the one above, except that the source is used as mask also. This means that the cursor's background is transparent. This form of the command will not work on Macintosh or Windows computers. @sourceName This form only works on Windows, and will load a Windows system cursor (.ani or .cur) from the file specified in sourceName. Kindly MichaelP From adalke at mindspring.com Mon Sep 22 01:29:09 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Mon, 22 Sep 2003 05:29:09 GMT Subject: Passing data out of a Sax parser References: <878yohajyc.fsf@pobox.com> Message-ID: Me: > > if name == "spam": > > self.count += 1 John J. Lee: > Works, but integers aren't mutable. I assume you refer to the snippet I posted above? Since it works, I don't understand the need for your comment. True, integers aren't mutable, so += does nothing to the integer. Since __iadd__ isn't defined, the Python runtime turns it into the equivalent of self.count = self.count + 1 and so does what is expected. Andrew dalke at dalkescientific.com From mertz at gnosis.cx Mon Sep 8 15:11:52 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 08 Sep 2003 15:11:52 -0400 Subject: What is marketing? References: Message-ID: <4RNX/kKkXgeM092yn@gnosis.cx> |> The neutral word that Alex is looking for is 'promotion', which has a |> subtle but important difference from the dirty word. Alex Martelli wrote previously: |Nope -- it's "marketing" as defined in textbooks of economics Ahh... that begs the question[*]. I do not believe that Economics is the relevant field to consult as to the purpose of the python.org website. Economists give only economic answers to questions, and that's not the particular song-and-dance that interests me (FWIW, I've published in an Economics journal, and taken graduate economics courses--albeit suspiciously lefty ones--so my eschewal comes from something other than simple ignorance). If we decide our textbook should be one about Sociology, or Psychology, or Anthropology, or Communications, the false generality for the term 'marketing' evaporates. IOW, I'm more interested in what Thorstein Veblen would say than in what Ludwig von Mises would say :-). Or for that matter, I'd rather consult Erving Goffman. Yours, Lulu... [*] Has anyone else noticed how horribly misused this phrase has become... including in a televised ad series by Adobe for Acrobat. -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. - _/_/_/ 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 tjreedy at udel.edu Mon Sep 15 19:41:06 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Sep 2003 19:41:06 -0400 Subject: unreferenced (???) variable; prob. simple References: Message-ID: "Halfdan Holger Knudsen" wrote in message news:mailman.1063654161.1263.python-list at python.org... >goodday all - here's a snippet of code that just doesn't seem to work...at >all! But I haven't got the faintest idea why I keep getting an unref. >local var. error. When asking a question about 'why do I get this error message', please copy and paste the complete error message, including the traceback. TJR From __peter__ at web.de Sun Sep 7 15:02:55 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Sep 2003 21:02:55 +0200 Subject: negative indices for sequence types References: Message-ID: dan wrote: > I was recently surprised, and quite shocked in fact, to find that > Python treats negative indices into sequence types as if they were > mod(length-of-sequence), at least up to -len(seq). > > This fact is *deeply* buried in the docs, and is not at all intuitive. > One of the big advantages of a high-level language such as Python is > the ability to provide run-time bounds checking on array-type > constructs. To achieve this I will now have to subclass my objects > and add it myself, which seems silly and will add significant > overhead. If you want this behavior, how hard is it to say a = b[x % > len(b)] ?? > > Can anyone explain why this anomaly exists, and why it should continue > to exist? After you have recovered from the shock, you probably will admit that (1) the most common "out of bounds" case is caught: >>> l = list("abc") >>> l[3] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range and (2) that accessing elements from the end of the list is something you will soon appreciate: >>> l[-1] 'c' >>> >>> l[-2:] ['b', 'c'] >>> I think that more code enjoys the beauty of accessing the end of a list than suffers from uncaught <0 index errors. See the possibilities rather than the danger :-) Peter From list-python at ccraig.org Mon Sep 15 09:24:52 2003 From: list-python at ccraig.org (Christopher A. Craig) Date: 15 Sep 2003 09:24:52 -0400 Subject: No "side effect" assignment! References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> <38ec68a6.0309142310.30c09f9f@posting.google.com> Message-ID: afriere at yahoo.co.uk (Asun Friere) writes: > I am alone in feeling some slight unease at the sight of "while 1: ... > break"? I know this is considered somewhat pythonic, but apart from > the fact that there is only a single assignment statement is there > really any advantage to be gained by doing it this way? It seems to > be trading one aesthetic disadvantage for another, and imho, a > marginally less legible one. While I agree with you, I don't think I'd bother with changing thel language now to fix it. If I were writing a new language I'd prefer a loop-and-a-half structure something like this: repeat: stuff while test: stuff I'd really prefer something like the above without the second colon. While it's nice to have the condition dedented for readability, it isn't really starting a new block. At any rate, I don't think adding this to the current language is worth it, so I'll keep using "while 1: break" structures and translating to the above in my head. -- Christopher A. Craig "So we who are many, are one body in Christ, and individually members one of another." Romans 12:5 (NASB) From jepler at unpythonic.net Thu Sep 4 23:02:19 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 4 Sep 2003 22:02:19 -0500 Subject: what's wrong with REBOL? In-Reply-To: References: <6005702b.0309020727.4ba46e78@posting.google.com> Message-ID: <20030905030219.GA2023@unpythonic.net> On Wed, Sep 03, 2003 at 12:32:19AM -0400, Lulu of the Lotus-Eaters wrote: > Yeah... and perhaps the word 'disingenuous' will be removed from future > editions of popular dictionaries; and then we will lack a concise way to > describe "special pleading" of this sort. I think it's unlikely though. Hey, big fella. I'm on your side. I was just playing devil's advocate for a moment. Jeff From danielk at aracnet.com Tue Sep 2 09:03:25 2003 From: danielk at aracnet.com (Daniel Klein) Date: Tue, 02 Sep 2003 06:03:25 -0700 Subject: Polymorphism the Python way References: Message-ID: On Sun, 31 Aug 2003 10:04:39 +0200, Peter Otten <__peter__ at web.de> wrote: >Daniel Klein wrote: > >> ...and then somewhere in some script I use... >> >> self.getthing() >> >> to get whatever 'thing' I want to get. >> >> Isn't there a better way to do this in Python? I hate doing these >> 'get' type methods. The seem ugly to me. > >You can use properties, which simplifies the client code at the cost of an >extra line in the class definition, e. g.: > Thanks. You and Alan Gauld provided the same answer, which seems to be the best approach. Dan From not at home.org Wed Sep 17 13:04:04 2003 From: not at home.org (Dfenestr8) Date: Thu, 18 Sep 2003 02:04:04 +0900 Subject: Mandrake Linux 9: Why isn't bsddb working? Message-ID: I started off trying to use bsddb with my standard mandrake 9 python 2.2.1 package. The shell reported back no such module. Strange, thinks I. I thought it was standard in the package, it was when I was using Windows. So I uninstalled Python, downloaded the latest python 2.3 and compiled it from source. Now when I try to import bsddb, I get this error...... >>> import bsddb Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/bsddb/__init__.py", line 40, in ? import _bsddb What might I have done wrong, and/or what should I do to fix it? From alkirke1 at comcast.net Thu Sep 11 21:55:01 2003 From: alkirke1 at comcast.net (Al Kirke) Date: Fri, 12 Sep 2003 01:55:01 GMT Subject: OT: Americans love their guns References: <16223.15950.299463.959577@montanaro.dyndns.org> <000b01c37824$c972de10$3a0ff10c@teaset> Message-ID: "Skip Montanaro" wrote in message news:mailman.1063290822.30564.python-list at python.org... > > Al> MY children were taught to handle firearms safely beginning age 5. > Al> Are yours? > > No, we're more intelligent than that. We have no guns in our house. > > Why is this on c.l.py anyway? It shouldn't be on the python group.. It was off-topic and I should not have replied. But in winding up, the fact remains that there is and has always been a violent criminal element in society, and none of us expect this to change. That being the case, without handguns is there any protection against those elements? The only statistics I know of that compare convictions of Texas carry-concealed license holders to convictions in the general population are from the Texas Department of Public Safety. http://www.tsra.com/DPS_convictions.htm About a year ago a constable pulled me over for speeding. The procedure for a driver is to hold both his drivers license and his concealed handgun license out the window for the officer to observe as he approaches. Texas police are in general comforted by the appearance of concealed handgun licenses, because these guarantee that a convicted felon is not driving that car. My (very) pretty daughter was in the car, and as the constable was writing out the ticket, he spent some time telling my daughter that the world is nastier now that it once was, and that she should seriously consider getting her own CHL. Remember, when you and your family are driving late at night, that you're only a timing belt away from meeting new and exciting people. Cheers, Al From claird at lairds.com Fri Sep 5 10:19:33 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 05 Sep 2003 14:19:33 -0000 Subject: OT: best book in years References: Message-ID: In article , Alan James Salmoni wrote: . . . >had a profound effect on all of us. Call this extremely geeky, but I >love the idea of tinkering around with the old machines described in >that book. I'll have to search for a simulator when I get a spare few >hours! I found it full of detail (not too technical, but lots of . . . The opportunities here are greater than you might realize. There's a great deal of amateur "retro-computing" activity: enthusiasts with PDP11s in their basement, and so on. A distinct, but equally engaging area, is that of emulators; wonderful work has been done to recreate the behavior of antique systems. While some of it is ill-maintained, I try to point to only the highlights in . -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From anand_soliton at yahoo.com Wed Sep 10 21:02:39 2003 From: anand_soliton at yahoo.com (Anand) Date: 10 Sep 2003 18:02:39 -0700 Subject: Python C extension: Value different if passed as list than if passed as number References: <3f5dc178.0309101343.256bb7f5@posting.google.com> Message-ID: <3f5dc178.0309101702.46a4ff58@posting.google.com> My bad. I wanted to do a inplace memory write for an int. so i = 0; func(i); print i; ====== output = 1. The funny thing is python doesnt use 0 as 0. instead it points to a memory location whose value = 0. Since in my inplace replace, i changed that value from 0 to 1, test[0] actually became test[1] :)) so i had tons of strange behavior happening. I shouldnt have made an immutable object as mutable. From jjl at pobox.com Mon Sep 8 17:52:49 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Sep 2003 22:52:49 +0100 Subject: Eureka! (Re: Comments on Python Redesign) References: <3F5CD10B.2020709@teksavvy.com> <200309072018.05589.dave@pythonapocrypha.com> Message-ID: <87u17nne1a.fsf@pobox.com> Skip Montanaro writes: [...] > * The tinyurl website can become a bottleneck, preventing people from > getting where they want to go. The tinyurl.com website seems to be fairly > unreachable for me at the moment, though this is the first time I've seen > this, and it appears to be a problem more with Northwestern's connection > to the net than tinyurl.com's. Apparently not: I can't reach it either. > * There's no guarantee tiny urls will remain unique or even available for > long periods of time. Their current practice of using four lower-case > letters suggests they have space for about 450,000 unique URLs before > extending to a fifth letter. Good practice to give both URLs, I suppose -- easier to cut-n-paste the tinyurl, but the original one has a better chance of still working later. John From vze4rx4y at verizon.net Thu Sep 25 14:38:20 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 25 Sep 2003 18:38:20 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> Message-ID: [sebastien] > So, I'd expect to have a riter() function which would call the > __riter__ special method. Okay, changed pep to list riter() as an alternative. > And I still think you don't need it often enough to put it in the > builtin namespace, so the function should go in the itertools module. If you have a magic method, __riter__, then the corresponding function needs to be a builtin. They go hand in hand. The core parts of the language need to be usable without having to know about itertools. Raymond From aleax at aleax.it Thu Sep 4 03:54:55 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 04 Sep 2003 07:54:55 GMT Subject: Writing solid code book References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> Message-ID: Roy Smith wrote: > Jules Dubois wrote: >> My "Software Engineering" class votes again tomorrow on the language we >> use >> for our group project. Tuesday's vote was Java (8 votes), Python (5), >> C++ >> (3), and Smalltalk (1); Thursday's vote will be between Java and Python. >> I get the opportunity to learn one or the other in a week. > > How many votes does a language need to get to be elected Governor of > California? Given that they vote in a sensible way (runoff between the top two candidates, rather than "first past the post") you can't directly compare the two elections. (You can get the same results as with a preliminary vote + runoff by such methods as STV and Condorcet -- the whole issue was discussed in depth last spring on this group regarding the ternary operator vote -- but that's an issue only if arranging for voting twice is costly or inconvenient). Alex From fpetermaas at netscape.net Fri Sep 26 06:13:12 2003 From: fpetermaas at netscape.net (Peter Maas) Date: Fri, 26 Sep 2003 12:13:12 +0200 Subject: Successful installation of mod_python on Apache on Win2k? In-Reply-To: References: Message-ID: Rolfe wrote: > 3. When I created and ran the following script shown at > http://www.modpython.org/live/current/doc-html/inst-testing.html, my > browser displays the full text of the script instead of running the > script: > "from mod_python import apache > > def handler(req): > req.write("Hello World!") > return apache.OK" > > 4. I've read Troubleshooting and FAQ, triple-checked my http.conf > file, and still can't get it to work. > > ANY SUGGESTIONS? This is my working conf (on Linux, though): LoadModule python_module modules/mod_python.so AddHandler python-program .py PythonHandler mptest PythonDebug On /usr/local/apache2/htdocs/test/mptest.py works. If you have an analogous conf, it might be an OS related issue. Mit freundlichen Gruessen, 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 $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 10 14:04:45 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 10 Sep 2003 19:04:45 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> Message-ID: On Wed, 10 Sep 2003 16:55:28 +0200, Peter Otten <__peter__ at web.de> wrote: >Obviously, your example could easily be rewritten to > >def inc(p): > return p + 1 > >x = inc(x) > >and a similar function with two by-ref parameters would still be readable: > >x, y = inc2(x, y) > >So here's my question. How many functions are there in your *real* code that >could benefit from, say three or more by-ref parameters? >Hint: for me it comes close to 0 :-) Its not an issue of whether the same effect can be achieved in Python. It's more an issue of whether the method used expresses the programmers intentions properly. If a function is defined as... def Inc (p) : return p + 1 then that to me expresses an intention which is different to that expressed by... def Inc (ref p) : p += 1 The latter case expresses the intention to in-place rebinding of the parameter. In doing so, it better expresses the purpose of some kinds of functions (though not this noddy example, obviously). This is all very fuzzy, so let's examine an example which is based on an issue in some real Python code (though this is simplified to make the point). The problem is to insert an object into some container - appending to a list will do here. However, the object being inserted will typically be quite large, so we want to avoid copying it if possible. No problem there, it seems... class c_Container : f_List = [] def Add (self, p_Object) : f_List.append (p_Object) The problem with this, however, is the risk of accidental side-effects. If the caller goes on to modify the object that he passed as a parameter, that will change the content of the container. So how can rebindable parameters help with this? One approach would be to make the function rebind the parameter to either None or some kind of read-only proxy object. If the caller tried to modify the object after passing it in, he'd very quickly get error messages. They may seem cryptic, but they'd be better than the strange hard-to-trace errors you get with accidental side-effects. Having figured out what the problem is, the caller simply has to make a copy of the object himself (or use a variant of the function that does the copying itself). class c_Container : f_List = [] def Add (self, ref p_Object) : f_List.append (p_Object) p_Object = None # p_Object = Read_Only_Proxy (p_Object) def Add_Copy (self, p_Object) : f_List.append (copy.deepcopy (p_Object)) The point of the ref parameter here is not just to allow information to be passed to the caller from the function - it is to ensure that the source of the specific parameter passed in gets rebound. The intention to 'give away' that object would be expressed by the 'ref' in the call... l_Container = c_Container () l_Object = Get_The_Object () l_Container.Add (ref l_Object) Actually, an 'in' or 'give' modifier might make even more sense here (very different to C# - I can't imagine a reason for an 'out' modifier in Python). Where such problems occur, this is by no means foolproof of course. For example... l_Container = c_Container () l_Object_Ref1 = Get_The_Object () l_Object_Ref2 = l_Object_Ref2 l_Container.Add (ref l_Object_Ref1) l_Object_Ref2.Mutate_Somehow () However, it would probably catch a very substantial portion of real accidental side-effect errors. >By the way, this is strictly from a user perspective, I trust the Python >developers to overcome the implementation issuses, *if* there is a >significant usability improvement. And that is the big question. C# 'needs' ref parameters because it has no convenient way to return multiple values from a function. Python does not. The question is really whether this argument about expressing intentions and evading errors is compelling or not. From essai1 at mci.local Mon Sep 29 18:28:02 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Tue, 30 Sep 2003 00:28:02 +0200 Subject: data encoding for Python COM interface References: Message-ID: Hi ! In other environment (windows + Paradox/objectPal +COM-python-script), i do : import locale CodingParDefaut = locale.getpreferredencoding() def XYZ(self, argu): # public method chaineretour = argu.encode(CodingParDefaut)) return chaineretour This work (encode in entry to COM-python nothing at return). Perhaps can you find in an idea ? * sorry for my bad english * @-salutations -- Michel Claveau From lutz at rmi.net Thu Sep 11 16:48:07 2003 From: lutz at rmi.net (Mark Lutz) Date: 11 Sep 2003 13:48:07 -0700 Subject: Learning Python, 2'nd Edition, O'Reilly References: <8e6e8e5d.0309101814.393a8ed0@posting.google.com> Message-ID: rdsteph at earthlink.net (Ron Stephens) wrote in message news:<8e6e8e5d.0309101814.393a8ed0 at posting.google.com>... > Does anyone know when this is due to be released? I am assuming that > this version will cover Python 2.3, and be the first book to fully do > so. > > Ron Stephens Not exactly, but the late-October-to-November timeframe is as good a guess as any. Last I heard, it's now in the production pipeline. It will be a 2.3 book, despite what some of the marketing might say (we started it awhile ago). For a few more words, here's a web page I posted in response to email queries: http://www.rmi.net/~lutz/about-lp2e.html Cheers, Mark Lutz (www.rmi.net/~lutz) From theller at python.net Thu Sep 18 13:48:35 2003 From: theller at python.net (Thomas Heller) Date: Thu, 18 Sep 2003 19:48:35 +0200 Subject: Streams causing heap crash using Python C-Extensions References: Message-ID: <3ceuf0ng.fsf@python.net> batraraj at hotmail.com (Raj Batra) writes: >> I'm using Python2.2.2, with Visual C++ 7 (.NET). The error occurs using >> both pythonwin and the standard command line python. I don't know whether you can use C++ stream I/O in a Python extension or not, but if you use MSVC7 to compile the extension, your Python must also be compiled with this one (generally). Thomas From h.b.furuseth at usit.uio.no Mon Sep 1 14:26:28 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 01 Sep 2003 20:26:28 +0200 Subject: imports after function definitions? References: <3F4F9021.354CDD2D@engcorp.com> Message-ID: Thanks for all the answers. Peter Hansen wrote: >Hallvard B Furuseth wrote: >> I'm setting sys.path in a config function which depends on variables >> near the end of the file. So the config function must be called late, >> and the imports that depend on it after that. > > Sounds like the structure ought to be changed (IMHO). OK, I did. Moved the sys.path setting out of the config function. > In other words, why do you need all those defines and all those > variables to come before the imports? I needed the config function to be called before the imports since it set sys.path, and the config function should be able to access some variables. So the imports had to come after it, and after those variables. I thought it looked better to have the imports at the end of the program than in the middle of it. Never mind, though. Now I have them right after the config function. I want that one at the beginning because that's what people need to edit. -- Hallvard From NO-MAIL at hotmail.com Fri Sep 19 05:26:54 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Fri, 19 Sep 2003 09:26:54 GMT Subject: How to pass parameter to a module? References: <8ef9bea6.0309182328.5c040595@posting.google.com> Message-ID: Thank you! "Hung Jung Lu" wrote in message news:8ef9bea6.0309182328.5c040595 at posting.google.com... > "M-a-S" wrote in message news:... > > I'd like to parametrize a module. That is, to set and pass > > some values into the module, while it is being imported. > > There are many ways. > > (However, classes may fit your need better. "Passing parameters to a > module" is not a common practice, as far as I know.) > > (1) Use a built-in namespace variable. > > import __builtin__ > __builtin__.myvar = 3 > print myvar > > This is a hack. I have been screamed at for mentioning it. :) > > (2) Hack your favorite (non-builtin) module. The module could be any > of the standard library modules, or your own third module. > > import sys > sys.myvar = 3 > > (3) Use environmental variables. > > import os > os.environ['myvar'] = 'hello' > > You get the idea. Python has three namespaces: built-in, global, and > local. Since global and local namespaces won't go over to the other > module, you need to rely on the built-in namespace, one way or > another. How you want to structure your data (by using the built-in > namespace, a module, a class, a dictionary or any other entities that > can hold a name entry), it's entirely up to you. > > Hung Jung From jacek.generowicz at cern.ch Wed Sep 17 07:49:59 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Sep 2003 13:49:59 +0200 Subject: Is there "let binding" in Python? References: Message-ID: Rob Hunter writes: > Is there an equivalent to Scheme's LET in Python? > LET creates a new binding in the current > environment. For example, here's some Scheme > code: > > (let ((x 3)) > (let ((f (lambda (arg) (* arg x)))) > (let ((x 4)) > (f 5)))) > > So, this program, which also tests that Scheme > has correct scoping, returns 15. Sorry, never heard of "correct" scoping[*]. I've heard of lexical and dynamic scoping though, and, to me, your code shows that Scheme has lexical scoping. > And in Python, I can write an equivalent program > that does correctly return 15, but I have to use > what, in Scheme, we call "left-left lambda"--a > way of simulating LET. Or rather, LET is > syntactic sugar for left-left lambda. A long, time ago (Python 2.0), Python only had 3 scopes: local, global and builtin. Now it has nested scopes of arbitrary depth (still wrapped inside global and builtin), but I'm not expecting "let" to appear anytime soon. [*] But given that you are formulating your question from a Scheme perspective, it's not really surprising that you call it "correct". :-) From skip at pobox.com Tue Sep 9 11:13:10 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 9 Sep 2003 10:13:10 -0500 Subject: Massive unit test vs MySQL In-Reply-To: References: Message-ID: <16221.60934.194086.18486@montanaro.dyndns.org> Richard> Yes, that is the problem, but it is not clear how to release Richard> the connections. They get released immediately when the script Richard> terminates. I am wondering of it is a gc problem. How about you explicitly tack an explicit exit; onto the end of the input? % mysql -u concerts -h localhost -p concerts Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 440197 to server version: 3.23.41-log Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> exit; Bye Skip From dickey at saltmine.radix.net Tue Sep 2 09:06:38 2003 From: dickey at saltmine.radix.net (Thomas Dickey) Date: 2 Sep 2003 13:06:38 GMT Subject: curses! trouble with pads and panels References: Message-ID: Edmond Ho wrote: > Hi, I'm having trouble with a small curses program. I'm associate a pad with > a panel. As I understand, a pad is supposed to be just a window with an > arbitrary size. That seems to imply that a pad can be treated like a normal not exactly - some special handling is needed in the library to make it treat pads like a normal window. Your example may be a case where it's not implemented. -- Thomas E. Dickey http://dickey.his.com ftp://dickey.his.com From bgailer at alum.rpi.edu Tue Sep 30 15:03:28 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 30 Sep 2003 13:03:28 -0600 Subject: where are the "class variables"? In-Reply-To: <62e9c66e.0309301057.65f24a3b@posting.google.com> References: <62e9c66e.0309301057.65f24a3b@posting.google.com> Message-ID: <6.0.0.22.0.20030930130109.03299928@66.28.54.253> At 12:57 PM 9/30/2003, Dominik Kaspar wrote: >i'm used to java and its strict way of defining variables. so how is >it possible to reach something like a class variable in python? >with the following code i didn't have much succes... > >class Server(threading.Thread): > running = 0 (??) > > def run(self): > running = 1 > while running: > print "do something here..." > def exit(self): > running = 0 prefix running with the class name: Server.running =1 while Server.running: ... Server.running = 0 Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003 From lunqual at gmx.de Tue Sep 23 13:02:09 2003 From: lunqual at gmx.de (Karlheinz klingbeil) Date: Tue, 23 Sep 2003 19:02:09 +0200 Subject: python script as an emergency mailbox cleaner References: Message-ID: Alex Martelli wrote: > All my mailboxes have been filling up with files of about 130k to 150k, no > doubt copies of some immensely popular virus. So, I've no doubt lost lots > of real mail because of "mailbox full" conditions (the proliferating fake > bounce messages more or less ensure nobody knows their mail to me has > bounced, either). > > As an emergency response I and Anna developed, over the last half hour, a > small Python script to be run from cron every few minutes and > automatically > scrub any POP3 mailbox from files in the target size range. I'm saving > them to a local file for potential later perusal, but that's obviously I have made a quick and dirty pop-cleaner, mor configurable with size, regex to deny and regular pattern match to explicitly allow mails look at http://www.lunqual.de/popclean.zip (only 3kb) -- Greetz.... lunqual http://www.lunqual.de From news at yebu.de Fri Sep 19 09:35:25 2003 From: news at yebu.de (Karl Scalet) Date: Fri, 19 Sep 2003 15:35:25 +0200 Subject: SMTPlib Emailing Attachments In-Reply-To: <4fd6e92.0309190518.3b226735@posting.google.com> References: <4fd6e92.0309170849.287e86b6@posting.google.com> <4fd6e92.0309190518.3b226735@posting.google.com> Message-ID: Bill wrote: > [...] > path = 'C:\\YourPath\\YourFile.txt' > filename = 'gfe.pdf' is this correct? Shouldn't path contain the directory only? Otherwise what's the content of YourFile.txt then. Karl From alan.gauld at btinternet.com Thu Sep 4 02:44:23 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Sep 2003 06:44:23 GMT Subject: questions References: Message-ID: <3f56dec8.372921773@news.blueyonder.co.uk> On Wed, 3 Sep 2003 21:22:55 -0500, "Andy" wrote: > Can you use Python to access SQLServer... if so do you have an example. Yes, look at the DAtabae section of the Python web site for info > What are the strengths and weaknesses of Python.? Look at the language comparisons section of the Python website > Is it like vbscript ? Not to look at, but yes in that they are both interpreted and Python can do most of the things VBSCript can do - plus a lot more that VBScript can't. > Example code of things that it's good at.... to get me started Visit the "Useless Python" web site for small sample code snippets. Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From asl2 at panix.com Thu Sep 18 10:56:42 2003 From: asl2 at panix.com (Aaron Lav) Date: 18 Sep 2003 10:56:42 -0400 Subject: ASN.1 source reader References: <3F69B497.CEF764ED@siemens.com> <8765jqurh3.fsf@pobox.com> Message-ID: In article <8765jqurh3.fsf at pobox.com>, John J. Lee wrote: >Tomas Kukosa writes: > >> does anybody know any way how to read ASN.1 source into Python? >> I can not find any ASN.1 parser. > >http://www.panix.com/~asl2/software/PyZ3950/index.html > >Aaron also links to another couple of ASN.1 libraries there. The current public release of PyZ3950 doesn't include a usable parser for ASN.1 specifications. My current sources do, and I hope to make a public release soon (mostly a matter of documentation, since I wrote the code for a client who only needed to compile the Z39.50-200x spec): I'd certainly be happy to make a prerelease available to anyone interested. Aaron (asl2 at pobox.com) From adalke at mindspring.com Thu Sep 25 18:04:15 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 25 Sep 2003 22:04:15 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> Message-ID: Raymond Hettinger: > Beauty and clarity are a matter of taste and we differ here. > To some (including me), s[::-1] looks more like line noise > than s.iter_backwards(). Understood. In all this, let me make it clearthat I have a preference for a function over a method, but won't call it a wart of the BFDL thinks otherwise. I point these out because I'm rather detail oriented. > > Also, a variant implementation may be even more concise, > > You must be pretty confident to take on the Timbot's code ;-) Well, I did say "may". I wouldn't really want to use it since inverting the score before the sort is a tricky thing to see and somewhat unexpected. (I'm half expecting some enlightening comment about how negation has subtle interactions with IEEE 754 math -- though I thought the point of 754 was to make naive approaches like mine usually correct. :) > > verfiles = os.listdir('/usr/lib/setup') > > verfiles = [name for name in verfiles > > if name.startswith("slack-version-")] > > I like your version better and recommend you submit it as a patch. > I'll take out the ifilter() comment. But that goes against the pretty good motto of "if it ain't broke, don't touch it." Granted, XP-style tests are supposed to help out with that, but I don't have a /usr/lib/setup where I can test this. > > ] random.shuffle() uses for i in xrange(len(x)-1, 0, -1) > > This isn't a use case. The xrange never returns a 0 while > > the iter_backwards one will. > > It is an important use case. The replacement code is: > > for i in xrange(1,len(x)). iter_backwards() Ahh, right. Didn't think about that. You should include that wording in the PEP. > Whenever the indices have any complexity, the forwards version, > followed by .iter_backwards() is, IMHO, much easier to mentally verify. I agree. When I do need to go backwards I often forgot to get both -1s in place. Ie, I'll do (n, 0) instead of (n-1, -1). Well, don't forgot much and more, but there's some tension in my mind as I worry if I got it correct or not. > BTW, don't underestimate the intensity of resistance to adding > new builtins. For me it's two things: remembering what all these new things do, and attempting to adhere to the 'don't use variables with the same name as builtins' guiding philosophy. I don't adhere to the latter wrt the type named 'file'. > Also, I have a preference for creating something that > is as robust as possible. Making a builtin function that > doesn't apply to all objects; behaves badly with mappings; > and crashes with an infinite iterator is not my idea of robust. The backup which uses __getitem__ and negative offsets does work for all objects, behaves exactly as badly as the existing iter, and doesn't crash with an infinite iterator, no? It's slow, but if you want the performance, make an __riter__. > I really don't understand the overpowering urge to make this a function > and add a new magic method protocol. Why isn't there a similar rage > against dict.iteritems()? Overpowering? My preference is for a function because of: - similaraties to iter, which is also a function - there are many types of iteration orderings, and not all can be special cased methods. - I don't see backwards iteration as all that important As for iteritems, I was annoyed about it because it meant my dictionary-like code would become more complicated to implement, until I came across UserDict.DictMixin, which lets user-defined code implement just a few methods then builds the rest from there. That suggests a UserList.ListMixin might be useful, but it isn't obvious to me that it would be. I also note that items is a method so by similarity it makes sense that iteritems also be a method. Additionally, many things offer forward iteration, while only dicts offer items. Should dicts support riteritems, ritervalues? > Okay, we simply disagree here. That's fine. Yup. I don't think I have anything useful or even interesting to offer to this dicusssion. I also think that with these changes, the PEP is pretty complete and solid. Andrew dalke at dalkescientific.com From wilkSPAM at OUTflibuste.net Wed Sep 3 09:49:11 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Wed, 03 Sep 2003 15:49:11 +0200 Subject: How to accelerate python application GUI speed References: <43e3984e.0309030532.3fe88bbc@posting.google.com> Message-ID: <87n0dmj82w.fsf@flibuste.net> ulysses_dm at yahoo.com.cn (ulysses) writes: > Hi,all > > I use wxPython make a bittorrent client. I find wxPython very slow and > use many many memory. > When app start, it need 19MB memory. I only use common GUI components. > Python is a really good > programming language. But how to do a small,smart, efficency GUI in > win32,it's a big question. An solution is to make a web application and use a tiny browser like kmeleon. bye -- William Dode - http://flibuste.net From post400 at prontomail.com Thu Sep 4 16:30:27 2003 From: post400 at prontomail.com (post400) Date: 4 Sep 2003 13:30:27 -0700 Subject: Code complete electronic version ? References: <871xuyowxv.fsf@pobox.com> <3f573bda.396747703@news.blueyonder.co.uk> Message-ID: alan.gauld at btinternet.com (Alan Gauld) wrote in message news:<3f573bda.396747703 at news.blueyonder.co.uk>... > On 4 Sep 2003 06:01:21 -0700, post400 at prontomail.com (post400) > wrote: > > see how expensive some books are in Europe compared to US. > > Where in Europe? I'm in the UK and prices on Amazon.co.uk are not > significantly higher than the US site (ie nothing like double!) In France ! Have a lokk at this: on amazon.fr ... Prix de vente conseill? au Royaume-Uni* : ?27.42 / EUR 39,61 Notre prix : EUR 39,61 and on amazon.com Code Complete: A Practical Handbook of Software Construction by Steve C McConnell Price: $24.50 which is almost half of 40? ! Ok maybe 40? is not that much but it's just not nice to see such a difference ! > > > is that most american sites don't ship to Europe or the taxes are > > enourmous. > > I've bought several books from the US(Barnes & Nobles, > Amazon.Com, and others). Taxes have never been significant. The > only real snag is the 4-6 week wait for shipment. > > Alan g. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld From tcronj at ananzi.co.za Tue Sep 23 15:41:19 2003 From: tcronj at ananzi.co.za (tertius) Date: Tue, 23 Sep 2003 21:41:19 +0200 Subject: IE or Netscape com access Message-ID: <3f70a1cc$0$64727@hades.is.co.za> I want to use IE or Netscape to print my documents which are in HTML format. Whould com/activex be the way to do it? Are there examples of how I can acieve this? Many thanks Tertius From dyoo at hkn.eecs.berkeley.edu Tue Sep 2 04:31:51 2003 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 2 Sep 2003 08:31:51 +0000 (UTC) Subject: TKinter is driving me crazy! References: <3285.208.224.10.29.1062445601.squirrel@webmail.iserv.net> Message-ID: Cousin Stanley wrote: : | import Tkinter as tk : | : | class GuessWidget(tk.Frame): : | def __init__(self, value, *args, **kw): : | : | tk.Frame.__init__(self, *args, **kw) : | .... : Jp .... : Thanks for posting this example script .... : How does one change the title : of the sub-classed frame ???? Hi Stanley, Frames don't have titles, but toplevels do. Try using the 'title()' method of the toplevel widget. For example: ### from Tkinter import * root = Tk() root.title("Hello world!") frame = Frame(root) Label(frame, text="This is a test! Hello! Can you see this?").pack() frame.pack() mainloop() ### There's more information on this from Fredrik Lundh's "An Introduction to Tkinter". http://www.pythonware.com/library/tkinter/introduction/x9843-style-methods.htm Hope this helps! From python at sarcastic-horse.com Sat Sep 13 09:55:49 2003 From: python at sarcastic-horse.com (python) Date: Sat, 13 Sep 2003 09:55:49 -0400 Subject: datetime: How to get diff between 2 dates in month units? In-Reply-To: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624715@stpmsg00.corp.fairisaac.com> References: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624715@stpmsg00.corp.fairisaac.com> Message-ID: <20030913095549.042d767d.python@sarcastic-horse.com> On Fri, 12 Sep 2003 16:50:53 -0500 "Pettersen, Bjorn S" wrote: > No, but I do have one question..: would diff.months be valid given d1 > and d2 above (which also contain a day part)? I'm not certain I understand. I guess what I'm trying to say is that I want a datetime object that has months as its smallest unit, just like datetime.date has days as its smallest indivisible unit. > If so, what would it be given the dates 3/1/2001 - 1/30/2001; i.e. is a > month 1/12 of a year, or until the same day next month (with special > rules for end-of-month)? My data is monthly-frequency, so when I do 2001m3 - 2001m1, it would return 2. > If you answer no to the first question then your very close to a (year * > 100 + month) representation... I will probably end up using something like this. But before I build that, I wanted to check around if I wasn't missing a more obvious solution. Also, after I've got monthly data objects, I'm going to need to be able to do the same thing for quarterly data. > -- bjorn > (time series data is fun ;-) Amen to that. Especially when it comes to handling weird stuff like leap years and holidays that can be in different months. From stuff at slinkp.com Thu Sep 4 15:24:49 2003 From: stuff at slinkp.com (Paul Winkler) Date: 4 Sep 2003 12:24:49 -0700 Subject: Zope mailing lists dead ? References: Message-ID: "Gilles Lenfant" wrote in message news:... > Hi, > > I didn't receive anything from the various Zope mailing lists I should > receive. > > zope at zope.org > zope-cmf at zope.org > zope-dev at zope.org > > Other subscribers can confirm or have I got problems ? One or two messages have trickled through... but the server is clobbered with the latest round of sobig. See this thread: http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=7h3ptigg8ul.fsf%40pc150.maths.bris.ac.uk&prev=/groups%3Fhl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26q%3Dgroup%253Acomp.lang.python%26btnG%3DGoogle%2BSearch The zope lists are run at python.org so they are affected by this. From jdhunter at ace.bsd.uchicago.edu Thu Sep 4 15:03:12 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 04 Sep 2003 14:03:12 -0500 Subject: quick and smart way for parsing a CSV file? In-Reply-To: <731fc603.0309031242.4e5493ce@posting.google.com> (soundwave56@yahoo.ca's message of "3 Sep 2003 13:42:24 -0700") References: <731fc603.0309031242.4e5493ce@posting.google.com> Message-ID: >>>>> "Hank" == Hank writes: Hank> Hi, I have a CSV file from excel that looks like this Hank> (simplified): Hank> name,description,type1,type2,name,filename test1,this is a Hank> test,0.000,1.000,, test2,another Hank> test,1.000,0.000,newname,filename test3,this is a Hank> test,0.000,1.000,, test4,this is a test,0.000,1.000,, Hank> test5,this is a test,0.000,1.000,, test6,this is a Hank> test,0.000,1.000,, I posted some code recently to parse CSV into a dictionary where you can extract rows or columns by key or index number. It's not exactly what you asked for, but might help http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&selm=mailman.1058882602.32583.python-list%40python.org&rnum=4 John Hunter From timh at zute.net Wed Sep 10 10:41:23 2003 From: timh at zute.net (Tim Hoffman) Date: Wed, 10 Sep 2003 22:41:23 +0800 Subject: Reportlab Image object opens filehandles In-Reply-To: References: Message-ID: <3f5f36de$1@news.highway1.com.au> Have a look at limit (or in csh ulimit) 256 open files is the default limit for a user/process. (all about conserving resources) you can make this bigger (much bigger ;-) assuming you have permissions. Rgds Tim Michael Schmitt wrote: > Hello. > > I am trying to build a pdf document using: > --- > from reportlab.platypus.flowables import Image > lst = [] > for filename in imageFiles: > I= Image(filename, width= 300, height= 300) > lst.append(I) > --- > Creating an Image object seems to open a filehandle, so if the size of > imageFiles increases, I get "IOError: [Errno 24] Too many open files" on a > Solaris machine, where the number of simultaneously opened filehandles > seems to be limited to roughly 255. > > Is there a way to produce a pdf document with a large number of images > without running into the problem of too many open filehandles? > > Thanks for any hints. > Michael > > From peter at engcorp.com Fri Sep 19 20:06:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Sep 2003 20:06:53 -0400 Subject: os.environ and os.path.chdir References: Message-ID: <3F6B9A1D.EB4F9558@engcorp.com> Yun Mao wrote: > > How to make changes to os.environ and os.path.chdir still effective after > I run the script? Currently, the changes are only good within my script. I > would like the shell who called python myprog.py also gets the change.. Is there some Python programming course where all you guys are coming from lately? :-) This question seems very popular this week. As John Roth just replied to one of your potential classmates :-), "Look at the thread "Setting Environment Variables" that started yesterday in the early morning." ... and note that the comments about environment variables apply equally to the current directory, as both are properties of the calling shell and can be changed only by scripts run by that shell. -Peter From http Fri Sep 5 13:40:00 2003 From: http (Paul Rubin) Date: 05 Sep 2003 10:40:00 -0700 Subject: in Ram database? References: <3f58bae9$0$13287$626a54ce@news.free.fr> Message-ID: <7xn0djrv67.fsf@ruckus.brouhaha.com> Romuald Texier writes: > Why not just use Dictionaries, or an object tree? Why do you want tables or > SQL abstraction if it is "in-memory"? Nothing else but your app will be > able to access the "live" data, anyway. I think it would be useful to have an in-memory database that could be used by multiple processes through a shared memory interface. From gventer at africonnect.com Tue Sep 2 14:12:40 2003 From: gventer at africonnect.com (Gerhard Venter) Date: Tue, 02 Sep 2003 19:12:40 +0100 Subject: win32all for 2.3 In-Reply-To: References: Message-ID: <3F54DD98.80200@africonnect.com> Michael Geary wrote: >Gerhard Venter wrote: > > >>I need to get *win32all* for 2.3 quite urgently. It should be at >>http://starship.python.net/crew/mhammond/win32/Downloads.html >>However, the starship site seems to have disappeared, even from DNS. Is >>there any other way I could get the file? >> >> > >Starship is up, but it seems to have dropped out of DNS. Try the IP address >instead: > >http://217.160.219.194/crew/mhammond/win32/Downloads.html > >And win32all-155 (for Python 2.3) is here: > >http://217.160.219.194/crew/mhammond/downloads/win32all-155.exe > >-Mike > > > Thanks, I got the file earlier from Alan Kennedy, but it is good to know the site still exists. I posted a reply to thank him, but I have only just realised this list is one of those where if you just hit Reply it does not go to the whole list.... Gerhard From SPAMtbone at freegates.be Sat Sep 20 17:37:56 2003 From: SPAMtbone at freegates.be (Philip) Date: Sat, 20 Sep 2003 23:37:56 +0200 Subject: DB2 driver for windows Message-ID: <3f6cc89b$0$1122$6c56d894@feed0.news.be.easynet.net> Hi, i'am looking for a db2 driver for windows the DB2 servers runs on as400 if that makes any difference. Thanks, Philip From toby at rcsreg.com Sun Sep 14 16:42:34 2003 From: toby at rcsreg.com (Tobiah) Date: Sun, 14 Sep 2003 20:42:34 GMT Subject: checking type of my own objects Message-ID: Hi, I have a module that defines a few classes. one of them is Event. If I do: e = Event() print type(e) I get back: now to check to see whether a given object is an Event or not, I could parse the string output of type, but that does not seem correct. What is the best way to check the type? Thanks, Tobiah From patrick at fraley.de Tue Sep 23 10:21:31 2003 From: patrick at fraley.de (Patrick W. Fraley) Date: Tue, 23 Sep 2003 16:21:31 +0200 Subject: TKinter and findertools.launch Message-ID: Hi everybuddy, I am experiencing some really weird problems when using the findertools from an Tkinter app (MacPython 2.2.3). When I start another application (i.e. a Browser), the Application starts behaving strangely. It does not seem to continue until I switch back and forth between it and the Tkinter app. Only then will it continue (for example load a web page). Has anybuddy here experienced something like this? Where can I find some more info on the findertools, besides giving me a list of methods and what they are used for? I tried the MacPython mailinglist, but never get any answers. Please help. TIA Patrick W. Fraley From mnations at airmail.net Thu Sep 11 15:59:38 2003 From: mnations at airmail.net (Marc) Date: 11 Sep 2003 12:59:38 -0700 Subject: Canvas - Rectangle. Is there an easy way to detect if you're inside? Message-ID: <4378fa6f.0309111159.7a9bb539@posting.google.com> Hi all, I've been using the canvas quite a bit lately, and I am wondering if I am just missing a quick trick somewhere. With most canvas objects you can bind then to mouse functions and quickly determine if you are selecting them. However, the rectangle (and I'm sure all other objects that aren't solid) only register if you actually hit the frame of the object, if it's transparent. If you fill it with color then it will register anywhere. At the moment I am doing as series of if-then statements involving coordinates and the positions that the rectangles hold to determine if the mouse is somewhere inside the rectangle. However it would be much simpler if there was a way to quickly recognize the internal area of a rectangle using a canvas function. Is there an easier way to do this? I've looked at all the canvas functions and none really make this process easier unless the rectangle can auto-recognize itself. Many Thanks, Marc From rudy.schockaert at pandora.be Tue Sep 30 15:04:35 2003 From: rudy.schockaert at pandora.be (Rudy Schockaert) Date: Tue, 30 Sep 2003 19:04:35 GMT Subject: intercepting smtp email In-Reply-To: References: <5Uieb.49566$Lw6.2263065@phobos.telenet-ops.be> Message-ID: <7tkeb.49855$CW5.2223199@phobos.telenet-ops.be> It seems you've looking where I've earlier this week ;-) I'm affraid there's nothing for Python on Windows yet. .r!kard wrote: > Google rules: > http://home.student.utwente.nl/g.v.berg/btk/ This one is for unices only, no Windows. > http://pycap.sourceforge.net From the Todo.txt file: * Make this work on Windows. I briefly struggled with compiling using VC7 under Win XP using winpcap_ and LibnetNT_. No luck, and was getting some rather interesting errors about missing header files which appeared to be where they should be :-/. > http://www.ghaering.de/python/unsupported/pylibpcap/ This could be a candidate if it were available for Python 2.3.x . It's for Python 2.2 only now. > http://aspn.activestate.com/ASPN/Mail/Message/python-list/1578279 Further down the thread: http://aspn.activestate.com/ASPN/Mail/Message/python-list/1578500 Gerhard H?ring wrote: > http://www.ghaering.de/python/unsupported/pylibpcap/ > I'll check if the sniff.py example will work, too. It doesn't look like it does. I may have introduced a subtle bug or some more changes are needed to make it useful under win32. If anybody wants to continue the win32 port, it's open source and you can continue where I stopped. -- Gerhard Out of luck again :-( > > *pheew* that was some real hardcore Googeling I can tell you... > > .r!kard >> >> >>>>>>>I want to write an NT service that will intercept any outgoing smtp >>>>>>>traffic, like Norton Antivirus does. Can anyone tell me how I can >>> >>>do >>> >>>>>>>something like this in Python? I do not know how to intercept the >>>>>>>outgoing traffic, specifically. >> > > From b.preusing at web.de Sat Sep 6 15:07:59 2003 From: b.preusing at web.de (Bernd Preusing) Date: Sat, 06 Sep 2003 21:07:59 +0200 Subject: Need help on UNICODE conversion Message-ID: <5lbklvgtlm6l4e1n51tnbin151drrh4410@4ax.com> Hi, today I (Python beginner) ran into a problem:^ I have a JPG file which contains some comment as unicode. After reading in the string with s=file.read(70) from file offest 4 I get a string which is shown as 'UNICODE\\0x00\\ox00K\\0x00o' and so forth in the debugger (using Komodo). How do I convert such string to a real unicode string and to a windows_1252 or latin1 afterwards? I know it's a text with german umlauts. I tried this: if rawdata[:7] == "UNICODE": ustring = rawdata[7:] us2 = unicode(ustring, "windows_1252") as2 = us2.encode("windows_1252") self.dic["ComUNI"] = rawdata But all I get on each stage is a normal string with lots of \\0x00. TIA Bernd From Alexandre.Fayolle at logilab.fr Fri Sep 26 12:38:34 2003 From: Alexandre.Fayolle at logilab.fr (Alexandre Fayolle) Date: Fri, 26 Sep 2003 18:38:34 +0200 Subject: [ANN] pylint-0.2 Message-ID: <20030926163834.GP28349@calvin> Logilab has released pylint-0.2 What's new? ----------- In addition to a large number of bug fixes, this release adds two new checkers, for missing encoding declaration, and for FIXME comments. Zope support was improved. About Pylint ------------ Pylint is a lint-like tool for Python code. It performs almost all the verifications that pychecker does, and additionally can perform some stylistic verification and coding standard enforcements. The checked code is assigned a mark based on the number and the severity of the encountered problems. The previous mark of a given piece of code is cached so that you can see if the code quality has improved since the last check. URLs ---- Homepage: http://www.logilab.org/projects/pylint Download: ftp://ftp.logilab.org/pub/pylint/pylint-0.2.tar.gz -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From raindog at no.spam.net Tue Sep 16 00:52:43 2003 From: raindog at no.spam.net (Rain Dog) Date: Tue, 16 Sep 2003 04:52:43 GMT Subject: a quick program to download tv listings References: <1f0bdf30.0309102237.d29f0de@posting.google.com> Message-ID: In article <1f0bdf30.0309102237.d29f0de at posting.google.com>, prochak at netzero.net (Erik Lechak) wrote: > Is there anyone out there that has written anything in python to > download tv listings (no XML)? ... I wrote the test > program below and it works. I am just curious if anyone has a more > robust python implementation before I take the time to add all the > bells and whistles. Here's a version that uses an HTMLParser and does its own filtering by channel, rather than setting a cookie. Some sample output: % tvsearch "college football" news College Football ABC 7 12:30 PM Sat Sep 13 College Football CBS 2 12:30 PM Sat Sep 13 Eyewitness News ABC 7 4:00 PM Sat Sep 13 CBS 2 News at 5:00 CBS 2 5:00 PM Sat Sep 13 College Football ABC 7 5:00 PM Sat Sep 13 Channel 4 News NBC 4 5:00 PM Sat Sep 13 CBS Evening News CBS 2 5:30 PM Sat Sep 13 ---------- 8< ---------- 8< ---------- 8< ---------- 8< ---------- #!/usr/bin/env python import formatter, re, time, urllib from htmllib import HTMLParser # Channel lineup (leave empty to search all channels) CHANNELS = [2, 3, 4, 5, 7, 9, 11, 13, 18, 22, 30, 32, 34, 35, 36, 39, 40, 41, 42, 43, 44, 46, 50, 57, 62] # Yahoo location code LOCATION = 'us_CA57315' # Yahoo TV listing URL YAHOO_TV_URL = ('http://tv.yahoo.com/grid?lineup=' + LOCATION + '&starttime=%(epoch)d&.intl=us') class Show(object): '''Just a structure to hold program information''' __slots__ = ('name', 'channel', 'station', 'start', 'end') def __init__(self, **kwargs): for k, v in kwargs.items(): self.__setattr__(k, v) def __str__(self): showTime=time.strftime('%I:%M %p %a %b %d', time.localtime(self.start)) if showTime[0] == '0': showTime = ' ' + showTime[1:] return '%-35s %8s %-4d %-s' % (self.name, self.station, self.channel, showTime) class YahooTVParser(HTMLParser): '''Minimal HTML parser for Yahoo TV listings''' showRE = re.compile('\/tvpdb\?d=tvp&id=(.*)') showInfoRE = re.compile('(\d*)&cf.*channels=us_([^&]*).*' '&chname=([^\+]*)\+(\d+)&progutn=(\d*)') def __init__(self): HTMLParser.__init__(self, formatter.NullFormatter()) self.shows = [] self.inShow = 0 def start_a(self, attrs): # handler '''If the tag's HREF matches showRE, record the show info.''' self.newShow = None self.showName = '' # Check if the HREF matches a show. for k, v in attrs: if k == 'href': url = ''.join(v.split('\n')) if self.showRE.search(url): m = self.showInfoRE.search(url) if m: # Create a new Show--its name isn't known yet. self.newShow = Show(start=float(m.group(5)), channel=int(m.group(4)), station=m.group(3)) self.inShow = 1 break def end_a(self): # handler '''If done with a show, record its name and add it to the list.''' if self.inShow and self.showName: self.newShow.name = self.showName self.shows.append(self.newShow) self.inShow = 0 def handle_data(self, text): '''Handle the data between, e.g., and tags.''' if self.inShow: self.showName += text def getGrid(epoch): url = YAHOO_TV_URL % vars() parser = YahooTVParser() parser.feed(urllib.urlopen(url).read()) parser.close() return parser.shows def findShows(patterns): isMatchingShow = None if patterns: nameRE = re.compile('|'.join(['(%s)' % n for n in patterns]), re.I) if CHANNELS: def isMatchingShow(show): return (show.channel in CHANNELS) and nameRE.search(show.name) else: def isMatchingShow(show): return (nameRE.search(show.name) is not None) elif CHANNELS: def isMatchingShow(show): return (show.channel in CHANNELS) THREE_HOURS = 3 * 60 * 60 ONE_WEEK = THREE_HOURS * 8 * 7 startTime = int(time.time()) endTime = startTime + ONE_WEEK for h in range(startTime, endTime, THREE_HOURS): allShows = getGrid(h) # Print matching shows sorted by starting time. if isMatchingShow is not None: shows = [(s.start, s) for s in allShows if isMatchingShow(s)] else: shows = [(s.start, s) for s in allShows] shows.sort() for t, s in shows: print s def main(): import os.path, sys args = sys.argv[1:] if '-h' in args: sys.stderr.write("Usage: %s [PATTERN]...\n" % os.path.basename(sys.argv[0])) sys.exit(1) try: findShows(args) except KeyboardInterrupt: pass sys.exit(0) if __name__ == '__main__': main() From NO-MAIL at hotmail.com Tue Sep 23 00:33:27 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 23 Sep 2003 04:33:27 GMT Subject: Thoughts on PEP315 References: Message-ID: If it was up to me, I would propose until : as an equivalent to: while not : and loop: for the enless loop, instead of ugly 'while True'. M-a-S PS. And I'd introduce the switch construction of course. From max at alcyone.com Mon Sep 8 12:55:21 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Sep 2003 09:55:21 -0700 Subject: More Comments on Python Redesign References: Message-ID: <3F5CB479.318229AC@alcyone.com> Tim Parkin wrote: > Just in case people didn't realise, there is a py-design-forum at :- > ... Didn't you just say you were done talking about this on comp.lang.python? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The enemy of my enemy is my friend. \__/ (an Arab proverb) From jhf at hex.no Tue Sep 2 16:45:30 2003 From: jhf at hex.no (Jørgen Hermanrud Fjeld) Date: Tue, 2 Sep 2003 22:45:30 +0200 Subject: Compiler C or Python? In-Reply-To: <7h3vfsbh1bg.fsf@pc150.maths.bris.ac.uk> References: <20030826213316.GA7285@unpythonic.net> <7h3vfsbh1bg.fsf@pc150.maths.bris.ac.uk> Message-ID: <20030902204530.GA23853@hex.no> On Tue, Sep 02, 2003 at 11:37:03AM +0000, Michael Hudson wrote: > jhf at hex.no (J?rgen Hermanrud Fjeld) writes: > > And in general, if should want to alter the Python compiler, should > > I start with the Python or C version? > > Whichever's easiest :-) This is usually the Python one. > Then I shall start with that one. Are there any other arguments/reasons to choose one or the other? That is technicalities one should consider. > A toy that might come in handy is an interactive mode (based on > code.InteractiveConsole) that compiles input with the customized > compiler. Thanks, this can make the task at hand a lot easier. > > As far as I can see from your email the Python version is easier to > > modify, but why two compilers? Isn't that a lot to maintain? > > The Lib/compiler/ package is pretty slow. Also, making that the only > compiler might lead to irritating bootstrapping problems (which I now > see Jeff talked about...). Yes, but the code it generates will be fast enough for my purposes. Do you happen to know how consistency between the compilers is maintained? Sincerely J?rgen From duncan at NOSPAMrcp.co.uk Fri Sep 26 05:13:25 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 26 Sep 2003 09:13:25 +0000 (UTC) Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: Grant Edwards wrote in news:slrnap5gfa.aol.grante at localhost.localdomain: >> I _think_ (can't be sure...) that at a C-libraries level the switch >> occurred either between DOS 1.0 and 1.1, or at the time of release of >> 2.0. > > I don't think 1.0 had a hierarchical filesystem at all did it? That is correct, originally DOS like CP/M didn't have a concept of directories, all file access used file control blocks. When they added directories in Dos 2.0 they added new int21 calls which supported the directory paths and these have always accepted either forward or reversed slashes as path separators interchangeably. Dos 3.0 added an int21 call to canonicalize pathnames which included converting all forward slashes to backslashes. -- 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 lorenb2 at bezeqint.net Thu Sep 11 03:48:39 2003 From: lorenb2 at bezeqint.net (Bill Loren) Date: Thu, 11 Sep 2003 09:48:39 +0200 Subject: socket error 10061 Message-ID: <00b701c37839$1d3027b0$6400a8c0@EVOD31> Hi, Upon running my program via the command line I get the above error. Weirder is the fact that upon running the same code from within ActiveState's PythonWin's IDE - I get no error and the code smoothly completes its running. any idea ? thx ~B From PeterAbel at gmx.net Tue Sep 30 18:05:32 2003 From: PeterAbel at gmx.net (Peter Abel) Date: 30 Sep 2003 15:05:32 -0700 Subject: eval's local arguement ignored? References: <56e1eff0.0309230923.1215833f@posting.google.com> <21064255.0309260745.6d3d5650@posting.google.com> <56e1eff0.0309300536.51fdf2b0@posting.google.com> Message-ID: <21064255.0309301405.5ac8f828@posting.google.com> jseb at cs.mcgill.ca (Jean-S?bastien Bolduc) wrote in message news:<56e1eff0.0309300536.51fdf2b0 at posting.google.com>... > > **kwa** is the solution! > > > > In your factory-function *foo* you have to declare *a* > > keywordarguement which is initialized with a. > > > > >>> def foo(): > > ... a=1 > > ... f=lambda x,a=a:a*x > > ... return f > > Not exactly what I'm looking for, I'm afraid. A more complete picture > is this: I'm writing a class such as this: > > class Foo: > def __init__(self, fnc, **params): > ... > def evaluate(self, val) > ... > > That has to be instantiated as, e.g.: > > x = Foo( 'lambda x : a*x', dict( a = 2. ) ) > > so that "x.evaluate( 5. )" will return, in this case, "2.*5.". > > The approach you describe will certainly work, but the thing is that > this class will have to be used by people who don't necessarily know > Python (yet). So I would really like the lambda function's parameter > list to always be the same, whatever you put on its RHS. > > Once again, I don't understand why the "eval", as described above with > "globals" and "locals" arguments specified, will not work. Is there a > way to modify a function's closure? > > Thanks, > JSeb Sorry, I missunderstood you. Since your last post I learned the further more two parameters of the eval-function. I'm even not sure if I checked the problem entirely, but let me try to explain what I think I may have understood. In the following function the eval-statement doesn't really need the locals() to evaluate the lambda-function. It really needs to tell the lambda where is its parent's namespace - what is by default the modules-namespace which one calls *globals()* - where to search for variables when not found in the locals(). >>> def new_fn(fn_string): ... a=99999 ... print locals() ... local_fun=eval(fn_string,globals(),locals()) ... return local_fun ... I think the locals() are always the variables of a function's body - in the above case of the function *new_fn*. >>> f=new_fn('lambda x:(x*a,locals())') will show that: {'a': 99999, 'fn_string': 'lambda x:(x*a,locals())'} So the following let us know what locals() means for the lambda-function: >>> a=0 >>> f(10) (0, {'x': 10}) >>> But *a* is found in the global-scope. I'm not sure if this really helps you and the only workaround for me is something I posted to you the last time. What makes me more confused is the following example, where the lambda-function is declared explicitly. >>> def new_fn(): ... a=99999 ... print locals() ... local_fun=lambda x:(x*a,locals()) ... return local_fun ... >>> f=new_fn() {'a': 99999} >>> a=0 >>> f(10) (999990, {'a': 99999, 'x': 10}) >>> But I think that's what you did already. PS: I here someone whispering something of *nested scopes*. Regards Peter From Mike at DeleteThis.Geary.com Sun Sep 28 20:09:37 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sun, 28 Sep 2003 17:09:37 -0700 Subject: IDE with a specific feature References: Message-ID: > I don't want to get into a 'which IDE is the best' conversation. I'm > looking for an IDE that has the ability to view 2 (or more) > methods/functions within the same module simultaneously. > > I've looked at the screen shots for Komodo, Wing, BlackAdder, etc and > it is not obvious that any of them have this feature. > > This is something I got use to in Smalltalk and have found it quite > useful when working on several methods that work closely together. It's good to be able to view more than one part of a source file, and of course you'll want to rule out IDEs that don't meet your basic requirements. But there are a lot of other things that can make you love or hate an IDE--so why don't you download a few of them and try them out for yourself? I tried all of the IDEs mentioned in this thread and quickly found that Komodo fit my taste the best. (And it does let you view two portions of a file at once--although it would be better if it allowed more splits than that.) I like PythonWin too, but the others didn't do it for me at all. Not getting into a "which IDE is best" conversation :-) but a couple of my requirements were ClearType support and an interface that wouldn't be confusing when switching back and forth between a Python IDE and Microsoft Visual Studio. Obviously, other people will have different priorities. So go try out a few different IDEs--it didn't take very long for me to do that. -Mike From jzgoda at gazeta.usun.pl Mon Sep 29 13:46:36 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 29 Sep 2003 17:46:36 +0000 (UTC) Subject: warnings during installation of python2.3.1 on SCO_SV 3.2v5.0.5 References: Message-ID: Roger Erens pisze: >> uname -X > > System = SCO_SV > Node = ontwik2 > Release = 3.2v5.0.5 > KernelID = 98/07/02 > Machine = i80386 > BusType = ISA > Serial = 5FL004745 > Users = 30-user > OEM# = 0 > Origin# = 1 > NumCPU = 2 > >>ld -V > SCO UNIX Development System Release 5.1.1A 27Jul98 > 395 /usrdir/rogere/Python-2.3.1 >>cc -V > SCO UNIX Development System Release 5.1.1A 27Jul98 I wouldn't be surprised, SCO systems is absolute crap. And they object reality. http://lwn.net/Articles/51374/ -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:jarek at jabberpl.org http://zgoda.jogger.pl/ From alkirke1 at comcast.net Tue Sep 9 20:53:47 2003 From: alkirke1 at comcast.net (Al Kirke) Date: Wed, 10 Sep 2003 00:53:47 GMT Subject: OT: Americans love their guns References: Message-ID: "Nick Vargish" wrote in message news:m3k78j6v5e.fsf at tanelorn.bandersnatch.org... > Steve Lamb writes: > > > Do this simple test. Get an egg timer (or any other timing device). > > Now set it to 4, maybe 5 minutes. Now lock yourself in the closet. > > Counter-test: Imagine your seven-year-old son finding your gun and > shooting and killing your five-year-old daughter while you're working > in your study. Impossible. The son had been taught safe gun handling on the pistol range w/ a .22 starting at aged five, and would come and tell you that firearm had not been safely stored. Al From pf_moore at yahoo.co.uk Mon Sep 8 12:16:37 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 08 Sep 2003 17:16:37 +0100 Subject: Ternary operator References: <3F5B6404.BD1A9709@engcorp.com> Message-ID: <4qznp862.fsf@yahoo.co.uk> Bob Gailer writes: >>It seems to me that the majority did want some kind of ternary operator, but >>the large number of options prevented any one from being the clear winner. I >>would wager that if the BDFL had picked his favorite from any of the most >>popular options and said, "Now vote yes or no on *this* syntax", he would >>have seen that clear majority he was looking for. Actually, that's what Guido did do at first (IIRC). He proposed the "expr1 if cond else expr2" form. The *community* argued against this specific syntax, rather than concentrating on the semantics, and it was only then that the discussion fragmented into endless discussions over what syntax to choose. >>I suppose this is all water under the bridge now, since the PEP stated that >>this was the community's one and only chance. I just can't help but think >>that the voting system guaranteed the outcome--but it's Guido's language and >>it was certainly his call to make. The voting system was designed by the community and so we can't blame anyone but ourselves for "rigging" the outcome... > THANK YOU. Your analysis of the process brings me a sense of relief. I > was also confused and frustrated by its failure to deliver what > (obviously) many of us wanted. My feeling is that there is a majority who want a ternary operation (not including me, but what the heck) but that there is violent disagreement on the syntax. > I was dismayed by the process being defined as "the community's one > and only chance" and then set up to fail. Well, I see it as Guido not really wanting to spend the time implementing a ternary operator. He offered to, in any case, if the community was in favour (and the PEP originally stated precisely what he was offering). But with the proviso "if you don't like this, I'm not going to offer again". I doubt he was surprised that the result was a lot of discussion over syntax, rather than an acceptance of the offer. The general history of this issue is one of endless discussion with no agreement. Maybe the majority would like the feature, but that same majority can't agree on syntax. The PEP just forced one more iteration of that process, and documented the result (lots of heated discussion, but no solid conclusion). Maybe it's a shame that Guido's original PEP wasn't preserved unaltered. What's there now doesn't capture the flavour of the original. Of course, all of this is only my recollection, and just as prone to being wrong as anyone else's... Paul. -- This signature intentionally left blank From tjreedy at udel.edu Sat Sep 27 12:56:25 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2003 12:56:25 -0400 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> Message-ID: "Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:bqeanvgel9ra3va44j090bmn2l126t340g at 4ax.com... > On Fri, 26 Sep 2003 17:28:02 -0400, "Terry Reedy" > wrote: > >A square-bracketed subscript (index/key) is a *single* object, in this > >case a tuple. The contents of the tuple are irrelevant (for this > >code). Any tuple will be echoed: > > I didn't see any sign that he wasn't aware of that. Since you both missed the key points I tried to make, I will try be a little clearer by being much wordier. When a sequence is indexed with a slice expression, the interpreter tries to immediately slice it. From 2.2.1: >>> def f1(): return c[:-1] ... >>> dis.dis(f) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_GLOBAL 0 (c) 9 LOAD_CONST 1 (-1) 12 SLICE+2 13 RETURN_VALUE No intermediate slice object is even constructed. Since stop is negative, 'SLICE+2' must look up the length to do the subtraction. When the index is a tuple, the interpreter does not try to slice: >>> def f2(): return c[:1,:1] ... >>> dis.dis(f2) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_GLOBAL 0 (c) 9 LOAD_CONST 0 (None) 12 LOAD_CONST 1 (1) 15 BUILD_SLICE 2 18 LOAD_CONST 0 (None) 21 LOAD_CONST 1 (1) 24 BUILD_SLICE 2 27 BUILD_TUPLE 2 30 BINARY_SUBSCR 31 RETURN_VALUE For BINARY_SUBSCR, the contents of the tuple only matter when the tuple is hashed. Roberto prevented this with his custom __getitem__() method. Since slices do not hash, a tuple of slices is normally useless and would give a TypeError if hashing were attempted. > I would have expected, given that the tuple contains slice objects > constructed from the multiple-slice notation, that the same > translations would be performed on the slices that are inserted into > the tuple that are applied when the single slice is created. Slice objects and tuples thereof were added for use by Numerical Python so it could slice multidimensional arrays stored as a single linear array. The length used for start or stop subtraction is the length of each dimension, which is typically different for each dimension. Subtracting the total length is the *wrong* thing to do for multiple slices. Only custom code can know the correct factors of that total length to use for each component slice. In Roberto's example, there is no single slice created. See disassembly above and comment below. > That is, whether the single or multiple notation is used, and whether > the slice objects are placed in a tuple or not, they are constructed > from the tuple notation Sorry, wrong. Tuple notation for single slices givea a different result. >>> c[:-1] # this is *NOT* tuple notation Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute '__len__' >>> c[:-1,] # (slice(None, -1, None),) DING! Here is how to get consistency. Add the tuplizing comma. Terry J. Reedy From neil.padgen at mon.bbc.co.uk Mon Sep 8 10:59:53 2003 From: neil.padgen at mon.bbc.co.uk (Neil Padgen) Date: Mon, 08 Sep 2003 14:59:53 +0000 Subject: Massive unit test vs MySQL References: Message-ID: On Friday 05 September 2003 15:17, Richard Wesley wrote: > In article , > Neil Padgen wrote: > >> On Thursday 04 September 2003 20:35, Richard Wesley wrote: >> >> > p = os.popen('mysql -u uid -ppassword mydatabase', 'w') >> > p.write(sql_commands) >> >> p.close() > > Yeah, I tried this, but it had no effect. > > The odd thing is that the process list cleans up _immediately_ when > the > script terminates. Maybe this is some sort of gc problem? > What is in sql_commands? Maybe there is a semicolon missing from the end, which might be causing mysql to wait for input. -- Neil -- From gh at ghaering.de Fri Sep 19 07:54:00 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 19 Sep 2003 13:54:00 +0200 Subject: Access to Win API In-Reply-To: <0c58d500ac94b27d7f8ff87a2a59f6e1@news.meganetnews.com> References: <0c58d500ac94b27d7f8ff87a2a59f6e1@news.meganetnews.com> Message-ID: <3F6AEE58.20904@ghaering.de> Ladv?nszky K?roly wrote: > Thanks for your help. I remember once I tried a Python cookbook sample code > that included ctypes but now 'import ctypes' does not work. > Should ctypes come together with the 2.3 installation? [...] No, it's a third-party module that you need to download and install. Google says it's at http://starship.python.net/crew/theller/ctypes/, but the Starship seems to be down ATM [1]. Maybe somebody has the ctypes installer for Python 2.3 and can send it to you. I only have ctypes 0.2 for Python 2.2 here ATM. -- Gerhard [1] Probably the recent virus flood bogs down the server :-/ From mwilson at sarcastic-horse.com Tue Sep 30 14:18:44 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Tue, 30 Sep 2003 14:18:44 -0400 (EDT) Subject: printing to files in python Message-ID: <35005.199.169.240.132.1064945924.squirrel@svr1.turboweb.net> Hi- I want to print stuff like: >>> "d1: %s, probability: %0.2f" % (d1, prob) to a file, but when I do: >>> str = "d1: %s, probability: %0.2f" % (d1, prob) >>> outfile = open("out.txt", "w") >>> outfile.write(str) I get errors. What am I missing? From aleax at aleax.it Fri Sep 26 04:03:50 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 08:03:50 GMT Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: Grant Edwards wrote: ... > Nope. AFAIK, it's always accepted '/'. I did C programming on DOS for > years, and I always used '/' since it was too error working with string > literals in C that contain '\'. Those same programs seemed to run fine > under Windows. > >> Does anyone know when that change occurred? Was it with the introduction >> of support for long filenames in NT and Win95? > > I'm not aware that there has ever been a "change". '/' has been OK since > the early DOS days. I _think_ (can't be sure...) that at a C-libraries level the switch occurred either between DOS 1.0 and 1.1, or at the time of release of 2.0. It's hard to say, because MS didn't release a C compiler as a product back then; however, it seems that, internally, they used C compilers running on their Unix machines (presumably their own version of Unix, named Xenix, which they later sold to SCO) to generate some parts of the DOS stuff of that age. The original QDOS ("Quick and Dirty OS") that they bought out and resold as DOS 1.0 surely had no knowledge of forward slashes -- it was basically CP/M disassembled, hacked and reassembled (all quite illegally of course). Just as surely, DOS 2.0 had that knowledge (Allen had also hacked into it some Unix idioms such as I/O redirection and pipes -- some "pipes", redirecting to a temporary file and then back out of it!, but syntactically Unixoid -- and more generally made it an uneasy mixmash of some concepts and practice from the CP/M world plus a little from Unix traditions); and so did the first C compiler, self-hosted on DOS, that MS later sold to the public (having bought it, I believe, from Lattice). Alex From tim.hochberg at ieee.org Fri Sep 12 13:56:57 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Fri, 12 Sep 2003 10:56:57 -0700 Subject: Python / C: small runtime difference? In-Reply-To: <3f5e0963.369221532@news.blueyonder.co.uk> References: <3f5e0963.369221532@news.blueyonder.co.uk> Message-ID: Alan Gauld wrote: > On Tue, 9 Sep 2003 15:54:41 +0200, "Martin Schneider" > wrote: > > >>for i in range(len(fileList)-1): >> for j in range(len(fileList)-i-1): >> if fileList[j+1] < fileList[j]: >> tmp = fileList[j] >> fileList[j] = fileList[j+1] >> fileList[j+1] = tmp > > > I think you might tweak that by doing: > > fileList[j],fileList[j+1] = fileList[j+1],fileList[j] > > which misses out the intermediate tmp assignment. Careful here. You'd have to time it to be sure, but the above is probably slower than what you're replacing. The reason is that the above creates an anonymous tuple then unpacks it. More or less equivalent to: tmp = (fileList[j+1], fileList[j]) fileList[j], fileList[j+1] = tmp I'd be tempted to do it anyway in all but the tightest loops as I think it's clearer. -tim > If you are gonna tweak the C you might as well tweak the > Python too! (But not with a real python, they tweak back > hard! :-) > > Alan G. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld From cnetzer at sonic.net Sun Sep 7 05:10:31 2003 From: cnetzer at sonic.net (Chad Netzer) Date: Sun, 07 Sep 2003 02:10:31 -0700 Subject: OT: Americans love their guns In-Reply-To: References: Message-ID: <1062925831.1855.10.camel@adsl-209.204.179.133.sonic.net> On Sat, 2003-09-06 at 00:43, Steve Lamb wrote: > If guns were such a overriding factor why is it the UK has as high > if not higher rate of gun related violence than the US? You still haven't responded to the rebuttals of this statement. On the face of it, it appears made up. Can you explain? -- Chad Netzer From aleax at aleax.it Fri Sep 26 04:33:08 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 08:33:08 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> Message-ID: <8RScb.169633$R32.5449258@news2.tin.it> Raymond Hettinger wrote: >> And I still think you don't need it often enough to put it in the >> builtin namespace, so the function should go in the itertools module. > > If you have a magic method, __riter__, then the corresponding > function needs to be a builtin. They go hand in hand. The > core parts of the language need to be usable without having > to know about itertools. I have already seen module copy presented as a counter-example to your assertion, and I'd like to add module pickle as a second, and I hope decisive, counter-example. It is, to put it simply, utterly false that functions corresponding to magic methods "need to be builtins": it's *perfectly* all right for such functions to live in standard library modules. Oh, and let's not forget module sets: the __as_immutable__ and __as_temporarily_immutable__ magic methods, that are used when making a set of sets, or checking for a set's membership in another set, can be seen as yet another example (and in this case there is no wiggling out of it by claiming that the magicmethod/NON-builtin correspondence is a historical/legacy thing, as the BDFL approved module sets.py, with just this usage, so very recently). I second the motion that function riter, with check for __riter__ and all, should live in module itertools. Reverse iteration is a RARE need -- far rarer than copying or even pickling -- and there is no real reason to burden __builtins__ with a function for it. Alex From martin at v.loewis.de Sun Sep 21 15:41:16 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Sep 2003 21:41:16 +0200 Subject: convert Unicode to lower/uppercase? In-Reply-To: <299f1138.0309210940.32e9acfe@posting.google.com> References: <299f1138.0309210940.32e9acfe@posting.google.com> Message-ID: jallan wrote: > But that really doesn't work properly. According to Unicode specs and > German usage the uppercase of "?" is actually "SS", that is the single > character "?" should uppercase to two characters. Can you cite exact chapter and verse of the Unicode specs that say so? According to the Unicode database, http://www.unicode.org/Public/UNIDATA/UnicodeData.txt has neither an uppercase mapping, nor a lowercase mapping. Also, in German, the uppercase mapping of ? is of ongoing debate. For example, the Duden from 1919 says | F?r ? wird in gro?er Schrift SZ angewandt [...]. Die Verwendung | _zweier_ Buchstaben f?r _einen_ Laut ist nur ein Notbehelf, der | aufh?ren mu?, sobald ein geeigneter Druckbuchstabe f?r das | gro?e ? geschaffen ist. The usage of SZ has only been eliminated in the recent change of the amtliche Rechtschreibung. Regards, Martin From alanmk at hotmail.com Fri Sep 19 06:02:39 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 19 Sep 2003 11:02:39 +0100 Subject: Python ISPs References: <924a9f9c.0309181224.374a5bef@posting.google.com> Message-ID: <3F6AD43F.8BEFC26E@hotmail.com> Paradox wrote: > Does anyone know of some ISPs that have Mod_Python installed. Check out the Python hosting Wiki. The "SpecializedCommercialHosts" page lists three hosting companies that support mod_python. http://www.python.org/cgi-bin/moinmoin/SpecializedCommercialHosts If you know of any others that are not listed there, then please add the information to that wiki. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From stefnin at alussinan.org Thu Sep 25 06:40:12 2003 From: stefnin at alussinan.org (Stéphane Ninin) Date: 25 Sep 2003 10:40:12 GMT Subject: pilconvert script disappeared ? Message-ID: Hello, I have just installed python 2.3 with many other libs, including PIL, (from http://www.pythonware.com/products/pil/), version 1.1.4 for Python 2.3b1. Am I dreaming or has the script pilconvert.py disappeared from the free PIL distribution ? Can I find it somewhere else ? Thanks, & regards, -- St?phane Ninin From aleax at aleax.it Sun Sep 28 07:13:35 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 28 Sep 2003 11:13:35 GMT Subject: Meta programming question References: Message-ID: Bruce Dickey wrote: > I've read a number of the meta progamming articles. I have not found > what I am looking for. I want to override assignments to variables which > are in the module namespace (not object members -- no classes involved). > Can this be done? No (not without, as somebody already suggested, rewriting substantial portions of Python's C-level implementation). A module-level statement = evaluates the expression, and sets the name to refer to its value -- no ifs, no buts, no overriding, and nothing to do with metaprogramming. Alex From max at alcyone.com Wed Sep 10 03:52:31 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 10 Sep 2003 00:52:31 -0700 Subject: How to instatiate a class of which the name is only known atruntime? References: <3F5ECDE2.40206@mxm.dk> Message-ID: <3F5ED83F.48E7DB60@alcyone.com> Max M wrote: > Is there any reason not to use a standard factory pattern for this? It > is the normal approach. Because introspection means you don't have to keep a separate list of all possible values updated. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ An undevout astronomer is mad. \__/ Edward Young From dakidd at sonic.net Thu Sep 25 14:55:34 2003 From: dakidd at sonic.net (Don Bruder) Date: Thu, 25 Sep 2003 18:55:34 GMT Subject: Another Python rookie trying to port to C/C++ question. Message-ID: A week or two ago, I asked here about porting Python to C. Got some good answers (Note 1) but now I've got another question. Actually, more a request for clarification of a topic that both the Python tutorial and docs leave a touch murky to my understanding. Dictionaries/"dict" types... Am I understanding/interpreting correctly when I go with the idea that a "dict" variable can be looked at as (effectively) two parallel arrays? Something like this C construct: struct DictStruct { char *KeyArray[]; ValType ValArray[]; } Where "ValType" would be likely be a union, to allow assigning/retrieving the actual values correctly depending on what their individiual types were, and "" is just that: Some more-or-less arbitrarily selected value that provides enough space to handle all expected numbers of key/value pairs? Similarly, would something like: struct DictStruct { char Key[25]; ValType Value; DictStruct *PrevDictEntry; DictStruct *NextDictEntry; } (again, ValType would probably be a union to cover each type of value that might be wanted in the dictionary - but in this case, Key directly contains the Key's name) then building a double-linked list of struct DictStructs end up behaving at least reasonably like a Python "dict"? I expect that either will be a reasonable facsimile of how Python handles dicts, with, of course, the corresponding overhead (which may be surprisingly little, I'm thinking... but I have yet to code that part, so I may find out it's going to be a nightmare) of "We want the value that goes with key, so we've got to walk the KeyArray[] until we find a match, then extract the value from the other array", or a similar procedure for the doubly-linked list. Or am I way out in left field with the way I'm RTFM? (Note 1) Along with quite a bit of entirely unwelcome "Python evangelism" -- Which part of "I don't care how good, bad, or indifferent Python is compared to C/C++, or any other language. I want this Python code to be written in C/C++, end of discussion." wasn't clear enough for those of you who took it upon yourselves to preach (including the idiot who decided to spew a relatively impressive (as such things go) string of insults about how stupid I am, how far up my ass my head is, and how pathetic my family all the way back to Adam must be for producing such a throwback because I've got no interest in adopting "the perfect language...") at me on the merits of Python, both on group and in-mailbox? -- Don Bruder - dakidd at sonic.net <--- Preferred Email - SpamAssassinated. Hate SPAM? See for some seriously great info. I will choose a path that's clear: I will choose Free Will! - N. Peart Fly trap info pages: From gh at ghaering.de Mon Sep 1 12:08:24 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 01 Sep 2003 18:08:24 +0200 Subject: Python Documentation? In-Reply-To: References: <3f533f3d$0$32467$edfadb0f@dread16.news.tele.dk> <3f5357a0$0$32519$edfadb0f@dread16.news.tele.dk> Message-ID: <3F536EF8.7040808@ghaering.de> Cc-ing python-list because it might be of general interest. Cameron Laird wrote: > In article you write: >>[1] If nothing else, I could then add "does anybody actually directly >>use this cra^wmodule?" to the page for ftplib <0.1 wink> >> > > What *is* going on there? Do you use Twisted instead? I needed a quick way to "stat" files via FTP (it's a mirror script that synchronizes the maps, etc. on Unreal Tournament 2003 gameservers). As ftplib lacks any methods whatsoever to parse the output of the LIST command, I searched for something higher level and found ftputil [1], which is quite nice to use. Unfortunately, the stat command of ftputil was very inefficient (it basically does a LIST for every stat() you call), so I extended it with a statall() method for my mirror script. Being annoyed with Python's ftplib I wasn't surprised that the ftpcp function in the module didn't work for me, while calling the Linux ftp client (well, whatever /usr/bin/ftp was at that machine ;-) worked fine when using the appropriate PROXY commands. My current solution creates a script that is then fed into the ftp client program. Yes, I need an appropriate ~/.netrc file :-/ It's quite a hack, but I needed a solution fast ;-) The good part was [2] that I learnt that FTP actually has one useful feature: server-to-server copy, which has the additional benefit of not creating any significant traffic on the controlling client. -- Gerhard [1] http://www.ndh.net/home/sschwarzer/python/python_software.html [2] thanks to deltab on #python From mwilson at the-wire.com Fri Sep 26 16:05:18 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 26 Sep 2003 16:05:18 -0400 Subject: Reduce need of backslash References: Message-ID: <+vJd/ks/KDtU089yn@the-wire.com> In article , Nicolas Fleury wrote: >I was wondering if the need for \ could be reduce in the language. For >example, could a line ending with = or + could be automaticly considered >incomplete? I've taken to exploiting brackets, that is, [], () and {}. Python won't let a line break break a bracketed expression. Lately I'm not above throwing in extra pairs of parentheses where I feel that escaped line breaks would annoy me. Regards. Mel. From bac at OCF.Berkeley.EDU Mon Sep 22 01:45:35 2003 From: bac at OCF.Berkeley.EDU (Brett C.) Date: Sun, 21 Sep 2003 22:45:35 -0700 Subject: python-dev Summary for 2003-09-01 through 2003-09-15 Message-ID: <3F6E8C7F.3080106@ocf.berkeley.edu> python-dev Summary for 2003-09-01 through 2003-09-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from September 1, 2003 through September 15, 2003. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the twenty-fifth summary written by Brett Cannon (with school looming on the horizon). All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the original text file. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on something mentioned here. PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. contents:: .. _last summary: http://www.python.org/dev/summary/2003-08-16_2003-08-31.html ===================== Summary Announcements ===================== Summary is nice and short this time. More people went on vacation (although Martin came back and so that helped to pick up the traffic a little). I skipped covering some threads that are due for PEPs since those will be more in-depth then anything I write. I should give fair warning that starting on the 22nd of September I will begin school. I am hoping that it will not be difficult and I will have a carefree time in school. But if my workload becomes a burden the Summaries might suffer. I hope they don't, though, and I am going to do my best to make sure that doesn't happen. ========= Summaries ========= --------------------------------------- If It Isn't Documented, Is It a Secret? --------------------------------------- Some undocumented methods in readline were discovered by Philip Eby. He asked if this was on purpose and whether he should submit a bug report on the lack of documentation. Guido told him to go ahead and submit the bug report. If you ever find something undocumented in the Python source code and there is nothing suggesting the code is meant to be hidden from the user (it's for internal use, a comment says it is experimental, etc.), then please file a bug report! Contributing threads: - `Undocumented functions in 'readline' module `__ ----------------------------------------------------------------------------------------- "You are more trouble than you are worth!", screamed the micro release to the new feature ----------------------------------------------------------------------------------------- The topic of what should be backported for micro releases (with Python 2.3.1 looming on the horizon) came up. Originally minor improvements were allowed in if they didn't break backwards compatibility. And of course bugfixes have been as well as long as they didn't break code that came to depend on the buggy behavior (really depends on how long the bugginess has been there and how well-known it is). But then the point of OS X 10.3 possibly becoming the largest install base of Python of any version (it will be 2.3) came up. With rough estimates being thrown around of 5 million installs in about a year's time, the point that making it difficult to run Python 2.3.x code on that size of an install base would be bad. For instance, if some small new feature was added to 2.3.1 then any code using that feature would not be able to run on a virgin install of OS X 10.3 (and considering that this is Mac it should not be expected that most users will want to, let alone know how, to add a secondary install of Python since the original is used by the OS and thus should not be overwritten). It looks like a more conservative patching scheme will be taken with micro releases. Bytecode will also continue to work between releases. Guido has always unofficially held that position but now it has been vocalized. Contributing threads: - `Documenting branch policy `__ ---------------------------------------------- PyPy "Berlin" sprint (29th Sep - 4th Oct 2003) ---------------------------------------------- Just what the title says: there is going to be a sprint_ for PyPy_ in Berlin from September 29 to October 4. Read the email for more specific details on goals and such. .. _sprint: http://www.python.org/cgi-bin/moinmoin/SprintPlan .. _PyPy: http://codespeak.net/pypy/index.cgi?home Contributing threads: - `PyPy "Berlin" sprint (29th Sep - 4th Oct 2003) `__ -------------------------------- Away with you ambiguous imports! -------------------------------- A discussion on how to create a hierarchy of loggers in the standard library led to the idea of having a way to cause an import to come directly from the standard library and thus remove any ambiguity from a relative import grabbing a similarly named module from the local package. Barry Warsaw said he was thinking of writing a PEP on this idea. Contributing threads: - `Consistent logging in the standard library `__ --------------------------------------------------- Quick: want to give a Python talk at Linuxworld NY? --------------------------------------------------- If you are interested in what the title asks, then read the email for some details. Contributing threads: - `Quick: want to give a Python talk at Linuxworld NY? `__ ------------------------------------------- Be careful about saying something is "easy" ------------------------------------------- A word of advice about saying something is "easy" on python-dev: if you say that you should make sure you can back up that claim because otherwise you will be told to write the "easy" patch and that will be the end of the discussion. Contributing threads: - `Making python C-API thread safe (try 2) `__ -------------------------- Parsing dates for datetime -------------------------- There was some talk about coming up with some code to parse dates for the datetime module. It was kind of hand-wavy since there are multiples chunks of code that can do that in the standard library. If you have an opinion on this (or anything for that matter), make sure to make a post to `comp.lang.python`_ about it. Contributing threads: - `datetime issues `__ From max at nospam.com Fri Sep 26 13:56:47 2003 From: max at nospam.com (max) Date: Fri, 26 Sep 2003 17:56:47 GMT Subject: PIL: Group4 Tiff Images In-Reply-To: References: Message-ID: Doug Tolton wrote: > I have been able to load a group4 tif into the wxImage class, but I > get tag errors when attempting to do so. > > Is there a better way of working with Group4 Tiffs? I have a huge > volume of Tiffs and decompressing them isn't a good option for me. > > Any ideas on the best way to tackle this problem? many :) I don't know where PIL stands on TIFF, but almost all C-based libraries rely on libtiff package in the end. Depending on how it is compiled you will get different results for TIFFs with nonstandard tags (which is probably your case). If you are willing to tinker you can recompile wx's version of libtiff. Also, how about reporting to the PIL people? G4 is the most popular tiff codec, they would want to know if it's broken. What are you doing with all those tiffs anyway? BTW, you did a nice job obfuscating your email, but it is plaintext in the header - you have to reconfigure you mailer to hide it... From davidcfox at post.harvard.edu Tue Sep 23 10:41:39 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 23 Sep 2003 14:41:39 GMT Subject: Indexing list of lists In-Reply-To: <95b4b9ac.0309230541.32800875@posting.google.com> References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <95b4b9ac.0309171233.21f4c07@posting.google.com> <95b4b9ac.0309180950.30b44d89@posting.google.com> <95b4b9ac.0309230541.32800875@posting.google.com> Message-ID: Hilde Roth wrote: >>Only if all the sublists are of the same length, which is guaranteed for >>a multi-dimensional array, but not for a list of lists. > > > This is a red herring. No, it's not. It is a hint that, despite the similarity of notation between Matrix[i][j] and NestedList[i][j], there is something fundamentally different between the two. See below for another example. > > >>What do you expect a[;1] to return if a = [[], [1, 2, 3], [4], 5]? > > > Whatever error python returns if you ask, e.g., for (1 2 3)[4]. > > Hilde Okay, here's a better example which I thought of just after I posted my previous reply: Given x = [[1, 2], [3, 4]] the statement x[0] = [5, 6] will result in a nested list x = [ [5, 6], [3, 4] ]. If you think of x as a multi-dimensional array represented by a nested list, then I've just replaced a row of the original array 1 2 3 4 with a new row, yielding 5 6 3 4 If we had an x[;0] notation, then you would expect to be able to do the same thing to replace a column: x[;0] = [7, 8] Unfortunately, there is no pre-existing list representing the first column of x, so x[;0] has to return a new list [1, 3], and assigning to that new list has no affect on x. Again, my point is that nested lists are a fundamentally different structure than multi-dimensional arrays. For simple things like x[i][j], you can use a nested list to represent a multi-dimensional array, but if you actually want to manipulate a two-dimensional array like a matrix, you are better off using a class designed for that purpose, like the ones defined in Numeric Python. David From tim.parkin at pollenationinternet.com Sun Sep 7 08:41:38 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 13:41:38 +0100 Subject: Comments on Python Redesign In-Reply-To: <20030907123549.GA1011@mail.earthlink.net> Message-ID: <002201c3753d$6797c3c0$0a00a8c0@JASPER> >A suggestion for use with any Python webpage redesign would be to >consider using an automated webpage checker such as the one at > > http://validator.w3.org/ > >That validator does checks on webpages and reports on the pages >"conformance to W3C Recommendations and other standards." > >-Jim Rutledge IT'S AN IMAGE!!!!! (aargh!!!) ;-) From garry at sage.att.com Wed Sep 17 16:47:06 2003 From: garry at sage.att.com (Garry Hodgson) Date: Wed, 17 Sep 2003 20:47:06 GMT Subject: smtplib question Message-ID: <2003091716471063831625@k2.sage.att.com> how do i use smtplib to send mail to someone with "cc" to someone else? if i just include the "to" addressees in the call to smtplib.sendmail(), and put the others in the "Cc" header fields, only the "To" recipients get the mail, thought the mail headers look right. but if i also add the "Cc" folks to the list of recipients in the call to smtplib.sendmail(), it arrives at their mailer with their address listed on both the "To" and "Cc" header fields. what i want is for everyone on the "To" or "Cc" list to get the mail, and for the mail headers to reflect this. please respond off-list. i had to give up following comp.lang.python for lack of time. thanks ---- Garry Hodgson, Technology Consultant, AT&T Labs Be happy for this moment. This moment is your life. From amk at amk.ca Sat Sep 20 20:54:43 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 20 Sep 2003 19:54:43 -0500 Subject: spam killing with poplib References: Message-ID: <5sadncwNpZ1Oa_GiRTvUqQ@speakeasy.net> On Sat, 20 Sep 2003 14:39:49 -0700, Dave Kuhlman wrote: > Almost all the spam I'm receiving has an attachment whose file > type is one of .exe, .bat, .com, .scr, .pif, and a few others. Is > there a way for your Python script to check for that? How do you > do that in Python. If you're using Exim as a mail server, you can compile Exim with Python as an extension language (elspy.sf.net). Rejecting all messages with executable attachments is then a matter of creating an exim_local_scan.py file containing: from elspy import execontent_simple def local_scan (fd, headers, info): # Trash executables execontent_simple.local_scan(fd, headers, info) # For now, do no other scanning return --amk From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Sep 25 18:36:11 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 25 Sep 2003 23:36:11 +0100 Subject: Another Python rookie trying to port to C/C++ question. References: Message-ID: <1lp6nv8b9vnlu453dgaegqujqegmp9chc6@4ax.com> On Thu, 25 Sep 2003 18:55:34 GMT, Don Bruder wrote: >Dictionaries/"dict" types... > >Am I understanding/interpreting correctly when I go with the idea that a >"dict" variable can be looked at as (effectively) two parallel arrays? >Something like this C construct: > >struct DictStruct > { > char *KeyArray[]; > ValType ValArray[]; > } Sort of, in a sense, but not quite. The types of items within the dictionary (both key and value) are not constrained. This is no problem as all Python objects are held using a reference scheme. So (assuming that a pair-object scheme is used in the dictionary) the struct will be defined much like... struct DictPair { PyObject *Key; PyObject *Data; } The items will almost certainly be held in a single 'array' of pair objects. The Python dictionaries use hashing. I don't know the details of the hashing used. Anyway, there are many ways to handle dictionary-like data structures. C++ has the std::map template, which uses a form of binary tree called a red-black tree (the red-black refers to a partial balancing system). Tree-based mappings can be slightly more flexible than hashing (for instance, a tree can be 'walked' in sorted order - the hashing process does not preserve relative ordering) but hashing tends to be faster. An interesting approach to dictionary-like objects is the ternary tree. This is rather like cascading binary trees - each subtree identifies one character and cascades into the subtree that finds the next character. The third link in the 'ternary' is the 'I've identified one character and moving on to the next' link. A ternary tree can be faster than hashing - in particular at deciding that a particular key is not present (hashing needs to calculate a hash over the whole tree before looking up the result - a ternary tree search may fail at the first character, without looking at the whole key). Digital trees (or tries, IIRC) can be even faster still - but wastes a lot of memory. In a digital tree, each node has an array subscripted by character/digit code of pointers to the next subtree. Multiway trees (most often used on disk for database indexes - B trees and B+ trees being types of multiway trees) may well be appropriate in main store on modern desktop machines with caching and virtual memory. If these options are just too complicated, sorted arrays can be extremely effective as long as you don't have too many items. The C++ library includes std::vector (a resizable array) and binary search algorithms which can ease the implementation. Odds are, if you are translating Python to C++, you should use an std::map to replace a dictionary. There are some different assumptions, though. Dictionaries assume that the key is hashable, but don't require relative comparisons ('<', '<=' etc). The std::map requires relative comparisons. This simply arises out of the different approaches - Python using hashing and C++ using binary trees. Going from Python to C++, 99 times out of 100 this is not a problem. From C++ to Python there is the minor issue that Python dictionaries can't be _directly_ iterated in sorted order, though there are certainly easy ways around that. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From bgailer at alum.rpi.edu Wed Sep 10 11:22:39 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 10 Sep 2003 09:22:39 -0600 Subject: advice choosing IDE In-Reply-To: References: Message-ID: <6.0.0.22.0.20030910092042.03b57778@66.28.54.253> At 10:01 PM 9/9/2003, Page wrote: >I find Wing IDE to work wonders. >Has all the essentials you'll need. And works on linux & win32 ;) >http://archaeopteryx.com/wingide In response to an older post I downloaded wingide. I found it very difficult to get started. There seems to be a lot of independent windows that open, and its very hard to determine what do to where and when. Is there some GOOD tutorial? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From claird at lairds.com Fri Sep 5 12:46:29 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 05 Sep 2003 16:46:29 -0000 Subject: Automated code generation References: <3f58ba15$0$97267$edfadb0f@dread12.news.tele.dk> Message-ID: In article <3f58ba15$0$97267$edfadb0f at dread12.news.tele.dk>, Max M wrote: >Yesterday there was an article on Slashdot: >http://books.slashdot.org/article.pl?sid=03/09/04/1415210&mode=flat&tid=108&tid=126&tid=156 > >It is about automatic code generation. . . . >Or os it useless in a language as dynamic as Python? > > >regards max M > Yes, it's largely useless in a language as dynamic as Python. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From jjl at pobox.com Thu Sep 11 13:15:47 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Sep 2003 18:15:47 +0100 Subject: GET and POST References: Message-ID: <877k4fgsak.fsf@pobox.com> Brian Victor writes: > franck wrote: > > i know how to do a GET. > >:) i have this example. > > my contact tell my i must do a get AND a post :/ > > > > GET to fuse param et POST for the others. > > Without knowing urllib, I would infer from the rest of the code that > you'd want to do something like this: > > getparams['fuseaction'] = '*****' > postparams['num_card'] = '*****' > > getparams = urllib.urlencode(getparams) > postparams = urllib.urlencode(postparams) # may not be necessary > f = urllib.urlopen("http://bidule.com?%s" % getparams, postparams) It seems unlikely that that's what is required (but you never know...). If the OP can post the HTML or a link, it would be rather easier to say what the problem is! John From CousinStanley at hotmail.com Tue Sep 2 18:08:47 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 2 Sep 2003 15:08:47 -0700 Subject: TKinter is driving me crazy! References: <3285.208.224.10.29.1062445601.squirrel@webmail.iserv.net> Message-ID: Daniel ... Applying the whatEver.master.title() method works out OK ... A slight modification of the last example script you posted ... import sys module_this = sys.argv[ 0 ] from Tkinter import * tk_Root = Tk() button = Button( tk_Root , text = "Press me !" ) button.pack() button.master.title( module_this ) tk_Root.mainloop() # ---------------------------------------------- And a slight modification of Jp's script also works OK to add the desired title ... if __name__ == '__main__' : import sys module_this = sys.argv[ 0 ] gw = GuessWidget( random.randrange( 100 ) ) gw.master.title( module_this ) gw.mainloop() # ---------------------------------------------- Thanks again for the information and steering me toward the master ... -- Cousin Stanley Human Being Phoenix, Arizona From daniel.dittmar at sap.com Fri Sep 26 11:18:27 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Fri, 26 Sep 2003 17:18:27 +0200 Subject: PEPs link gone from the Python homepage? References: Message-ID: David Abrahams wrote: > Since a significant part of Python is only documented in PEPs, I am > disappointed to see that they can't be easily found. Where are they? Don't bother with site navigation, google "pep site:python.org". Daniel From chasm at rift.sytes.net Sun Sep 21 11:22:20 2003 From: chasm at rift.sytes.net (Julian Tibble) Date: Sun, 21 Sep 2003 15:22:20 +0000 (UTC) Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> Message-ID: In article , Julian Tibble wrote: > recursion - 4.7 > xrecursion - 0.5 > reduction - 5.2 > xreduction - 5.2 Whoops!!!! Make that iteration, not recursion. I do know the difference...honestly :) Julian From python at sarcastic-horse.com Tue Sep 16 17:08:53 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Tue, 16 Sep 2003 17:08:53 -0400 (EDT) Subject: When passing functions as args, how to pass extra args for passed function? Message-ID: <65365.199.169.240.132.1063746533.squirrel@svr1.turboweb.net> When I pass a function as an arg, like for map(...), how do I pass args to use for that function? If I have a function like this: def pretty_format(f, fmt='%0.3f'): return fmt % f I want to use it with map() like this: formatted = map(pretty_format, unformatted_list) #exept I want fmt='%4.5f' !!! I need to figure out how to pass a non-default value for fmt. How do I do that? From john at rygannon.com Thu Sep 18 18:03:41 2003 From: john at rygannon.com (John Dean) Date: Thu, 18 Sep 2003 22:03:41 GMT Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> <3y7ab.1043$Od.78860@twister.tampabay.rr.com> <3f697584$0$10966$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3f6a2bd3$0$10998$fa0fcedb@lovejoy.zen.co.uk> Hi You may or may know that BA is based on the Qt GUI Application Toolkit, so you problem with the duel monitor set up is something I shall take up with Trolltech. Unfortunately, none of use at theKompany run a duel monitor setup so it is something that we are not aware of. Thank you for bring up this problem and I will get back to you with a solution or our proposal for a solution -- Best Regards John From mpeuser at web.de Sat Sep 6 04:51:19 2003 From: mpeuser at web.de (Michael Peuser) Date: Sat, 6 Sep 2003 10:51:19 +0200 Subject: OT: best book in years References: <87k78mlrp3.fsf@pobox.com> Message-ID: "John J. Lee" schrieb im Newsbeitrag news:87k78mlrp3.fsf at pobox.com... > "Michael Peuser" writes: > > > "Juha Autero" > > > > > > G?del, Escher, Bach: an Eternal Golden Braid. It may not be the best > > > book I read and not very useful, but I'd recomend reading it anyway. > > > > > > > I made the same recommendation some minutes ago, but without your > > reservation. In fact I might even come to the conclusion it *is* the best > > book I have read ;-) > > > > Why do you think it is not very useful? What do you think of Shakespeare by > > the way? > > [not directed at me, but I'll answer anyway...] > > Well, it dazzles you with all sorts of fascinating stuff, and succeeds > at being something wonderful purely in its own right, but it fails to > actually solve any problems. Of course, nobody can really tell him > off for that, since his subject matter revolves around what appears to > be the biggest unsolved mystery in human knowledge. > Absolutly true. But I have the feeling that whenever anyone will explain the reason ofor everything to us in 1000 years it will be absolutly useless as well. In fact I had the vision of some multimedia event, laying in a hospital bed, connected to artificial nutrition, wearing headphones, listening to Bach's music and reading Hofstadter. Excuse me for being such hillarious. Kindly Michael P From tebeka at cs.bgu.ac.il Tue Sep 30 06:57:08 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 30 Sep 2003 03:57:08 -0700 Subject: isNumber? check References: Message-ID: <33803989.0309300257.63284ced@posting.google.com> Hello Rob, > How do I check if a value is a number in Python? > > One way is (x == type(1)) and (x == type(1.2)) and (x == > type(2387482734274)) and ... > > but this seems kludgy. Any better way? Same thing, different way: from types import IntType, LongType, FloatType def is_num(n): return n in (IntType, LongType, FloatType) HTH. Miki From aleax at aleax.it Mon Sep 22 11:42:45 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 15:42:45 GMT Subject: questions about a C++ COM object accessed in Python via win32com References: Message-ID: T.T.H. wrote: > Hi > > I am coding a C++ COM object which I want to access in Python. For that > I do have some detail questions and need help since I am not that familiar > with the documentation itself of Python and win32com yet. > > > 1. > How do I know that... > > import win32com.client > > ...was successful or not? If it fails, it raises an exception -- so, if you want to handle the failure, you try this statement in the try clause of a try/except statement. That is reasonably similar to C++'s exception (syntax apart), so the concept shouldn't be too alien. > 2. > In my COM object I do have the following C++ function: > > STDMETHODIMP CMyTestObjekt::Connect() > { > if (m_boolReadyToConnect == false) { > return E_FAIL; > } > return S_OK; > } > > How do I know in Python whether I got back a S_OK or an E_FAIL? Or is this E_FAIL translates into an exception. > whole concept wrong and I should better make an additional return value > like: > > MyFunktion(......., [out, retval] BOOL *pVal); (declaration in the IDL) This would be much more COM-idiomatic, unless the failure IS an exceptional event, something that SHOULD not happen in a well-functioning system and probably the result of mis-configuration or hardware malfunctioning. > > 3. > If I execute the following command... > > MyObject = win32com.client.Dispatch("MyCOM.MySuperCOMObject") > > ...what is the return value from which I know whether it was successful? Guess...?-) Yep: if it's not successful it raises an exception! > Or what can be the ""content"" of "MyObject" afterwards? If an exception wasn't raised, MyObject is an instance of some class (you need not care about which one...) on which you can call methods (which will be "proxied" to the actual C++-implemented COM object). > > 4. > If I have a function in Python in which I call the (global) COM Object, > what "if" do I have to use to know whether the COM object already had > been allocated? I tried the following but that didn't work: > > def foo(): > if MyObject == None: > print "COM not there yet" > else: > print MyObject.Message If name "MyObject" has never been bound, trying to access it will... I give you three guesses... *raise an exception*! However, I _would_ suggest that in this case you set MyObject=None at a global level and test as above (except, use "Myobject is None" rather than ==) -- that is more idiomatic in Python. Alex From tim at remove_if_not_spam.digitig.co.uk Tue Sep 23 14:47:10 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Tue, 23 Sep 2003 19:47:10 +0100 Subject: Try/except vs. if/else References: <3F70598E.8020500@bu.edu> Message-ID: On Tue, 23 Sep 2003 11:10:49 -0400, Shu-Hsien Sheu wrote: >Hi, > >In my understanding, using try/except rather than if/else is more >pythonic. Rule of thumb: when the block of code is still doing what it's supposed to do, use if/else. If it's failing to do what it's supposed to do, use try/except. "except" should be an /exception/! >However, sometimes it is difficult to use the later. >For example, I want to search for a sub string in a list composed of >strings. It is considered "possitive" if there is a match, no matter how >many. > >my_test = ['something', 'others', 'still others'] > >case 1: try/except > >hit = 0 >for i in my_test: > try: > i.index('some') > hit = 1 > except ValueError: > pass I'd reckon that to be a bad use of try/except; the "exception" is a perfectly normal case. >case 2: if/else > >hit = 0 >for i in my_test: > if 'some' in i: > hit = 1 My /guess/ is that this would be faster than case 1, as well as clearer! >It seems to me that in a simple searching/matching, using if might be >better and the code is smaller. Try/except would have its strengh on >catching multiple errorrs. However, problems occur if the criteria is >composed of "or" rather than "and". For instance: > >if (a in b) or (c in b): > *do something > >try: > b.index(a) > b.index(c) > *do something >except ValueError: > pass > >The above two are very different. Yes. The first is clear and concise, the second is verbose and unclear! Also the second could mask a genuine ValueError if a, b, or c is an evaluation rather than a simple variable, so you'd think that neither a nor c was in b when in fact you have no idea: something went invisibly wrong and you never actually completed the search. So try/except /only/ when something has gone wrong and you need to go into some sort of recovery or termination, /not/ for routine tests. From geoff at gerrietts.net Fri Sep 12 00:45:48 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 11 Sep 2003 21:45:48 -0700 Subject: Overlaying transparent images with PIL In-Reply-To: <7d3dc526.0309111903.2a4a044@posting.google.com> References: <7d3dc526.0309111903.2a4a044@posting.google.com> Message-ID: <20030912044548.GB10167@isis.gerrietts.net> Quoting Fearless Freep (joconnor at cybermesa.com): > > Anyway. I have a basic image and I need to overlay an image on top of > it and let some of the basic image show through. Just as an aside the > images are not of the same size and the top image needs to be pasted > over the underlying image at an offset from the origin. What you want is to convert both your images (or at least the top one?) to an RGBA image. The RGB are the color codes, and the "A" is the alpha layer. The alpha layer specifies how opaque each pixel should be, 0 being transparent and 255 being opaque. If you convert the GIF you're using into an RGBA image, this should work. The problem with GIF is that it's not really 'transparent', the pixels are actually colored. There's just a special marker in the GIF file format that allows you to identify one of the colors as "transparent". I believe the PNG file format actually provides a full four-layer model with variable transparency, but I'm a long way from expert or even knowledgable in these affairs. I just know what's worked for me before.... Best of luck! --G. -- Geoff Gerrietts http://www.gerrietts.net/ "If I were two-faced, would I be wearing this one?" --Abraham Lincoln From mpeuser at web.de Fri Sep 5 16:51:10 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 22:51:10 +0200 Subject: Why the 'self' argument? References: Message-ID: "Grzegorz Staniak" > I'm a newbie Python user, a systems administrator - I've been trying > to switch from Perl to Python for administrative tasks - and one thing > I cannot understand so far is why I need the special 'self' (or anything > esle) argument in class method definitions. You probably do not mean "class methods"; this a technical term in OOP. The Python class basics are *very* similar to the implementation of Perl classes!! You should not have much problems.... Kindly Michael P From aleax at aleax.it Tue Sep 30 13:28:20 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 30 Sep 2003 17:28:20 GMT Subject: query References: <2003929-93022-80040@foorum.com> Message-ID: Terry Reedy wrote: > "drn" wrote in message > news:2003929-93022-80040 at foorum.com... >> as we are going to develop a educational s/w for children at > preprimary level > > My daughter started with simple games at about age 3, so I know this > can be productive. Ditto (and now she's just started university -- telecom engineering:-). >> -----shall we go for individual terminals with Linux 7.3, and with a > minimum of > around 600 MB of free space,Minimum requirement for RAM > 32 MB. >Minimum requirement for Hard Disk 2.1GB, > > The cheapest machines you can buy in US (about $600) have much more > than this. With duplicate machines, any program you develop on one > will run on all. Wrong! You may be thinking of *general-purpose* "machines", but it seems to me drn may not need general-purpose machines. See: http://info.lindows.com/webstation/ -- $169 base price, runs Linux (lindows version) from CDROM ("unbreakable", "virus-proof":-), 800 MHz processor, 256 MB RAM, no hard disk, no floppy, but with good audio and video, and 10/100 Ethernet. Basically you point its browser to wherever (presumably on the local LAN) the specialized server (which I would suggest writing in Python with Twisted, or perhaps with apache+webware) lives, and off you go. (If you want speakers, they're $5 extra; so is each of keyboard and mouse, and a screen [monitor] is also extra -- $120 for 15", $143 for 17"). I'm not quite sure what the OP means by "Linux 7.3" (there is no such animal -- the next coming release of Linux will be 2.6; he may be thinking of some specific DISTRIBUTION of Linux, such as Mandrake, RedHat, SUSE -- I think 7.3 is very old for each of those, of course by different degrees since each keeps their own numbering;-), but I suspect Lindows OS 4.0 will be fine for him. If you do want a hard-disk in addition, admittedly the cheapest that you can add is 40GB, making the total (with speakers, keyboard, mouse AND 40 GB HD) $262. Still a fair bit less than $600 -- but I suspect (no direct experience with these webstations yet) that you could more cheaply get the diskspace from the central server via NFS anyway (as to how to configure and startup the machines to get their NFS shares, when the boot is always from CDROM, that's the part I don't know -- I suspect you may be able to save such config info on a floppy, the drive being $12 and taking the machine cost to $196 sans monitor -- $316 with a 15" monitor, $339 with a 17" monitor instead). Given that the machines are advertised to come with the OpenOffice suite, I guess/assume there must be SOME way for you to get disk space (e.g. on the LAN) to save your work on -- be it NFS, SMB, or whatever. >>There will be no networking even among machines at one location. > > I think this would be a mistake. Network cards cost US$10-20. An > 8-port hub or router < $200, I think. When you write a program, it > will be *much* easier to install on other machine with a network. The > same will be mostly true for files downloaded from Internet. Yes, it would be a disaster to forego the advantages of networking. Note that the above-mentioned "webstations" CRUCIALLY rely on the LAN to be usable -- and, like just about all computers these days, they come with 10/100 ethernet connectivity built-in anyway. I have seen 5-port 10/100 switches sold in stores, *VAT INCLUDED*, for $50 or less around here (so I'm sure they're cheaper in the US) -- a few meters of cable, and off you go. >> -----which lanuage do you suggest - c/c++ or any browser based > software like >> php/python. > > Python is not browser based. It is a complete standalone language > just like C/C++. It also has many free add-ons available, like > PyGame, which you might > find useful for games and other graphics work. Absolutely. But Python is PERFECTLY suitable for writing special purpose webservers -- or serverside applications that run together with apache -- which might be the best way to arrange the OP's goals. It's simply a more powerful AND simpler language than PHP, much higher-level than C, and MUCH simpler than C++. The only alternatives to Python which I think might be worthy of the OP's attention (if in his environment it should be easier to find programmers for those alternative languages) would be other languages of similar power and semantically high level: Ruby, Smalltalk, Common Lisp, O'CAML, Dylan, Haskell... out of all of these, Ruby and Python are the only two that can be learned FAST by typical programmers (i.e., unless you start with programmers already skilled in some of the other ones), and Python is overall a bit simpler, roughly of the same power of Ruby, IMHO more suitable for multiple programmers to work together (because it emphasizes uniformity, while Ruby has emphasis on individual unbridled originality), AND offers vaster choice in terms of existing add-ons, extensions, integration with webservers and frameworks for writing standalone special servers (Twisted above all!), development environments, books, etc, etc. So, it would seem to me that Python should be the obvious choice unless special circumstances apply (e.g., half a dozen skilled Common Lisp coders are already around and available -- in such a fortunate case, by all means go with Common Lisp, for example). >> please help and send your suggestions as soon as possible. >> my email id is bmproj2003 at yahoo.com > > Posted and CCed Ditto. Alex From juliagoolia301 at hotmail.com Thu Sep 11 15:33:09 2003 From: juliagoolia301 at hotmail.com (Julia Goolia) Date: 11 Sep 2003 12:33:09 -0700 Subject: tkinter, sockets and threads together Message-ID: <79ad5955.0309111133.5f6bf26f@posting.google.com> hello, i read that it is bad to use threads with tkinter. so my question is how does one create a gui program with sockets? at one point you have to call mainloop() which does not return. then you are not free to do stuff with the sockets. what's up with that? thanks so much for your time! julia From post400 at prontomail.com Wed Sep 3 07:32:22 2003 From: post400 at prontomail.com (post400) Date: 3 Sep 2003 04:32:22 -0700 Subject: Code complete electronic version ? Message-ID: Hi, apparently there is a very famous book that every developer should read: Code complete by Steve McConnell ! Is there an electronic version freely downloadable ? After all, the book was released in 1993 , it should have been public domain by now ! It would be nice to have a try before ! 50? is not exactly cheap ! What do you think ? Is it worth the money or not ? Thanks ! post400 From mpeuser at web.de Fri Sep 12 03:45:52 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 12 Sep 2003 09:45:52 +0200 Subject: Canvas - Rectangle. Is there an easy way to detect if you're inside? References: <4378fa6f.0309111159.7a9bb539@posting.google.com> <0KScnYKghrLc1fyiXTWJjQ@comcast.com> Message-ID: "Marc" ..... > Like I say, I am doing it right now with a bunch of if statements. It works > fine. But it's sort of a brute force method. Seems kind of hackish. It just > seems like one of those things where there has to be a cleaner way. > Have you tried using 'tags'. These are widely underestimated. There is the special tag 'current' which is bound to the object under the cursor. The 'object' however is only the drawn area, i.e. you have to 'fill' it. Useful methods are gettags, find_withtag; even tag_bind might be useful! There can be a list of tags to each object of course and they can be manipulated in multiple ways ( Kindly Michael P Try this: from Tkinter import * c=Canvas(width=300,height=300) c.create_rectangle(10,10,280,280,tags='a',fill='yellow') c.create_rectangle(100,100,200,200,tags='b',fill='green') c.pack() def aMove(ev): print c.gettags('current') c. bind("",aMove) c.mainloop() From paulpaterson at users.sourceforge.net Wed Sep 3 22:20:56 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Thu, 04 Sep 2003 02:20:56 GMT Subject: Interoperability between VB and Python under ASP In-Reply-To: References: Message-ID: bigdog wrote: > Max Ischenko wrote in message news:... > >>Hi, >> >>I've started to develop under Microsoft ASP framework, which allows >>different lang. used in a ActiveX page. I wonder about possible >>strategies to use Python modules from VBScript <%%> includes. > > I don't know if this will help, but it might be worth a shot. > http://vb2py.sourceforge.net/ I've never used it myself, I only point > it out as a curiosity I've heard of Although it isn't (currently) targetted at VBScript, the CVS version of vb2py might help if you have reasonably sized blocks of VBScript code to convert. It hasn't been tested on VBScipt specifically but the parser should work for most things and I'd certainly be interested to hear of any specific problems with ASP scripts. Out of the box it won't even recognize code in a .asp page, but I threw together the following code. I'm not an expert on ASP or VBScript but even if this is not correct it might point you in the right direction if you want to try a convert-to-python route .... test = """ <% function factorial(x) if x = 0 then factorial = 1 else factorial = x*factorial(x-1) end if end function %> """ from vb2py.vbparser import parseVB, VBCodeModule import re def translateScript(match): """Translate VBScript fragment to Python""" block = parseVB(match.groups()[0], container=VBCodeModule()) return "<%%\n%s\n%%>" % block.renderAsCode() converter = re.compile(r"\<%(.*?)%\>", re.DOTALL + re.MULTILINE) print converter.sub(translateScript, test) ... which should output: """ <% from vb2py.vbfunctions import * def factorial(x): if x == 0: _ret = 1 else: _ret = x * factorial(x - 1) return _ret %> """ You'll need the CVS version to get this to work - the v0.1.1 doesn't have the full parser and the v0.2 release is a couple of weeks off yet. If you do decide to try this route, I'd be very interested to hear of any specific issues that come up with translating ASP/VBScript to Python. Paul ========================= Paul Paterson vb2py :: A Visual Basic to Python Conversion Toolkit http://vb2py.sourceforge.net From tina_li23AThotmailDOTcom Thu Sep 25 18:28:52 2003 From: tina_li23AThotmailDOTcom (Tina Li) Date: Thu, 25 Sep 2003 18:28:52 -0400 Subject: Bottleneck? More efficient regular expression? References: <3f7069db_4@corp.newsgroups.com> <3f71ad83_4@corp.newsgroups.com> Message-ID: <3f736cad_4@corp.newsgroups.com> Hi Andrew, | > Thanks for the XML code. I've written up something | > similar using xml.parsers.expat, but it's conceivably slower | > than regexp. | | Conceivable, yes. But 1) did you test it, and 2) would it make a | difference? I tested it in terms of correctness. I didn't do any serious performance bench-marking as it's not the most important. The lag is *perceivable* (this is what I meant; sorry) by a human user so it's slower. | Here's a question for you. When is it easier to read the | documentation for existing code (which has been tested) | then it is to write and debug your own code? Is it a test question? =) I think it depends on the nature of the task. If it's intrinsically complex and error-prone, and that I have little exposure to it, I wouldn't risk re-inventing a wheel that doesn't turn. As well, what would the opportunity cost be between the time it takes to understand the documentation and that to code and test? Are the docs long, drab and obscure? Sometimes existing code isn't easy to customize for a particular need, then we'd have to redo it. | You can also make the pattern a bit less ambiguous, | eg, use [^>]* instead of .*? when you are inside an element, | which turns | | r'(?P.*?).*?' | | into | | r'(?P[^<]*).*?' | | (and use [^"]* instead of .*? for getting the text of an | attribute.) | | You can get rid of the other ambiguity (skipping characters | until the start of the next tag) by using something like | | ([^<]|<(?!queryGaps))* Message-ID: <3f535b95@news.mt.net.mk> >> Is this a bug? > > Yes. But since the DB is opened read-only, perhaps close() is not so important?!? -- ?????? (jabberID:damjan at bagra.net.mk) A: Because it reverses the logical flow of converstion. Q: Why is top posting frowned upon? From news at datatailors.xs4all.nl Sat Sep 6 19:45:57 2003 From: news at datatailors.xs4all.nl (Peter van Kampen) Date: Sun, 7 Sep 2003 01:45:57 +0200 Subject: OT: Americans love their guns References: Message-ID: In article , Steve Lamb wrote: > If guns were such a overriding factor why is it the UK has as high > if not higher rate of gun related violence than the US? For that matter I very much doubt that, can you provide some numbers to backup this statement? > why is it in several other European nations (Netherlands and Switzerland > IIRC) where there is a legal requirement for all males over a certain > age to be armed (standing militia) that there is so little gun related > violence? The Netherlands has no standing militia, nor does it require all males to own a gun. Until the early 90s there was a draft --if that's what it's called-- (Give all young men a chance to learn how to kill and then bore themselves to death in the other (11,13 or 17) months of service), but it was abandoned in 1993. The Netherlands now have a profesional army (i.e. all military personal voluntarily joined the army/navy/air force) that is mostly used in peace-keeping missions (with, regretfully, very mixed results). > When are people going to learn, it ain't the guns, its the education > and attitude surrounding them. It isn't guns that are the problem, it's > ignorance of guns thats the problem. By that rationale it wouldn't matter who owns 'weapons of mass destruction' as long as they would know how to (not) use them... If you would agree that Saddam Hussein shouldn't be allowed to own a 'gun', could you still argue that every Tony, Dick and George should? Only-mentioning-Godwin's-Law-ly yours, PterK -- Peter van Kampen pterk -- at -- datatailors.com From tl_nntp at webcrumb.com Thu Sep 4 02:47:13 2003 From: tl_nntp at webcrumb.com (Tom Lee) Date: Thu, 04 Sep 2003 06:47:13 GMT Subject: Thank you!!! In-Reply-To: References: Message-ID: <3f56dff0$1@news.comindico.com.au> MK wrote: > Thank you, Pythonistas. > > You gave me a medium to express myself. > > What is Fender to Jimi, or color to Monet, > Python is for me. > > My thoughts are flowing naturally with you, > Python. What is "Voodoo Chile" to Jimi, that's > short, elegant and working ZEN-code in > Python for me. > > Truly a freeing, non-linear and transcendent(*) > experience, > yours > MK > > > > (*) > Those excit?ng, legendary days when I implemented > a paint program in 6502 assembler, and a CAD/CAM program > in Turbo Pascal. > > And then 10 years of IT toiling... Am I loosing my faith? > > But programming is fun, again!!! > PYTHON!! PYTHON!! PYTHON!! PYTHON!! > PYTHON!! PYTHON!! PYTHON!! PYTHON!! > > erm ... yep, I like it too. ;) - TL From garyr at fidalgo.net Wed Sep 10 22:03:18 2003 From: garyr at fidalgo.net (Gary Richardson) Date: Wed, 10 Sep 2003 19:03:18 -0700 Subject: Tkinter Canvas/Grid question Message-ID: Is there a simple way of causing the size of a canvas to change as the window is resized when using the Grid geometry manager? Setting sticky='NESW', as in the following code, doesn't work though the documentation for Grid seems to imply that it should: "sticky If a slave's cell is larger than its requested dimensions, this option may be used to position (or stretch) the slave within its cell. ... The sticky option subsumes the combination of anchor and fill that is used by pack". Or is there something wrong with my code? Thanks, Gary Richardson from Tkinter import * class Test(Frame): def __init__(self, parent): Frame.__init__(self, parent) frame = Frame(parent) self.canvas = Canvas(frame, bg='white' , width=300, height=100) self.canvas.grid(row=0, column=0, sticky='NESW') frame.grid() root = Tk() Test(root) root.mainloop() From skip at pobox.com Mon Sep 29 16:27:01 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 29 Sep 2003 15:27:01 -0500 Subject: shelve keeping old (unused) data around? In-Reply-To: References: Message-ID: <16248.38293.601612.845564@montanaro.dyndns.org> nospam> I'm using shelve module in python 2.3 and I found that it does a nospam> very odd thing, at least very unexpected to me. It seems that nospam> the data of a replaced or deleted key stays in filename.dat nospam> file. The bits which actually get written to the disk depend on the underlying library writing those bits. The shelve module has no say in the matter. All it does to create a file is ask anydbm to open it, then pickle the values so they can be written out as strings. Again, shelve doesn't do that directly. It asks the object created by anydbm to do that. You didn't say (perhaps you don't know) what the underlying library is on your system. It seems likely that the library deletes the key, but leaves the data dangling (perhaps also marked free so it can reuse it at a later time). Skip From moss2533 at kettering.edu Sat Sep 6 01:09:25 2003 From: moss2533 at kettering.edu (Mark Moss) Date: 5 Sep 2003 22:09:25 -0700 Subject: XRC, wxMenuBar's, and wxMenuBarPtr's Message-ID: I have an XRC file that contains a complete menubar. I load this menubar into a frame with: self.ResMenu = wxXmlResource("menus.xrc",0) self.MenuBar = self.ResMenu.LoadMenuBar("MenuBarEditor") self.SetMenuBar(self.MenuBar) Then set up a menu event handler: EVT_MENU(self, XRCID("MenuItemSnapToGrid"), self.OnSnapToGrid) Finally, in OnSnapToGrid, I try to get a specific wxMenuItem by using the wxMenuBar.FindItem: m = self.MenuBar.FindItem(XRCID("MenuItemSnapToGrid")) This falls flat on its face because: AttributeError: wxMenuBarPtr instance has no attribute 'FindItem' It seems that LoadMenuBar returns a wxMenuBarPtr rather than a wxMenuBar. My question then is given a wxMenuBarPtr and the ID of the menu-item (via XRCID), how do I get ahold of the wxMenuItem object? Alternativly, is there a way to check/uncheck a wxMenuItem without having a reference to the actual object (using the id or similar)? Thanks in advance, Mark Moss From max at fr.fm Thu Sep 18 17:47:34 2003 From: max at fr.fm (Maxime Biais) Date: Thu, 18 Sep 2003 23:47:34 +0200 Subject: print and trailing white space References: <20030918232501.4f2ab362.max@fr.fm> <3F6A24B5.B26940B3@engcorp.com> Message-ID: <20030918234734.467cfcf1.max@fr.fm> Thu, 18 Sep 2003 17:33:41 -0400 Peter Hansen wrote: > What's wrong with write() ? Print is merely provided for convenience. > When it's not doing what you want, you are supposed to use write(), > not come up with weird hacks for print. ok sorry, I believed write was not buffered. I just read the library reference part on write() and see I was wrong. -- Maxime Biais From peter at engcorp.com Thu Sep 11 07:39:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Sep 2003 07:39:21 -0400 Subject: socket error 10061 References: Message-ID: <3F605EE9.36AB9C5B@engcorp.com> Bill Loren wrote: > > Upon running my program via the command line I get the above error. > Weirder is the fact that upon running the same code from within > ActiveState's PythonWin's > IDE - I get no error and the code smoothly completes its running. When posting questions of this nature, please include the traceback if there is one, or cut and paste the exact error right from your screen, along with the failing code section (for context). To find what 10061 means, import errno and type errno.errorcode[10061] -Peter From sminni_news at minisoftindia.com Mon Sep 1 00:23:25 2003 From: sminni_news at minisoftindia.com (Sanjay Minni) Date: 31 Aug 2003 21:23:25 -0700 Subject: tix / idestudio on win98 python 2.3 crashes Message-ID: <836a2f21.0308312023.4d2871a3@posting.google.com> Hi, I installed IDEStudio 1.9 on python 2.3 on win98 (all are current downloads) the sample tix app crashes pythonw invalid page fault tcl84.dll But it was working on python 2.2.3 Is it working for anybody ? Regards Sanjay Minni www.planage.com From lists at andrebocchini.com Fri Sep 19 19:48:57 2003 From: lists at andrebocchini.com (Andre Bocchini) Date: Fri, 19 Sep 2003 18:48:57 -0500 Subject: Proxy Authentication using urllib2 Message-ID: I'm having some trouble using proxy authentication. I can't figure out how to authenticate with a Squid proxy. I know for a fact the proxy is using Basic instead of Digest for the authentication. I can authenticate just fine using Mozilla. I've done some Google searches, but the closest piece of code I've is is for HTTPBasicAuthHandler: # set up authentication info authinfo = urllib2.HTTPBasicAuthHandler() authinfo.add_password('realm', 'host', 'username', 'password') proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"}) # build a new opener that adds authentication and caching FTP handlers opener = urllib2.build_opener(proxy_support, authinfo, urllib2.CacheFTPHandler) # install it urllib2.install_opener(opener) f = urllib2.urlopen('http://www.python.org/') Can anybody point me in the right direction to some more detailed documentation? I haven't really been able to understand what I found in the Python Library Reference either. I thought something like this might work, but is didn't: proxy_handler = urllib2.ProxyHandler({"http" : "http://myproxy:3128"}) proxy_auth_handler = urllib2.ProxyBasicAuthHandler() proxy_auth_handler.add_password(None, "myproxy", "myname", "mypass") opener = urllib2.build_opener(proxy_handler, proxy_auth_handler) urllib2.install_opener(opener) f = urllib2.urlopen("http://www.python.org") data = f.readlines() I always get a 407 error. Well, thanks in advance. -- Andre From missive at frontiernet.net Tue Sep 2 20:03:52 2003 From: missive at frontiernet.net (Lee Harr) Date: Wed, 03 Sep 2003 00:03:52 GMT Subject: cli arguments References: <3f5506d5$0$8546$ba620e4c@reader0.news.skynet.be> Message-ID: In article <3f5506d5$0$8546$ba620e4c at reader0.news.skynet.be>, Geiregat Jonas: > What is the module called that's made to dael with cli argument's like > --foo-bar -c -blabla ? > In python2.3, try optparse From member39949 at dbforums.com Wed Sep 17 05:58:07 2003 From: member39949 at dbforums.com (netytan) Date: Wed, 17 Sep 2003 05:58:07 -0400 Subject: Can Python Module Locate Itself? References: Message-ID: <3379901.1063792687@dbforums.com> You can use sys.argv[0] to get the path of the program and use that to read in the program file.. you could then parse the source as usual. But personally i'd be enclined to go with Juha's idea, it seems more elegant and requires less work on the part of the program and the programmer.. Have fun, Mark. -- Posted via http://dbforums.com From aleax at aleax.it Sat Sep 27 12:17:08 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Sep 2003 16:17:08 GMT Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: <8Kidb.130826$hE5.4452165@news1.tin.it> David Eppstein wrote: ... >> Really? I would expect a common usage to be: >> >> for 0 <= index < len(list): >> do something with list[index] > > Isn't that what the new enumerate(list) is for? Not necessarily. enumerate is for when you need the values of both index AND somelist[index], which is clearly a pretty common case. But sometimes you don't care about the "previous value" of somelist[index]. E.g., say that your specs are: if issospecial(index) returns true, then, whatever the previous value of somelist[index] might have been, it must be replaced with beeble.next(). Then, expressing this as: for index in range(len(somelist)): if issospecial(index): somelist[index] = beeble.next() looks rather better to me than: for index, item in enumerate(somelist): if issospecial(index): somelist[index] = beeble.next() where the fact that 'item' is being so deliberately REQUESTED... and then utterly IGNORED... makes me wonder if the code's author may not have committed some typo, or something. Admittedly, these cases where you don't CARE about the previous values of items ARE rare enough that enumerate use-cases vastly outnumber them. Alex From farmenta at pillardata.com Tue Sep 30 19:49:28 2003 From: farmenta at pillardata.com (Fernando Armenta) Date: Tue, 30 Sep 2003 16:49:28 -0700 Subject: How do you use " " whe sending a command Message-ID: <36504F2E352484458C5D574719DC83720138FF44@caex01.trans.corp> Hello, I am trying to pass the following command ssh IP_address "ssh IP_address ls" How you do that in Python? /" ? "/ ? p = os.popen('ssh.exp ' + MGMT_IP + ' ' + /" ssh + PMI_IP_NODE1 + ' ' + /bin/tdslog -C "/') Thanks for the help... -F -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at engcorp.com Wed Sep 17 09:33:50 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Sep 2003 09:33:50 -0400 Subject: scp in python References: Message-ID: <3F6862BE.66AA65EC@engcorp.com> Michael wrote: > > Is there a scp (ssh) written in Python ? Yes, no... this might help: http://groups.google.com/groups?q=comp.lang.python+scp+pexpect -Peter From jjl at pobox.com Thu Sep 18 08:46:41 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Sep 2003 13:46:41 +0100 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> Message-ID: <87znh26z7y.fsf@pobox.com> hildegarde_roth at yahoo.de (Hilde Roth) writes: > Thanks for the suggestion but zip is not nice for large lists > and as for array/numpy, although I chose a numeric example in > the posting, I don't see why only numeric arrays should enjoy > the benefit of such a notation. Numeric (and presumably numarray) can handle arbitrary Python objects. > l[;0] is illegal right now but does anyone of any other bit > of syntax it might conflict with if proposed as an extension? BTW, just remembered that Numeric/numarray *does* use commas for multi-dimensional indexing. Apparently (glancing at the language ref) that's not actually indexing with a tuple, but part of Python's syntax. Same goes for that other obscure bit of Python syntax, the ellipsis, as used by Numeric: foo[a, ..., b]. John From newsgroups at jhrothjr.com Mon Sep 15 16:40:54 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 15 Sep 2003 16:40:54 -0400 Subject: Datetime utility functions References: <182bcf76.0309150707.3a8c0482@posting.google.com> Message-ID: "Paul Moore" wrote in message news:brtl7s6v.fsf at yahoo.co.uk... > "John Roth" writes: > > > "Paul Moore" wrote in message > > news:182bcf76.0309150707.3a8c0482 at posting.google.com... > > >> 1. Get the last day of the month contatining a given date(time). I > >> really was surprised to find this one missing, as it seems to me that > >> the datetime module must know what the last day for each month is, so > >> exposing it wouldn't have been hard. > > > > I'm kind of surprised to see that it's missing, too. > > The best solution I could find was > > def month_end(dt): > # Get the next month > y, m = dt.year, dt.month > if m == 12: > y += 1 > m = 1 > else: > m += 1 This looks incomplete. You could use this to get the sequential date for the first of the next month, but you still have to subtract one day and then print out the day. > > # Use replace to cater for both datetime and date types. This > # leaves the time component of a datetime unchanged - it's > # arguable whether this is the right thing. > > return dt.replace(year=y, month=m, day=1) - datetime.timedelta(days=1) > > It's not hard - but it's mildly tricky (I made a few false starts and > some silly off-by-one errors) and I'd much rather grab it from a > library than make the same mistakes next time I need it. As I said, I don't see any obvious reason why they wouldn't accept a patch, if you want to submit it. > >> 2. Add a number of months to a date. This is messy, as there are > >> options (what is one month after 31st Jan). The trouble is that the > >> calculation, while simple, is tricky to get right (month is 1-based, > >> so off-by-1 errors are easy to make, and divmod isn't as useful as > >> you'd first think). > > > > That's application dependent. > > True. But for "naive" use, a simple definition does. This is in line > with the datetime module's philosophy of not trying to cater for > "advanced" uses, but to provide something useful for straightforward > use. In this particular case, I'd argue that the obvious definition > (same day number N months on) where applicable, plus a well-documented > "reasonable" answer for the edge cases (eg, Jan 31 plus 1 month) is > useful. In practice, I suspect that 99% of cases involve adding a > number of months to either the first or the last of a month. Except for the edge case I mention below, this is really too simple; it's just add one to the month and keep the same date. Hardly worth a method at all, especially if you have the "last day of month" method. > > If a bond, for example, has interest payable on the 30th of the > > month, you probably want the 30th, except in February you want the > > last day of the month. However, the contract may specify something > > else. And in no case do you want the date to suddenly change to the > > 28th because you went through February. > > But that's not so much a case of adding a month, as a more complex > concept, a "repeating date". Nevertheless, I take your point. Yes. When you've got something application dependent, they tend not to put in "naive" definitions. What's a 'naive' definition for one person is simply wrong for another. John Roth > Thanks for the comments, > Paul. > -- From shlomme at gmx.net Wed Sep 17 08:03:28 2003 From: shlomme at gmx.net (Torsten Marek) Date: Wed, 17 Sep 2003 14:03:28 +0200 Subject: audio module In-Reply-To: <9bP9b.71118$Mb2.2369961@twister.tampabay.rr.com> References: <9bP9b.71118$Mb2.2369961@twister.tampabay.rr.com> Message-ID: Todd Stephens schrieb: > Is there such a module containing audio tools? I am looking specifically > for tools to manipulate ogg-vorbis and convert other formats (mp3, wav) to > ogg. > What do you mean by "manipulation"? Edit the tag info? You can have a try with (my) libtagedit (libtagedit.sourceforge.net), which supports mp3 as well. Converting mp3 into ogg with preserving the tag information consists mostly out of building the commandline: trans_table = { "Artist": "--artist", "Title": "--title", "Track": "--tracknum", "Genre": "--genre", "Year": "--date", "Album": "--album", "Comment": "-c ="} def mp3ToOgg(tag, outdir, quality="3,5"): args = ["%s \"%s\"" % (trans_table[field], tag[field]) for field in trans_table.keys() if tag[field]] args = " ".join(args) new = os.path.join(outdir, os.path.basename(tag.filename().replace(".mp3", ".ogg"))) os.system("lame --decode \"%s\" -|oggenc -q %s -r -o \"%s\" %s -" % (tag.filename(), quality, new, args)) This example uses libtagedit (tag is a tageditor class). If you want more specific information, I could mail you some scripts I wrote. greets Torsten From knightsofspamalot-factotum at gvdnet.dk Thu Sep 4 17:59:29 2003 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Thu, 04 Sep 2003 23:59:29 +0200 Subject: Selecting elements from a list Message-ID: <87y8x4w6ym.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Howdy! Suppose I have a list A containing elements that I want to put into list B if they satisfy some property. The obvious way of doing it would be, B = [] for i in A: if A.property(): B.append(i) Now, list comprehensions, map() etc. can make a lot of list operations easier, but I haven't found a shorter, more elegant way of doing this. Have I missed something, or will I have to stick to my explicit loops? Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAj9XtcEACgkQYu1fMmOQldVX0wCeJ7gxV82QVCqRZ3r44vbkFquf M3QAnRGXnV3l/KslD7LNxT9roVQhGgJM =aVpW -----END PGP SIGNATURE----- From ajsiegel at optonline.net Wed Sep 3 08:05:01 2003 From: ajsiegel at optonline.net (Arthur) Date: Wed, 03 Sep 2003 08:05:01 -0400 Subject: Open Source leader? (was Re: Celebrity advice) Message-ID: <005701c37213$9ae638b0$0c02a8c0@Arts> > aahz at pythoncraft.com (Aahz) writes: > > > In article , > [...] > > OTOH, Perens is also (like me ;-) a self-described asshole. When I saw > > him at the Waterside Conference earlier this year, he basically claimed > > that only assholes could make significant progress in the Open Source > > community. > [...] > ahaz, is of course, being an opportunist. The record will show that I am the first here to have made claim - in just those words - of being a self-described asshole. And heard no objection to the categorization. which, it now seems, puts me in charge ; good! Art From aleax at aleax.it Sat Sep 6 11:30:09 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Sep 2003 15:30:09 GMT Subject: Embedded Perl or Python (XPost) References: <74e674c13888643bf15a72e800c9d8ed@news.teranews.com> Message-ID: <54n6b.22635$hE5.830077@news1.tin.it> Tassilo v. Parseval wrote: > Also sprach Alex Martelli: > > [ embedding an interpreter ] > >> Another option you may want to consider is Ruby. I don't know >> how easy it is to interface it specifically to C++, and in >> particular to get the cross-language subclassing and overriding >> effect you want (which Boost provides so smoothly) -- but it's >> basically the same power as Perl or Python, a distinctive style >> of its own that along some axes lies in-between the two P's, >> and a small but enthusiastic community. Size-wise, though, I >> don't think it will significantly help you. > > The C interface of Ruby is very simple and clear (likewise the C code in > which Ruby was written). It almost made me cry when I saw it and > compared it to that of Perl. :-) It's probably also smaller than both > Python and Perl. I don't know about Python, but Perl's unwrapped source > is currently well beyond 50meg. In compiled form it's still pretty large For Python, I count 1.8 MB of .h files, 7.6 MB of .C files, and 1.8 MB of .py files. Of course, that includes all sort of things such as the RISCOS and Mac/OS implementations, the Tkinter GUI library, the IDLE integrated development environment, and a bazillion other tools, unit and integration tests, and "weird" library modules (Python lacks Perl's CPAN, so far, but does have a huge included library). In terms of compiled size, I see: [alex at lancelot src]$ size /usr/bin/ruby text data bss dec hex filename 569672 4192 56768 630632 99f68 /usr/bin/ruby [alex at lancelot src]$ size /usr/bin/python* text data bss dec hex filename 514283 90792 9240 614315 95fab /usr/bin/python2.1 (these are the latest statically linked ones I have around) so the sizes would appear to be very directly comparable (sorry, no statically linked perl around for comparison!). > due to all the modules that come with Perl. Not sure whether the OP > needs all of them though. He did say he plans to cut things out selectively (e.g. sockets). > The bridge to C++ should not be so hard considering that a C++ compilers > wont mind to include C code as well (or can at the very least easily be > convinced to do so). Ah, but what the OP wants is specifically for (Python/Perl/Ruby) classes to be able to inherit from C++ classes, override some methods, and be callable from C++ with the overridden methods smoothing and transparently executed. That's far from being as simple as it sounds -- it just can't be done at a purely C level, and Boost Python does manage to pull it off with much C++ template metaprogramming (David Abrahams, Boost Python's author, is one of the true magicians in this specific area). Alex From losnations at comcast.net Fri Sep 12 00:17:53 2003 From: losnations at comcast.net (Marc) Date: Thu, 11 Sep 2003 23:17:53 -0500 Subject: Canvas - Rectangle. Is there an easy way to detect if you're inside? References: <4378fa6f.0309111159.7a9bb539@posting.google.com> Message-ID: <0KScnYKghrLc1fyiXTWJjQ@comcast.com> The problem is that I have other objects in the rectangle that I'm basically using as a holder. So if I use the closest function, then sometimes when I have more than one object in the rectangle it will pick up the other objects. Therefore I simply need a way of always knowing when the cursor is within the bounds of the rectangle. Like I say, I am doing it right now with a bunch of if statements. It works fine. But it's sort of a brute force method. Seems kind of hackish. It just seems like one of those things where there has to be a cleaner way. "Gordon Airport" wrote in message news:ekCdneV55u9Ij_yiXTWJhA at comcast.com... > Have you tried find_closest? > Given a click event... > > x = cv.canvasx( event.x ) > y = cv.canvasy( event.y ) > cvid = cv.find_closest( x, y )[0] > cv.itemconfig( cvid, fill = 'black' ) > > From gez_75 at hotmail.com Mon Sep 29 05:36:45 2003 From: gez_75 at hotmail.com (Gez) Date: 29 Sep 2003 02:36:45 -0700 Subject: Wavelet package available? Message-ID: <2ceb70f8.0309290136.118a856d@posting.google.com> Hi, Does anyone know if there is a wavelet package available for Python? This package should at least have the Daubechy wavelet. Cheers, Gez 75 From danielk at aracnet.com Fri Sep 19 13:39:53 2003 From: danielk at aracnet.com (Daniel Klein) Date: Fri, 19 Sep 2003 10:39:53 -0700 Subject: [OT] New Play: SPAMELOT Message-ID: http://www.dailyllama.com/news/2003/llama206.html From roberto at dealmeida.net Sat Sep 27 09:45:23 2003 From: roberto at dealmeida.net (Roberto A. F. De Almeida) Date: 27 Sep 2003 06:45:23 -0700 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> Message-ID: <10c662fe.0309270545.1fd5d839@posting.google.com> Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:... > I would have expected, given that the tuple contains slice objects > constructed from the multiple-slice notation, that the same > translations would be performed on the slices that are inserted into > the tuple that are applied when the single slice is created. > > That is, whether the single or multiple notation is used, and whether > the slice objects are placed in a tuple or not, they are constructed > from the tuple notation - the translation from notation to slice > object should be done consistently. Yes, I believe I was not very clear. This is the inconsistency I was talking about. (And this is with Python 2.3.1) > >What you probably want is b[:-1][:-1], etc. Each index must be > >separately bracketed to access items in list of lists (etc). > Maybe. Maybe not. I assumed he was doing something similar to what > happens in numeric - they do some rather interesting > slicing-of-multidimensional-container things over there. Of course I'm > not a numeric user, so I may be misunderstanding things. Yes, you're right. The problem with b[:-1][:-1] is that it will return b[:-1], and then slice the result again. It's ok if you're working with lists, but not for what I'm doing. I'm working in a client to access OPeNDAP servers. It's basically data served through http, with some metadata and the ability to specify the variables and ranges you want. For example, if you have a dataset served at: http://server/cgi-bin/opendap/dataset.nc You can download the variable "A" as ASCII with the following URL: http://server/cgi-bin/opendap/dataset.nc.ascii?A If you want only part of "A", in binary (xdr) format: http://server/cgi-bin/opendap/dataset.nc.dods?A[1:10][1:5][6] What I'm doing is this: >>> from opendap import client >>> data = client.dataset("http://server/cgi-bin/opendap/dataset.nc") >>> print data.variables["A"].shape (20,10,12) >>> A = data.variables["A"][1:10,1:5,6] Data is only retrieved when you slice a variable like above, and only the data sliced is requested from the OPeNDAP server, instead of the whole range. If I use multiple slices, eg, >>> A = data.variables["A"][1:10][1:5][6] then first the client will have to download A[1:10][:][:], and slice it later -- more data than needed will be retrieved. If instead I pass a tuple of slices, I can construct the URL http://server/cgi-bin/opendap/dataset.nc.dods?A[1:10][1:5][6] and request from the server only the data that will be used, and return it as a Numeric array. Roberto From DeepBleu at DeepBleu.org Fri Sep 26 18:52:44 2003 From: DeepBleu at DeepBleu.org (DeepBleu) Date: Fri, 26 Sep 2003 22:52:44 GMT Subject: Passing a String to a Python CGI Script References: Message-ID: <0r3db.113900$z32.73864@twister.austin.rr.com> I figured this thing out. But, really truly no one could have suggested the use of standard I/O???? DeepBleu "DeepBleu" wrote in message news:METcb.113316$z32.83149 at twister.austin.rr.com... > I'll reword that: > A client is writing a string to the web server (IPlanet on a Sun Server) > using a java program. The client then establishes a connection with a cgi > Python program on the server. This client wants the string to be passed > into this cgi Python script on the server. > There are no name=value request pairs. How can this cgi Python script read > the string sent to the web server. The client is POSTING the string as a > REQUEST. For the Pythong cgi script I am using CGI module to handle > requests and responses. However, how do you handle this REQUEST? > > "DeepBleu" wrote in message > news:AY3cb.104524$834.93516 at twister.austin.rr.com... > > When one is using an HTML form via a web broswer, the user submits the > form > > contents and these are passed to a CGI Python script on the web server. > > I need to write a client script that connects to a web site, runs a Python > > CGI script on the web server AND passes a string to the CGI Python script > > that the Python CGI script can store/manipulate/evalute etc.... > > I know how to connect to the web site and run the CGI Python script using > a > > client Python script with the urllib module. But how do I submit/send a > > string via this client Python script to the web server on behalf of the > CGI > > Python script? Can someone give me a clue or a hint on how to do that? > Do > > I write the string to the web server? If so, how would the CGI Python > > script know about it, read it, and store it? > > Thanks, > > DeepBleu > > > > > > From newsgroups at jhrothjr.com Fri Sep 5 16:48:48 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 16:48:48 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> Message-ID: "Mel Wilson" wrote in message news:qpOW/ks/KnRV089yn at the-wire.com... > In article , > "John Roth" wrote: > >"Grant Edwards" wrote in message > >news:3f58b1f6$0$155$a1866201 at newsreader.visi.com... > >> In article , John Roth wrote: > >> > > >> > "Grant Edwards" wrote in message > >> > news:3f58a2bd$0$156$a1866201 at newsreader.visi.com... > >> 2) It would mean that there's some sort of difference between > >> a function and a method. > > > >I don't understand your point. There is currently a difference > >between a function and a method that could be eliminated by > >making self a reserved word and removing it from the method > >header. Or have you never tried to invoke a method from the > >wrong context and gotten the "unbound method" error? > > There's no difference in the sense that a method is > simply a function whose first parameter refers to the class > instance to be worked on. No magic words, no "undeclared" > parameters. It means that in my demo code in limitcases.py > (somewhere in the newsgroup lately) I can say > > limitcases.Lowest.__str__ = lambda x: "-Infinity" > > to give the Lowest class a new method sans ennuis. But why do it that way? Neither Java nor Ruby require giving the instance a name. Hence my comment that requiring it is more complex than not requiring it. John Roth > > Regards. Mel. From james.kew at btinternet.com Sat Sep 20 18:09:49 2003 From: james.kew at btinternet.com (James Kew) Date: Sat, 20 Sep 2003 23:09:49 +0100 Subject: python script as an emergency mailbox cleaner References: Message-ID: "Phil Weldon" wrote in message news:ZCZab.45450$Aq2.39773 at newsread1.news.atl.earthlink.net... > My guess is that the internet will not open on Monday. Yeah, well, death of the Internet's been predicted many times before and hasn't happened yet. F-Secure's writeup is pretty good at describing the various attacks and texts the worm uses: http://www.f-secure.com/v-descs/swen.shtml FWIW, for me Bayesian filtering is doing a pretty good job on both the fake security advisories and the fake bounce messages. (Somewhat ashamedly, I'll admit to using POPFile (Perl) rather than the SpamBayes (Python) -- as a POP3 proxy solution it seemed slightly slicker at the time...) James From ec at clif2.com Wed Sep 17 12:22:37 2003 From: ec at clif2.com (Elliot Clifton) Date: 17 Sep 2003 09:22:37 -0700 Subject: [newbie] Manipulating Dates Message-ID: <3cad211d.0309170822.b31822@posting.google.com> X-No-archive: yes Hi, How do I do the following with the Date object: newDate = oldDate + 3 months What would that be in Python code? Thanks, Elliot From and-google at doxdesk.com Wed Sep 24 07:38:42 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 24 Sep 2003 04:38:42 -0700 Subject: CGI Redirect to another page References: <09a3d6364c.tim@worthy.demon.co.uk> Message-ID: <2c60a528.0309240338.1e4dd261@posting.google.com> Tim Howarth wrote: > print "Location: http://abcxyz/index.html" > AFAIUI it simply sends a redirect header. Yep; however, if you include a relative URI with no hashpart: print 'Location: /index.html' print Then the server should send that page to the browser directly, without sending a redirect back to the browser. This may be preferable in some cases. (The second print is needed to end the CGI response headers.) Full spec here: http://hoohoo.ncsa.uiuc.edu/cgi/interface.html (Using JavaScript or meta-refresh to do redirects is almost always a really terrible idea.) -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From seberino at spawar.navy.mil Tue Sep 30 19:11:09 2003 From: seberino at spawar.navy.mil (Christian Seberino) Date: 30 Sep 2003 16:11:09 -0700 Subject: distutils (packaging) newbie questions please.... Message-ID: I really want to learn distutils to professionally package some open source software. I had some distutils questions after reading python.org distutil docs on packaging code if you don't mind. I would really appreciate some help..... 0. I'm confused about use of the word "package" in setup.py. packages = ["", "", ...] Does package here just mean "a new directory of source code to consider"??? 1. What exactly goes into the __init__.py files? I know what to put in setup.py and I know __init__.py is used for packages but I don't know what to put IN this file. 2. About the data_files option for setup.py.... data_files = [ "", [ "", "", ...] ] Is there a way to AVOID having to type EVERY single data file?? Can I specify just the directory or use wild cards?? 3. python setup.py sdist will make a package of SOURCE code and using "bdist" will put BINARIES in package. What does this mean??? Will bdist packages unpack to pyc (bytecode) files and sdist will unpack py (noncompiled) files???? What if I wanted py and pyc files installed from the package?? (i.e. source and compiled versions) Thanks! Chris From rganesan at myrealbox.com Fri Sep 12 06:21:03 2003 From: rganesan at myrealbox.com (Ganesan R) Date: Fri, 12 Sep 2003 15:51:03 +0530 Subject: Can This Code Be Made Faster? References: Message-ID: >>>>> "John" == John Abel writes: > I have a problem, in that the following code is sometimes failing. I > am stat'ing a list of files, but, sometimes, one of the files may be > moved by an external process, after the os.path.exists and before the > lstat, causing the script to fail. My question, is there anything I > can do to speed it up, or put in a trap, to stop the stat from failing? > fileTimes = [ ( os.lstat( os.path.join( rootPath, fileName ) > )[stat.ST_MTIME], fileName) for fileName in fileList \ > if > os.path.exists( os.path.join( rootPath, fileName ) ) ] Then there's no point in doing os.path.exists(), you might as well call os.lstat directly. Some like this should work: ====== fileTimes = [] for fileName in fileList: try: fileTimes.append( (os.lstat(os.path.join(rootPath, fileName)).st_mtime, fileName) ) except: pass ====== Ganesan -- Ganesan R From jepler at unpythonic.net Sun Sep 28 21:07:49 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 28 Sep 2003 20:07:49 -0500 Subject: Python parser that records source ranges In-Reply-To: References: Message-ID: <20030929010749.GA21627@unpythonic.net> The tokenize module will give column information for each token, but it produces a stream of tokens only, not an AST. Jeff From peter at engcorp.com Tue Sep 9 11:27:46 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 09 Sep 2003 11:27:46 -0400 Subject: Ternery operator References: <3F5C7CBD.A6C97371@engcorp.com> Message-ID: <3F5DF172.6B59A2@engcorp.com> Uwe Schmitt wrote: > > Peter Hansen wrote: > > Uwe Schmitt wrote: > >> > >> Andrew Chalk wrote: > >> > Is there a python equivalent of the C ternery operator? > >> > >> > I.e.: > >> > >> > fred = (x == 1) ? 12 : 15 > >> > > > I would think a *Python* equivalent to ?: should not use > > direct equality comparison with 1. Better to drop the "==1" > > parts in any of the above, to allow the usual Python interpretation > > of what is True and what is False to occur. > > > ...so fred = [12, 15][not x] is sufficient. > > You made a mistake, compare : True, sorry. I think I was thrown off by your explicit comparison with 1 in the original, and my critical nature homed in on that aspect, thinking you were presenting another example of a non-Pythonic way of evaluating True/False. I'll make this point instead: noting my mistake, and the excited disagreement that followed in other replies (lots of exclamation marks showing up!), this can only be seen as yet more evidence that using any of those alternatives to a simple if/else is rather too likely to be error prone for anyone to prefer it. -Peter From jfranz at neurokodeXREMOVEX.com Wed Sep 24 17:11:47 2003 From: jfranz at neurokodeXREMOVEX.com (Jon Franz_antispam) Date: Wed, 24 Sep 2003 17:11:47 -0400 Subject: Fastest way to get thousands of db records to client in 3 tier? References: <3f71361f$0$97182$edfadb0f@dread12.news.tele.dk> <874qz22jah.fsf@pobox.com> <5mncb.14032$cK5.5101@fe1.columbus.rr.com> Message-ID: <01b201c382e0$77414fc0$7401a8c0@voidmk9> > I _have_ used systems that returned a subset of matching records to > the client, and found it very uncomfortable. That's why in my system I > want to scratch my own itch, and return all the records. Here are some odd ideas: - Have the server do the original query, but put the results into a table (temporary table? - depends upon the lifespan of temp tables in your RDBMS), then let the server hand the client the name of this table. The client then queries for the records from the location the server gave it. The table the client queries is a one-time view of the data, thus your server code can do any joins and logic needed for the biz rules, and the client simple does a select * on the results. - Stored procedures. Move some of your biz logic into them, the server will get simpler, and the occasional client by-pass of the server won't cause headaches when the biz rules change. - Warning, this one is ugly: Write the query in such a way that the results are preformated for transmission between the server and client. For example, using string concatenation, change your query to return 1 column, which would contain a pickled object sutable for immediate transmission to the client. If you're not passing pickled objects, this will be easier, since you just format the column to contain a valid line/record for sending to the client. ~Jon Franz NeuroKode Labs, LLC From peter at engcorp.com Fri Sep 19 20:04:26 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Sep 2003 20:04:26 -0400 Subject: Custom Execution from Python References: Message-ID: <3F6B998A.FBA7E584@engcorp.com> satish wrote: > > I have a shared object executable viz. *cable* which I execute as follows : > $ ansyscust71 -custom cable -p ANSYSRF > > **ansyscust71 is a shell script and is a part of a software called ANSYS** > > Now, I have generated a python module using a *fortran-python interface > generator called F2PY* using the same *make rules* which were used to make > *cable* when not using F2PY > > I got a Python extension module named *cable_f2py* again. > > From the python environment when I tried to execute *cable_f2py* ( this is > python module due to F2PY), I got a segmentation error just like how I would > get this error when I execute *cable* as follows when not using F2PY: > > $ ./cable > Segmentation Fault > > However, when I execute it as follows, it works > > $ansyscust71 -custom cable -p ANSYSRF --> This is required for succesful > execution > > Now, I dont understand how I can mimic the above way of execution from within > Python to execute *cable_f2py* which as I mentioned earlier is the result of > making and linking all the same libraries which were used while making and > linking cable > > I am really confused So are we, as most of what you describe above seems to have very little relationship with Python. You might need to think through your problem and attempt to explain it in a different way for us to help you. For example, you don't show *how* you try to execute it "from the python environment". Have you got some code to show us? Anyway, as a bit of a long shot, are you aware of the os.system() function, and the various other methods of running external executables? If you are already using one of those, you might want to show us how you use it. -Peter From fuerte at sci.fi Sat Sep 6 16:58:50 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Sat, 06 Sep 2003 23:58:50 +0300 Subject: Why the 'self' argument? In-Reply-To: <3f5a2260$0$166$a1866201@newsreader.visi.com> References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <3f5a2260$0$166$a1866201@newsreader.visi.com> Message-ID: Grant Edwards wrote: > In article , Harri Pesonen wrote: > >>I agree, it's not logical. I'm learning Python at the moment, and like >>it very much. This "self" thing seems to be the only odd feature, > > It seemed quite natural to me, but perhaps that's because I'd > used other languages that worked the same way. Coming from > Modula-3 and Smalltalk, the way classes worked in Python seemed > quite intuitive. > > OTOH, C++ seems like a real non-intuitive mess to me. > >>it feels like the whole class feature was added later. > > Why? Because everything else in Python seems to be very compact, there are no variable type declarations, or variable declarations, or anything else unnecessary that can be omitted. I would like to have self omitted, it would make the class syntax more beautiful and compact. On the other hand, I would like to have real private methods. Also I think that the class members should be explicitly declared. In general, it would be nice to have an option (like Option Explicit in Visual Basic) so that you can't assign to variables that have not been declared. It would probably make Python less error prone. Also if variable declarations could have the type, again some errors could be detected at compile time. I have not written any real Python applications yet, so I'm not expert, these are just my thoughts at this point. Harri From bluheaven2 at yahoo.com Thu Sep 4 20:12:49 2003 From: bluheaven2 at yahoo.com (Dave) Date: 4 Sep 2003 17:12:49 -0700 Subject: Python port to Swiss Ephemeris work with 2.3? Message-ID: <734b753f.0309041612.2066021@posting.google.com> Hi, I was just wondering if anyone knows whether it's possible to use the Python port to the Swiss Ephemeris with the latest version Python 2.3? I downloaded it from the vault, and it worked fine with Python 2.2.2, but then when I switched to Python 2.3 it gives me this error: "ImportError: DLL load failed: The specified module could not be found" Yet it has no problem importing the rest of the modules which are in the same directory as the dll. Does anyone know what's going on? Am I stuck using the older version of Python for the Swiss Ephemeris? Thanks -Dave From martin at v.loewis.de Sat Sep 20 07:28:50 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 20 Sep 2003 13:28:50 +0200 Subject: Help Compiling 64bit Python References: Message-ID: John Abel writes: > c++ -o python \ > Modules/python.o \ > libpython2.3.a -lresolv -lsocket -lnsl -lrt -ldl > -lpthread -lm > ld: fatal: file Modules/python.o: wrong ELF class: ELFCLASS64 > ld: fatal: File processing errors. No output written to python > collect2: ld returned 1 exit status > make: *** [python] Error 1 > > I'd be very grateful for any pointers. You need to arrange to use the -m options in the linker line as well. Looking at the generated Makefile will tell you where to best insert these options. Regards, Martin From nav+posts at bandersnatch.org Fri Sep 12 11:06:03 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 12 Sep 2003 11:06:03 -0400 Subject: OT: Americans love their guns References: <16223.15950.299463.959577@montanaro.dyndns.org> <000b01c37824$c972de10$3a0ff10c@teaset> Message-ID: "Al Kirke" writes: > It shouldn't be on the python group.. It was off-topic and I > should not have replied. [ More pro-gun rhetoric snipped. ] And yet, you are still determined to push your agenda, despite your admission that it's OT and you should not have replied. Real nice. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From news at fairford.co.uk Fri Sep 26 05:32:13 2003 From: news at fairford.co.uk (jim) Date: Fri, 26 Sep 2003 09:32:13 +0000 (UTC) Subject: WaitCommEvent error Message-ID: Hi, All I am using python (activestate 2.2.2-224) on XP home and have suddenly got the following error from a file which worked fine under millenium. self.Overlapped = win32file.OVERLAPPED() self.overlapped.hEvent = CreateEvent(None, 0, 0, None) hComm = win32file.CreateFile(comport, win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL | win32con.FILE_FLAG_OVERLAPPED, None) Error - File "E:\code\Python\PyModbus\FEModbusV101.py", line 162, in ComPortWrite rc,mask =win32file.WaitCommEvent(self.hComm,self.Overlapped) api_error: (87, 'WaitCommError', 'The parameter is incorrect.') I think the api call requires 3 parameters but only 2 are used in python any ideas ? many thanks Jim From aleax at aleax.it Fri Sep 26 07:11:29 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 11:11:29 GMT Subject: Python embedded in C & memory releasing References: <63701d2f.0309231819.31fdec85@posting.google.com> <87vfri14a3.fsf@pobox.com> Message-ID: John J. Lee wrote: > leonardbocock at yahoo.com (lebo) writes: > >> I'm trying to understand how Python handles memory usage and dynamic >> object loading and unloading. Problem to solve? Build a very low >> memory footprint (non-GUI) Python application for Unix/Windows. Why >> use Python? End user flexibility. >> >> So far it seems that (on Windows): >> (1) memory increases when you import . Expected behaviour. >> (2) memory does not release when you del . Why not? Is Python >> not releasing the memory or is it the OS not releasing memory? > [...] > > On almost all OSes, processes hold on to all memory that has been > allocated by the OS. Memory released by a process can only be reused > *by that same process*. The OS only gets it back when the process > exits. This is not true any more these days!!! Consider the following program: #include #include int main() { char* blobbone; printf("No blob yet, measure me now, then press enter... "); while(getchar() != '\n') {} printf("\n"); blobbone = malloc(1024*1024); printf("I have the blob, measure me now, then press enter... "); while(getchar() != '\n') {} printf("\n"); free(blobbone); printf("No more blob, measure me now, then press enter... "); while(getchar() != '\n') {} printf("\n"); printf("Bye bye.\n"); return 0; } Using Ctrl-Z to suspend and Enter to continue, on Linux, we see: [alex at lancelot sae]$ gcc mem.c [alex at lancelot sae]$ ./a.out No blob yet, measure me now, then press enter... [1]+ Stopped ./a.out [alex at lancelot sae]$ ps -C a.out v PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND 32606 pts/6 T 0:00 73 1 1330 276 0.0 ./a.out [alex at lancelot sae]$ fg ./a.out I have the blob, measure me now, then press enter... [1]+ Stopped ./a.out [alex at lancelot sae]$ ps -C a.out v PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND 32606 pts/6 T 0:00 82 1 2362 320 0.0 ./a.out [alex at lancelot sae]$ fg ./a.out No more blob, measure me now, then press enter... [1]+ Stopped ./a.out [alex at lancelot sae]$ ps -C a.out v PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND 32606 pts/6 T 0:00 82 1 1334 316 0.0 ./a.out [alex at lancelot sae]$ fg ./a.out Bye bye. [alex at lancelot sae]$ See? the DRS grows from 1330 to 2362 K when the blob is allocated, then drops back to 1334 when the blob is freed again. I'm pretty sure on Windows, with a good modern VC++ version, you'll see the same, apart from the slightly higher difficulty of the "measure me now" task;-). And in Python...? *SAME THING*!!! Watch: print "No blob yet, measure me now, then press enter...", x = raw_input() print blobbone = 1024*256*[None] print "I have the blob, measure me now, then press enter...", x = raw_input() print del blobbone print "No more blob, measure me now, then press enter...", x = raw_input() print print "Bye bye." [alex at lancelot sae]$ python mem.py No blob yet, measure me now, then press enter... [1]+ Stopped python mem.py [alex at lancelot sae]$ ps -C python v PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND 32648 pts/6 T 0:00 436 779 3864 2504 0.4 python mem.py [alex at lancelot sae]$ fg python mem.py I have the blob, measure me now, then press enter... [1]+ Stopped python mem.py [alex at lancelot sae]$ ps -C python v PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND 32648 pts/6 T 0:00 436 779 4892 3536 0.6 python mem.py [alex at lancelot sae]$ fg python mem.py No more blob, measure me now, then press enter... [1]+ Stopped python mem.py [alex at lancelot sae]$ ps -C python v PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND 32648 pts/6 T 0:00 436 779 3864 2508 0.4 python mem.py [alex at lancelot sae]$ fg python mem.py Bye bye. [alex at lancelot sae]$ See? Just the same behavior -- DRS grows 3864->4892, then shrinks back to 3864 when the blob is dropped. The explanation of the behavior observed by the original poster is quite different from the one you posit: rather, it is that "del module" does NOT drop the module -- the module remains in memory, fully available and loaded, and it is pointed to by the appropriate entry sys.modules['module'] in case you want it back. That's all there is to it -- modules, as opposed to, say, lists, are NOT so easily disposed of:-). Alex From martin at v.loewis.de Mon Sep 1 04:31:18 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 01 Sep 2003 10:31:18 +0200 Subject: Accessing class members from C In-Reply-To: References: Message-ID: disgracelands wrote: > Basically i have the python class object as a C > pointer You mean, you have an instance object? > and i want to access one of the class members, somevar, And you want to access an instance attribute? I recommend to use PyObject_[Get|Set]Attr[String] (this would actually work for class objects and class members as well). Regards, Martin From adalke at mindspring.com Wed Sep 24 18:05:01 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 24 Sep 2003 22:05:01 GMT Subject: Pre-PEP: reverse iteration methods References: Message-ID: Me: > The only two I can think of are: > for i in range(len(obj)-1, -1, -1): yield obj[i] Peter Otten proposed a nice variation; assume negative indicies work. Then there's no need to assume len works. Andrew dalke at dalkescientific.com From baas at ira.uka.de Wed Sep 10 16:42:07 2003 From: baas at ira.uka.de (Matthias Baas) Date: Wed, 10 Sep 2003 22:42:07 +0200 Subject: ANN: Python Computer Graphics Kit v1.0.1 Message-ID: <123vlvo9vt41b6ubmufjni4m31gjicucsn@4ax.com> The first non-beta release of the Python Computer Graphics Kit is available at http://cgkit.sourceforge.net What is it? ----------- The kit is a collection of Python modules that contain the basic types and functions required for creating 3D computer graphics images. The kit includes several new types such as vectors, matrices and quaternions. It contains a binding for Pixar's RenderMan interface which is a renderer independent API to communicate 3D data to renderers which will finally produce a 2D image. There are already several RenderMan compliant renderers freely available (they are not part of the kit). The kit also includes some of the functionality from the RenderMan Shading Language which enables you to create procedural models or textures from within Python. Even though the kit focuses on RenderMan, the new types or the Shading Language functionality can also be used for other rendering mechanism such as OpenGL or other renderers such as POV-Ray. The kit should run on any platform where Python (and a C/C++ compiler) is available. Windows users can download a binary version for Python 2.2 and Python 2.3. What's new? ----------- Finished the previously incomplete modules and added the corresponding documentation. For a list of other minor bug fixes and enhancements see the change log. There has been release 1.0 available for a couple of days but the binary for Python 2.2 was broken and the source zip contained a modified version of the pre-generated file cgtypes.c which didn't work on Linux. Release 1.0.1 is fixing these issues. If you were among those who downloaded release 1.0 and you got it to work then you don't have to download 1.0.1 again as there's no difference in functionality. For more information, visit: http://cgkit.sourceforge.net - Matthias - From riquito at riquito.matrix Thu Sep 25 09:51:05 2003 From: riquito at riquito.matrix (Riccardo Attilio Galli) Date: Thu, 25 Sep 2003 15:51:05 +0200 Subject: send email References: Message-ID: On Thu, 25 Sep 2003 11:46:16 +0100, Peter Nuttall wrote: > here is a program to send emails with python. It was writien quickly so it is > not perfect. > [SNIP] > > if anyone has any comments I would like to see them. > > Peter peter, your program write 'e-mail' absolutely not rfc2822 compliant. read http://www.faqs.org/rfcs/rfc2822.html to know how should be a real e-mail message This is an example of how the simplest e-mail should look like: ====================================== From: John Doe To: Mary Smith Subject: Saying Hello Date: Fri, 21 Nov 1997 09:55:06 -0600 Message-ID: <1234 at local.machine.example> This is a message just to say hello. So, "Hello". ====================================== remembering that every line MUST end whit "\r\n" Please try to make your program sending correct e-mail, because it's hard to develop parser which understand e-mail written in non standard format. Ciao, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From newsgroups at jhrothjr.com Tue Sep 9 09:12:03 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 9 Sep 2003 09:12:03 -0400 Subject: set built-in func_code? References: Message-ID: "Birgit Rahm" wrote in message news:bjk4v2$6iv$07$1 at news.t-online.com... > > > Hello newsgroup, > > I want to set the built-in func_code in my function, how can I does this in > the correct way? > My books dont tell me anything about this. Check the index of the Python Reference Manual. You don't, in general, want to set that value even though it's settable. At least, you don't unless you've got an unusual amount of dynamism in your program. I'd suspect the reason your help system is looking for the code object is to find out the function name, which is in the compiled code object. John Roth > > TIA, Birgit > > From __peter__ at web.de Sat Sep 6 11:30:04 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 06 Sep 2003 17:30:04 +0200 Subject: Help with a utility class and having a method call another method from within References: <37500ed8.0309051159.1eef42c5@posting.google.com> Message-ID: Ian wrote: > I have written this utility class that has a method which calls > another method. I don't want to pass in the self parameter and was > wondering by doing this does it make the function to be private or > uncallable outside of the class. For new style classes, you can write methods without a self parameter: class Sample(object): def test(arg): print arg test = staticmethod(test) # this is crucial def indirect(self, arg): Sample.test("indirect(%s)" % arg) def __mangled(self): # transformed into _Sample__mangled by the compiler pass def _privateByConvention(self): pass and then call it with a class or instance: Sample.test("from class") instance = Sample() instance.test("from instance") instance.indirect("from instance") In Python, privacy is rather a gentlemen's agreement. You can start a method name with a single underscore "_" to signal "use at your own risk". Two underscores trigger some name mangling by the compiler and can be used to avoid name clashes. Occasions where this is useful, e. g. to protect a method against overriding in a subclass, should be rare. Peter From llothar at web.de Wed Sep 17 09:43:33 2003 From: llothar at web.de (Lothar Scholz) Date: 17 Sep 2003 06:43:33 -0700 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <6ee58e07.0309170543.354e65b0@posting.google.com> "John Dean" wrote in message news:<3f65f7e6$0$10993$fa0fcedb at lovejoy.zen.co.uk>... > Hi > I would like to announce, for real this time, the release of BlackAdder > V1.0.0. We have just finished our weekly conference during which I was give > specific instructions by Shawn Gordon to make this announcement > > I have uploaded the demos to http://www.rygannon.com and to > http://www.totalrekall.co.uk How about a useable trial version instead of demos. As long as i can't try it out for 30 days in real work (saving files) i will never consider buying it. From skip at pobox.com Wed Sep 3 17:06:47 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 3 Sep 2003 16:06:47 -0500 Subject: python 2.3, cvs module specific question In-Reply-To: <3f565440$0$1114$6c56d894@feed0.news.be.easynet.net> References: <3f565440$0$1114$6c56d894@feed0.news.be.easynet.net> Message-ID: <16214.22503.138317.693442@montanaro.dyndns.org> Bernard> But this is rejected: Bernard> inf = file('data.csv') Bernard> headers = inf.readline().split(';') Bernard> rd = csv.DictReader( inf, headers, delimiter=';' ) Bernard> for row in rd: Bernard> # ... This is a known problem. For the time being, define a new dialect class and pass it in. If you know what the delimiter is, it's easier to define a class than call the sniffer. class semi(csv.excel): delimiter = ';' inf = file('data.csv') headers = inf.readline().split(';') rd = csv.DictReader(f, headers, dialect=semi) for row in rd: ... Bernard> If DialectReader does indeed not accept the optional "fmtparam" Bernard> then at least the documentation needs fixing. But then again I Bernard> may just be misreading it.... No, it's just a bug in my implementation. Skip From pinard at iro.umontreal.ca Tue Sep 23 21:06:31 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 23 Sep 2003 21:06:31 -0400 Subject: How to tell if a forked process is done? In-Reply-To: <879b6a51.0309231547.428214f7@posting.google.com> References: <879b6a51.0309231547.428214f7@posting.google.com> Message-ID: <20030924010631.GA26263@alcyon.progiciels-bpi.ca> [John Lin] > I want to know how to tell if a forked process is done. A few people suggested `os.system()' already, and I presume this is what you want and need. In the less usual case you want concurrency between Python and the forked shell command, for only later checking if the forked process is done, the usual way is to send a zero signal to the child using `os.kill()'. The zero signal would not do any damage in case your forked process is still running. But if the process does not exist, the parent will get an exception for the `os.kill()', which you may intercept. So you know if the child is running or finished. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 04:04:03 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 09:04:03 +0100 Subject: Explaining how a (Mind) program works References: <3LOdnYcq9oVxiOmiU-KYuA@metrocast.net> <3f748bc6@news.victoria.tc.ca> Message-ID: On 26 Sep 2003 11:56:06 -0800, uj797 at victoria.tc.ca (Arthur T. Murray) wrote: >> Programming languages are for controlling computers, >> not for communicating with people. Oh dear. I hope I never have to maintain any of your code :-( Actually, getting serious, I'm not going to jump to any conclusions about your coding style and I agree that access to the original author/earlier maintainers/additional documentation can be a great help when trying to understand code. It is easy to believe that your code expresses the 'why' as well as the 'how' when you are familiar with it, but to learn otherwise when someone else has to read it. But still, I think that statement is simply false. Source code should not just written to control computers, but also to be understood and maintained by people. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From achrist at easystreet.com Wed Sep 10 19:29:43 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Wed, 10 Sep 2003 16:29:43 -0700 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> <3F5F8742.C1C66903@engcorp.com> <3F5F95B9.A8CB5786@easystreet.com> <3F5F9A8C.CA54DD5D@engcorp.com> Message-ID: <3F5FB3E7.C17FF181@easystreet.com> Peter Hansen wrote: > > The real question might be why would you want to? > > If you don't want a thread, but you want something which takes > input from elsewhere and does some processing, then returns > control to some other place until more data is available (which > is what one might assume if threads aren't good for you), there > is already a convenient solution: the subroutine. ;-) > > Seriously, what's the requirement driving the need for this? > (I suspect Erik Max's answer is still what you need, and you > misunderstand the nature of what he was suggesting, but if you'll > explain the specific case you have in mind we'll know for sure.) > No, I didn't say that I didn't want a thread. If there are no serious drawbacks to relying heavily on threads, I'd be glad to use them. This would be deluxe. There really isn't any need for a generator, but it is a very nice way to construct the input side of a program (the caller doesn't have to worry about expicitly calling initialization and finalization). Some kind of through-the-looking-glass version of a generator would be a very nice way to construct the output side. I decided to test threads to see what happens: -------------Warning, Code Follows--------------------- import Queue import thread import time queues = [Queue.Queue()] threads = [] appendLock = thread.allocate_lock() def TransferData(queues, atPos): while len(queues) < atPos + 1: pass inputQueue = queues[atPos] outputQueue = Queue.Queue() appendLock.acquire() queues.append(outputQueue) appendLock.release() while 1: data = inputQueue.get(True) outputQueue.put(data, True) startTime = time.time() for i in range(1000): print i, threads.append(thread.start_new_thread(TransferData, (queues, i))) queues[0].put(i, True) appendLock.acquire() print queues[-1].get(True) appendLock.release() print time.time() - startTime --------------Warning Discussion Follows ------------------------- Running this on my Windows NT 200 NHz machine gave decent results. With 1000 threads and 1000 Queues, memory used was 24MB. Python takes almost 10 MB to start, so the overhead per thread + Queue is only a little over 10 kb. Passing all the messages through the chain took 2.5 minutes, so we are down around a quarter millisec for each put or get. That should be pretty good for many uses. Al From bokr at oz.net Tue Sep 30 09:00:39 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Sep 2003 13:00:39 GMT Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> Message-ID: On Mon, 29 Sep 2003 17:20:21 -0400, Lulu of the Lotus-Eaters wrote: >Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote previously: >|I just wrote a fairly simple sieve, which gave primes up to 1,000,000 >|in a few seconds (1.8GHz P4, Python code). There were 78498 primes in >|that range...at least in theory there should be less than 100 times as >|many primes in the range up to 10^8. > >Quite a few less, actually. Under Gauss' Prime Number Theorem, an >approximation for the number of primes less than N is N/ln(N). I know >there have been some slight refinements in this estimate since 1792, but >in the ranges we're talking about, it's plenty good enough. > >So I only expect around 5,428,681 primes less than 10^8 to occur. Well, >that's not SO much less than 7.8M. > >|So here's the thought - a binary file containing a complete list of >|primes up to 10^8 would require roughly 30MB (using 32 bit integers, >|which should comfortably handle your requirement). > If the object is to be able to test primeness of an arbitrary candidate number in range(10**8), I think I might just make a bit map of the 10**8 on disk, which would only be >>> 10**8/8000000. 12.5 megabytes. In fact, that's not that bad to hold in memory, but you could calculate an exact sector to seek to and read and then you can check the bit pretty fast. It might be interesting to make a timed access map for sectors, to see what kinds of seek/read delays there are on the average. But it would be hard/timeconsuming to reset/flush the OS and controller cache states to get mechanical delay info. Perhaps it has to be done at the BIOS level out of non-protected DOS or a disk mounted raw... Anyway, getting to a known (file-relative) sector and only reading that sector ought to be about as fast as you could get the info off the disk for an arbitrary number, IWT. Nth-prime and how-many-below-N would need some other representations. >I wonder if such a data structure is really necessary. Certainly it >produces a class of answers quite quickly. I.e. search for a prime, and >its offset immediately gives you the number of primes less than it. >Heck, searching for any number, even a composite occurring between >primes, works pretty much the same way. Of course, the above >approximation gives you a close answer even quicker. > >But if you are worried about disk storage, one easy shortcut is to store >a collection of 16-bit differences between successive primes. That's >half the size, and still lets you answer the desired question *pretty* >quickly (extra addition is required)... or at least generate a local >copy of Horne's data structure in one pass. > >Moving farther, even this gap structure is quite compressible. Most >gaps are quite a bit smaller than 65536, so the highbits are zeros. In >fact, I am pretty sure that almost all the gaps are less than 256. So >an immediate compression strategy (saving disk space, costing time to >recreate the transparent structure) is to store gaps as 8-bit values, >with a x00 byte escaping into a larger value (I guess in the next two >bytes). I wouldn't be surprised if most of the gaps are less than 16... I wonder what the largest gap between primes in range(10**8) is, and what the distribution of gaps might be. > >Maybe I'll try it, and see how small I can make the data... unless I do >my real work :-). > Hm, the bit map stores the same information in another form, so if you generate that, a zip compression of that ought to give an idea of how small you are competing with. You could translate the bit map to a sequence of prime counts for 8 or 16-bit chunks with a simple 2*8 or 2**16 byte table mapping bytes or 16-bit chunks to the counts of bits within them, then sum and only fiddle with one bit chunk to make an nth-prime table... The bit map ought to be pretty compressible, since all the bits at indices of a multiple of 2, 3, 5, and 7 beyond the first byte should be zero, so even as bytes, the alphabet ought to contain a lot less than 256 states. Or you could pre-compress the bit map using a mask of redundant zeroes (beyond the first chunk) generated from some smallish set of small primes like 2,3,5,7. Probably hard to beat zip though. Regards, Bengt Richter From usenet at microtonal.co.uk Mon Sep 15 15:36:26 2003 From: usenet at microtonal.co.uk (Graham Breed) Date: Mon, 15 Sep 2003 20:36:26 +0100 Subject: Win32 Com + ADO: How to compare the result of a recordset to 'nothing' In-Reply-To: <3c91a864.0309151108.5597753d@posting.google.com> References: <3c91a864.0309151108.5597753d@posting.google.com> Message-ID: logistix at cathoderaymission.net wrote: > Recordsets have a .BOF property that is similar to .EOF, but indicates > that your cursor is before the first record. If both .BOF and .EOF > are true, you have a null recordset. So something like: > > if not(rst.BOF and rst.EOF): > rst.MoveFirst() > > should work. Maybe should, but frequently doesn't. Although the books tell you to do this, I've never found it to be any use. SQL Server, at any rate, always sets the cursor to the first record, so rst.EOF is enough to test for no records. The problem comes when nothing is returned, which is different to no records being returned. (In Query Analyser, you see nothing, instead of column names with nothing underneath.) In that case, I find checking for rst.State==1 does the trick. I think BOF fails the same way as EOF in this case (if the record set's closed, it's an error to even ask where the cursor is). From the error message, I don't think this is the OP's problem, though. You would see something telling you not to do that on a closed record set. I suggest poking the object in an interpreter, and looking in pywintypes, if nobody has any better ideas. Graham From skip at pobox.com Tue Sep 30 14:39:16 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Sep 2003 13:39:16 -0500 Subject: Python Windows Source? In-Reply-To: <924a9f9c.0309300954.29b155d@posting.google.com> References: <924a9f9c.0309300954.29b155d@posting.google.com> Message-ID: <16249.52692.51406.580615@montanaro.dyndns.org> Joey> This seems like a simple question but I keep looking and can't Joey> seem to find it anywhere. Do I have to check it out directly from Joey> CVS. Is there anywhere I can download the source already Joey> compiled. All I really want is to be able to compile PIL. I don't believe there is a distribution which contains object files (compiled, but not yet linked). You can get the Python source code from here: http://www.python.org/ftp/python/2.3.1/Python-2.3.1.tgz (that's a gzipp'ed tar file), or the Windows binary installer from here: http://www.python.org/ftp/python/2.3.1/Python-2.3.1.exe There is nothing in between. Skip From gherron at islandtraining.com Mon Sep 29 16:10:57 2003 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 29 Sep 2003 13:10:57 -0700 Subject: append log file In-Reply-To: References: Message-ID: <200309291310.57700.gherron@islandtraining.com> On Monday 29 September 2003 12:53 pm, Tom wrote: > Hi, > I have a log file and of course I want to add the new information to the > end of that log file. Unfortunately I always delete the old information > and only append the current info. > > Right now I do it like this: > I call a module which consists of a class and a function. It actually > doesn't matter, but I just included it for the sake of completeness. > The module looks like this: > > class log_C: > def errorlog(self, filename, Data, d): > LogFile = file(filename, 'w') > ErrorInfo = Data[d+1] > LogFile.write(ErrorInfo) > LogFile.close() > > How can I add the new info without deleting the old info? > I tried the modes 'a' and 'a+' but they both didn't work. Actually the > data was totally unreadable! It was kind of messed up. :-( I don't know > why. Well ... A mode of "a" is the correct thing, abd it works just fine for me. So we need to know some other things to solve this problem. What platform? Is the data ascii or binary? (If binary on win32, then you probably need mode "ab" or some such) Exactly what do you mean by "messed up"? Gary Herron From tdelaney at avaya.com Tue Sep 23 18:34:26 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 24 Sep 2003 08:34:26 +1000 Subject: Memory allocation Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEBF967B@au3010avexu1.global.avaya.com> > From: Batista, Facundo [mailto:FBatista at uniFON.com.ar] > > The detail is that I *already have* the serialized object in disk, so: > > 1. Load the pickled object from disk (already must) > 2. Unpickle the object to memory (already must) > 3. Keep the "backup" pickled object in memory > 4. ... > 5. Pickle the object (already must) > 6. Compare to the backup object > 7. If different, write to disk (already must) > > So, the only overhead in the change of process is > > 1) keep the backup pickled object in memory: can do this if the > memory space overhead is not too big. > 2) compare the serialized objects: if is to prevent a > disk access, > makes the system faster. So why not just try it? Set up a number of test cases, using various amounts of data, then see what happens. It would take a lot less time to just set this up and try it than to ask questions that have no right answer. Tim Delaney From __peter__ at web.de Wed Sep 3 17:57:31 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2003 23:57:31 +0200 Subject: python 2.3, cvs module specific question References: <3f565440$0$1114$6c56d894@feed0.news.be.easynet.net> Message-ID: Bernard Delm?e wrote: > Hello, I can't seem to be able to specify the delimiter when building a > DictReader() > DictReader currently does not accept parameters for creating a dialect on the fly. See Bug #792558. > One rather convoluted workaround is the following: > > inf = file('data.csv') > d = csv.Sniffer().sniff(s) > inf.seek(0) > headers = inf.readline().split(';') > rd = csv.DictReader( inf, headers, dialect=d ) > for row in rd: > # ... > Another workaround might be (untested) class MyDialect(csv.excel): delimiter = ";" inf = file('data.csv') headers = inf.readline().split(';') rd = csv.DictReader(inf, headers, dialect=MyDialect) Of course your version should be more general, especially if you replace the literal ';': headers = inf.readline().split(d.delimiter) Peter From peter at engcorp.com Fri Sep 19 07:21:58 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Sep 2003 07:21:58 -0400 Subject: was: Re: looking for MOP documentation References: Message-ID: <3F6AE6D6.5DB1546D@engcorp.com> Christian Tanzer wrote: > > Peter Hansen wrote: > > But it doesn't really modify the *language's* behaviour in the way > > implied by a simplistic reading of the above phrase. That is, the > > "obvious" interpretation is that syntax and grammar are being affected, > > not just the behaviour of one small slice of the language, specifically > > how classes behave. In some languages the two things are not so > > separate, but in Python they seem to be. > > Are you sure? > > >>> class Nasty(type) : > ... def __new__(cls,name,bases,d): > ... return 1 > ... > >>> class Surprise(object): > ... __metaclass__ = Nasty > ... > >>> Surprise > 1 > >>> type(_) > > >>> I don't see how that changes the syntax or grammar of the language. You're just playing with types. -Peter From sheu at bu.edu Tue Sep 23 10:32:46 2003 From: sheu at bu.edu (Shu-Hsien Sheu) Date: Tue, 23 Sep 2003 10:32:46 -0400 Subject: Slicing vs .startswith In-Reply-To: References: Message-ID: <3F70598E.8020500@bu.edu> Great thanks for all the answers! I really enjoy Python and learned a lot here. -shuhsien From martin at v.loewis.de Wed Sep 24 03:53:31 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 24 Sep 2003 09:53:31 +0200 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> <299f1138.0309230818.22bc9bf6@posting.google.com> Message-ID: Peter Otten <__peter__ at web.de> writes: > While we are at it, would it be viable to "abuse" the > encoding/decoding mechanism to do case conversions? It might be viable, but I would consider it abuse: for one thing, I'm not in favour of codecs which do Unicode->Unicode conversions - IMO, a codec should convert between Unicode and byte strings. Furthermore, a codec IMO should represent a proper "encoding", which case conversions would not do. Instead, it would be much better to provide such functions in a library, e.g. by wrapping ICU. Then, case conversions should be done locale-dependent, instead of being general (as .upper currently is). The locale-dependent way would best operate on explicit locale objects, so you would spell locale_object = load_locale("German", "Plattdeutsch") up_string = locale_object.to_upper(lower_string) In that case, the upper-case function would stop being a string method, and be a locale method instead, taking a string argument. Regards, Martin From tjreedy at udel.edu Wed Sep 24 17:03:55 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2003 17:03:55 -0400 Subject: Announcement: ActiveState acquired by Sophos References: Message-ID: > As some of you have heard by now, ActiveState was acquired > yesterday by Sophos Plc, a UK-based global anti-virus company, as > described in this press release: > > http://www.activestate.com/Corporate/Communications/Releases/Press1064364490.html > > and in this open letter to ActiveState customers: > > http://www.activestate.com/corporate/letter/. Interesting timing for an anti-virus, anti-spam merge, given that I (along with too many others) have been getting several hundred virus spams a day since last Thursday. I wish you could sell UD an effective detect and delete package. Congratulations on being valued at over $200,000/employee. From what I've read, this is a decent price and a validation of your collective work. ... > While I have to get back to work (on the usual things, like adding Python >features to Komodo, help plan the next release of ActivePython, help plan >for PyCon 2004, iron out legal issues for the PSF and a few other things like >that), I'll be monitoring these lists, and welcome email questions as well -- >send them to me at DavidA at ActiveState.com. Do you have an ETA for Active Python 2.3? Terry J. Reedy From max at alcyone.com Tue Sep 9 15:21:05 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Sep 2003 12:21:05 -0700 Subject: Ternery operator References: Message-ID: <3F5E2821.4AB14E5F@alcyone.com> Michael Chermside wrote: > Uwe Schmitt writes: > > > Normaly[sic] you should simulate "C ? T : F" > > > > either by > > [T,F][not C] > > > > or > > > > (C and [T] or [F])[0] > > ... > > NOT TRUE! > > NEITHER of your options does short-circuit evaluation. The latter does, due to its use of and/or. An equivalent form including lambdas is (C and lambda: T or lambda: F)() -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Silence is the most perfect expression of scorn. \__/ George Bernard Shaw From uce at ftc.gov Mon Sep 22 17:31:04 2003 From: uce at ftc.gov (Gordon Airport) Date: Mon, 22 Sep 2003 17:31:04 -0400 Subject: Mutable strings In-Reply-To: References: Message-ID: <0omdnTV6gfvZ9_KiU-KYgw@comcast.com> Wow, that's timely! Good write-up. From __peter__ at web.de Thu Sep 18 06:45:21 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2003 12:45:21 +0200 Subject: [NEWBIE] access return values References: Message-ID: paul k?lle wrote: > hi folks, > > during the last couple of days I wrote my first small app with wxPython > and it all works pretty well, but now I'm somewhat lost. I'd like to > access the return value from a function inside an imported module (a > method of a class of that module eh?) > > ---gui.py---- > > from wxPython.wx import * > from app.py import * > > user=UserObject(config) # class instance from app.py > > the class UserObject has a function set_pwd() which returns a var, say > "ch_success" indicating success/failure wich I'd like to pass to a > Dialog to give some feedback to the user. > > but: > --in gui.py---- > > d=wxMessageDialog(self, user.ch_success,"Info:", wxICON_INFORMATION | > wxOK) > > gives: > > AttributeError: UserObject instance has no attribute 'ch_success' > > That makes sense, since ch_success is a local variable of set_pwd(), so > I tried to make it global but with very little success so far. I tried: > > --in app.py---- > > def set_pwd(someargs, moreargs) > do stuff // > ... > global ch_success > or: > return ch_success > or: > self.ch_success > > Nothing worked (but frankly, I don't really know what I'm doing here). > > Any ideas? Thanks > > Paul A function does not keep its return value between calls. You have to bind it like so: func(args) # return value lost forever value = func(args) #keep it in value and can use value in subsequent code. I can only guess that set_pwd() is a method of UserObject and ch_success an attribute: class UserObject: set_pwd(self, pwd): # your code self.ch_success = True # say, the pwd was successfully set which would be used: user = UserObject() user.set_pwd("secret") print user.ch_success Please post *real* code and the resulting tracebacks to allow for a more detailed analysis. Peter From duncan at NOSPAMrcp.co.uk Thu Sep 11 06:57:52 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 11 Sep 2003 10:57:52 +0000 (UTC) Subject: Parsing python file by statement in python References: <3F605192.5010405@netscape.net> Message-ID: Tim wrote in news:3F605192.5010405 at netscape.net: > don't really want to compile the statement until have a top level block > - have seen some scripts that do incremental command_compiles() on > readlines until they get back non-None but these obviously balls up on > statements like > > for i in range(n) : > foo(i) > bar(i) code.compile_command handles this like the interactive interpreter, the trick is to make sure you have newlines separating the lines, but no trailing newline. This simulates the interactive thing of needing a blank line to terminate the block. >>> import code >>> code.compile_command("x=3") ", line 1> >>> code.compile_command("for i in range(n):") >>> code.compile_command("for i in range(n):\n foo(i)") >>> code.compile_command("for i in range(n):\n foo(i)\n bar(i)") >>> code.compile_command("for i in range(n):\n foo(i)\n bar(i)\n") ", line 1> >>> -- 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 ben.young at transversal.com Wed Sep 10 05:56:46 2003 From: ben.young at transversal.com (Ben Young) Date: Wed, 10 Sep 2003 09:56:46 +0000 Subject: Slight metaclass confusion In-Reply-To: References: Message-ID: On Tue, 9 Sep 2003, David Mertz wrote: > ben at transversal.com (ben at transversal.com) wrote previously: > |"Metaclass Programming In Python, Parts 1 and 2" > |I get the fact that the instance of a metaclass is a class, but in > |this case I fail to see why the following does'nt work: > > Read part 2 again. It takes a while to sink in. > > Your problem is that you aren't considering the MRO of Class: > > >>> class Meta(type): > ... def __str__(cls): # Use 'return', not 'print' > ... return "I am " + repr(cls) > ... def foo(cls): > ... return "I am " + repr(cls) > ... > >>> Class = Meta("Fish", (), {}) > >>> Class.foo() > "I am " > > Class is an instance of Meta, just like you expect. Calling the .foo() > method shows this. But when you call a method, the method name is > checked in the -method resolution order- (before the metaclass is > checked): > > >>> Class.mro() > [, ] > > Fish doesn't define a method .__str__(), so Python looks in Fish's > parent, object. Well, object -does- define, .__str__(), so your call > resolves to: > > >>> object.__str__() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: descriptor '__str__' of 'object' object needs an argument > > Of course, since object doesn't define a .foo(), resolution proceeds to > the metaclass. If you want to get Class' metaclass method, you can let > Python do the magic for you: > > >>> str(Class) > "I am " > > Or if you want to be really explicit: > > >>> Class.__class__.__str__(Class) > "I am " > > Yours, David... Right I think i'm getting there now. Thanks to all those who replied! I see now that *instances* if classes must always look in their class dist because they _don't have an mro_, whereas classes do and this is always looked at first, causing the unbound method error. Does this mean function calls are done something like this (untested code) mro = getattr(obj, "mro", None) if mro: for i in mro: func = getattr(i, "function") if func: return func(*args, **kw) #Fall through return getattr(type(obj), "function")(obj, *args, **kw) Ben --- > > -- > _/_/_/ 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 bgailer at alum.rpi.edu Mon Sep 22 21:59:16 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 22 Sep 2003 19:59:16 -0600 Subject: Connect to VBA Objects? In-Reply-To: References: Message-ID: <6.0.0.22.0.20030922195446.034375c0@66.28.54.253> At 07:38 PM 9/22/2003, Kenneth Hutson wrote: >Hi, >I wonder if Python can connect to the object models exposed by Excel or Word. Use Mark Hammond's win32all. http://starship.python.net/crew/mhammond/win32/Downloads.html import win32com.client app = win32com.client.Dispatch("word.application") app.visible = 1 documents = self.app.Documents doc = documents.Add("c:\\foo.doc") etc. app = win32com.client.Dispatch("excel.application") app.visible = 1 app.WorkBooks.Open("c:\\foo.xls") etc. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From xy at nikolaidis.com Thu Sep 25 08:05:19 2003 From: xy at nikolaidis.com (Peter Nikolaidis) Date: Thu, 25 Sep 2003 08:05:19 -0400 Subject: MySQLdb installed, won't connect on OSX Message-ID: <88819D23-EF50-11D7-A633-00039393C622@nikolaidis.com> Greetings, I am attempting to get MySQLdb 0.9.2 installed on Mac OS 10.2 with a Fink distribution of Python 2.2.2. I have seen only a few posts on the subject, some of them relate to "conflicting header files," but I don't know what to do about conflicting header files, or where I would find them, and once I found them, which ones to remove. I have compiled MySQL 4.1 and installed into /usr/local/mysql, but since have moved to a Fink package installation or 4.0.13. Although MySQLdb appears to install successfully (I think), I am unable to connect when I try, as shown below: >>> import sys >>> import MySQLdb >>> conn = MySQLdb.connect (db = 'mydb', host = 'localhost', user = 'myuser', passwd = 'mypassword') Traceback (most recent call last): File "", line 1, in ? File "/sw/lib/python2.2/site-packages/MySQLdb/__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "/sw/lib/python2.2/site-packages/MySQLdb/connections.py", line 116, in __init__ self.converter[types.StringType] = self.string_literal TypeError: object does not support item assignment >>> My setup.py file contains the following (although I've tried many variations, commenting and uncommenting stuff with no real success): # include files and library locations should cover most platforms include_dirs = [ # '/usr/include/mysql', # '/usr/local/include/mysql', # '/usr/local/mysql/include/mysql', '/sw/include/mysql' ] library_dirs = [ # '/usr/lib/mysql', # '/usr/local/lib/mysql', # '/usr/local/mysql/lib/mysql', '/sw/lib/mysql', '/sw/lib' ] This is what happens when I build: running build running build_py not copying CompatMysqldb.py (output up-to-date) not copying _mysql_exceptions.py (output up-to-date) not copying MySQLdb/__init__.py (output up-to-date) not copying MySQLdb/converters.py (output up-to-date) not copying MySQLdb/connections.py (output up-to-date) not copying MySQLdb/cursors.py (output up-to-date) not copying MySQLdb/sets.py (output up-to-date) not copying MySQLdb/times.py (output up-to-date) not copying MySQLdb/constants/__init__.py (output up-to-date) not copying MySQLdb/constants/CR.py (output up-to-date) not copying MySQLdb/constants/FIELD_TYPE.py (output up-to-date) not copying MySQLdb/constants/ER.py (output up-to-date) not copying MySQLdb/constants/FLAG.py (output up-to-date) not copying MySQLdb/constants/REFRESH.py (output up-to-date) not copying MySQLdb/constants/CLIENT.py (output up-to-date) running build_ext skipping '_mysql' extension (up-to-date) And when I run setup.py install: running install running build running build_py not copying CompatMysqldb.py (output up-to-date) not copying _mysql_exceptions.py (output up-to-date) not copying MySQLdb/__init__.py (output up-to-date) not copying MySQLdb/converters.py (output up-to-date) not copying MySQLdb/connections.py (output up-to-date) not copying MySQLdb/cursors.py (output up-to-date) not copying MySQLdb/sets.py (output up-to-date) not copying MySQLdb/times.py (output up-to-date) not copying MySQLdb/constants/__init__.py (output up-to-date) not copying MySQLdb/constants/CR.py (output up-to-date) not copying MySQLdb/constants/FIELD_TYPE.py (output up-to-date) not copying MySQLdb/constants/ER.py (output up-to-date) not copying MySQLdb/constants/FLAG.py (output up-to-date) not copying MySQLdb/constants/REFRESH.py (output up-to-date) not copying MySQLdb/constants/CLIENT.py (output up-to-date) running build_ext skipping '_mysql' extension (up-to-date) running install_lib not copying build/lib.darwin-6.6-PowerMacintosh-2.2/_mysql.so (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/_mysql_exceptions.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/CompatMysqldb.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/__init__.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/connections.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/constants/__init__.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/constants/CLIENT.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/constants/CR.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/constants/ER.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/constants/FIELD_TYPE.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/constants/FLAG.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/constants/REFRESH.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/converters.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/cursors.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/sets.py (output up-to-date) not copying build/lib.darwin-6.6-PowerMacintosh-2.2/MySQLdb/times.py (output up-to-date) skipping byte-compilation of /sw/lib/python2.2/site-packages/_mysql_exceptions.py to _mysql_exceptions.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/CompatMysqldb.py to CompatMysqldb.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/__init__.py to __init__.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/connections.py to connections.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/constants/__init__.py to __init__.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/constants/CLIENT.py to CLIENT.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/constants/CR.py to CR.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/constants/ER.py to ER.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/constants/FIELD_TYPE.py to FIELD_TYPE.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/constants/FLAG.py to FLAG.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/constants/REFRESH.py to REFRESH.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/converters.py to converters.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/cursors.py to cursors.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/sets.py to sets.pyc skipping byte-compilation of /sw/lib/python2.2/site-packages/MySQLdb/times.py to times.pyc Any help would be greatly appreciated. Thanks, Peter From rnia at algonet.se Tue Sep 30 14:25:52 2003 From: rnia at algonet.se (.r!kard) Date: Tue, 30 Sep 2003 20:25:52 +0200 Subject: intercepting smtp email References: <5Uieb.49566$Lw6.2263065@phobos.telenet-ops.be> Message-ID: Google rules: http://home.student.utwente.nl/g.v.berg/btk/ http://pycap.sourceforge.net http://www.ghaering.de/python/unsupported/pylibpcap/ http://aspn.activestate.com/ASPN/Mail/Message/python-list/1578279 *pheew* that was some real hardcore Googeling I can tell you... .r!kard "Rudy Schockaert" wrote in message news:5Uieb.49566$Lw6.2263065 at phobos.telenet-ops.be... > Woldn't this require something like winpcap? I know some folks have > attempted to call winpcap from within Python, but I don't know if they > succeeded. If my memory serves well, it was Gerhard H?ring who did > something with it. > > I would also be interested in something similar, but then for MSN > traffic. Decoding the MSN Messenger stream is not the problem, capturing > the traffic from a promiscous nic in Python is where I get stuck. > > >>Now you got me corious, is that possible in python? > >>Possibly by extending it with som C of course... > > > > > > I've got no idea where you would put that kind of hook > > in Windows. > > > > John Roth > > >>>>>I want to write an NT service that will intercept any outgoing smtp > >>>>>traffic, like Norton Antivirus does. Can anyone tell me how I can > > do > >>>>>something like this in Python? I do not know how to intercept the > >>>>>outgoing traffic, specifically. > From scott at hcsprogramming.com Tue Sep 30 09:18:48 2003 From: scott at hcsprogramming.com (Scott Hathaway) Date: 30 Sep 2003 06:18:48 -0700 Subject: intercepting smtp email Message-ID: I want to write an NT service that will intercept any outgoing smtp traffic, like Norton Antivirus does. Can anyone tell me how I can do something like this in Python? I do not know how to intercept the outgoing traffic, specifically. Any help is greatly appreciated. Thanks, Scott From jallan at smrtytrek.com Mon Sep 22 11:24:50 2003 From: jallan at smrtytrek.com (jallan) Date: 22 Sep 2003 08:24:50 -0700 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> Message-ID: <299f1138.0309220724.7b684aa2@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:... > "Martin v. L?wis" wrote: > > > jallan wrote: > > > >> But that really doesn't work properly. According to Unicode specs and > >> German usage the uppercase of "?" is actually "SS", that is the single > >> character "?" should uppercase to two characters. > > > > Can you cite exact chapter and verse of the Unicode specs that say so? > > According to the Unicode database, > > > > http://www.unicode.org/Public/UNIDATA/UnicodeData.txt > > > > has neither an uppercase mapping, nor a lowercase mapping. > > It seems like UnicodeData.txt does not give the full story. Quoting from > http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt: > > [...] > # (For compatibility, the UnicodeData.txt file only contains case mappings > for > # characters where they are 1-1, and does not have locale-specific > mappings.) > [...] > # ; ; ; <upper> ; (<condition_list> ;)? # <comment> > [...] > # The German es-zed is special--the normal mapping is to SS. > # Note: the titlecase should never occur in practice. It is equal to > titlecase(uppercase(<es-zed>)) > > 00DF; 00DF; 0053 0073; 0053 0053; # LATIN SMALL LETTER SHARP S > [...] > > Thus, to comply with the standard, "?".upper() --> "SS" is required. Yes. Also the Unicode main charts in the annotation for 00DF state: uppercase is "SS" See http://www.unicode.org/charts/PDF/U0080.pdf This note on the character first appeared in Unicode 1.0 (published in 1991) and has been in every revision. Unicode 1.0, Volume One also lists this in the lower case to upper case casing tables on page 453. There is nothing new about this casing requirement. A further mention occurs in the Unicode 4.0 specifications in Table 4-1 in section 4.2 Case--Normative. See http://www.unicode.org/versions/Unicode4.0.0/ch04.pdf This contains the warning: << Only legacy implementations that cannot handle case mappings that increase sring lengths should use UnicodeData case mappings alone. The single-character mappings are insufficient for languages such as German. >> So is Python just another shit legacy implementation? Jim Allan From braver at pobox.com Tue Sep 9 12:12:39 2003 From: braver at pobox.com (Alexy Khrabrov) Date: 9 Sep 2003 09:12:39 -0700 Subject: A couple of OOPython questions Message-ID: <3915d531.0309090812.6a4db47e@posting.google.com> Reading python books feels a bit like reading Perl books -- although OO is there, some fundamental questions are not illuminated, and then OO comes after scripting or text, as in the Cookbook! E.g., a = b is a deep copy. How do you do shallow copy? What are the equivalent of copy constructors? Here's another OO question for some real-life application, not that puny regex fun (or was that perl? :)... I've developed a CORBA server for structural protein data, and made a simple python client for it with omniORBpy. My server wraps a huge DB2 database into a series of accessors, each returning rows from the corresponding table. Let's say I just want to view the rows. As I came to expect, the thing (perl or python) will unravel and pretty-print any hierarchy of dictionaries or lists. [I can't help it, but perl books are shorter since hash is a better term than a dictionary! Just like with graphs, where node saves you space over vertex.] OK, now I go to my python prompt and I want to inspect my objects as returned by the CORBA server. One of them represents an atom site. I merrily type just its name to see the great unknown unwrap before my eyes. Here: >>> a <MMS.StructConf instance at 0x8cb1b44> Hmm. That's not what I hoped for. Some fragments of code I saw run through my mind and I type in, >>> dir(a) ['_NP_RepositoryId', '__doc__', '__init__', '__module__', 'beg_auth', 'beg_label', 'conf_type', 'details', 'end_auth', 'end_label', 'id'] Good, we're getting somewhere. I also googled out vars(a), which seems to be the same as a.__dict__ (are they?... why is __dict__ not shown above then? 2.2...) Printing out gazillion fields by hand for each class is silly, they only wrap strings and numbers and other objects of that nature. I am ready to dive in a recursive descent. No such luck -- whoever created CORBA bindings for python didn't make those objects dictionary-like! I can't get members by name, although they _are_ in some __dict__, useless apparently, until I supply __getitem__! Is there an easy way to write something _once_, general enough, to print out a hierarchy of nested objects which just don't have __getitem__, although every field is either a string or a number or another object? Cheers, Alexy Khrabrov From bdesth.nospam at removeme.free.fr Mon Sep 1 12:34:26 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2003 18:34:26 +0200 Subject: HELP : class and variables In-Reply-To: <5c184570.0309010801.2353a3cc@posting.google.com> References: <5c184570.0309010801.2353a3cc@posting.google.com> Message-ID: <3f5372a8$0$16192$626a54ce@news.free.fr> vincent delft wrote: > Sorry if my question is stupid. > I've missed something with classes. > Can you explain the following ? > class test: > var1=1 > var2=2 > res=var1+var2 > > t=test() > print t.res > >>>3 Until here, t.var1 means test.var1 (class variable) > t.var1=6 From here, you created a new instance variable for object t, named var1. It hides test.var1. > print t.res > >>>3 What would you expect ? 1/ assigning to t.var1 does not modify test.var1 2/ modifiying test.var1 would not modify test.res anyway ! Guess why ? Try this instead : >>> class test: ... def __init__(self): ... # create instance variables ... self.var1 = 1 ... self.var2 = 2 ... def res(self): ... return self.var1 + self.var2 ... >>> t = test() >>> t.res() 3 >>> t.var1 = 6 >>> t.res() 8 Bruno From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 20:02:47 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 24 Sep 2003 01:02:47 +0100 Subject: Thoughts on PEP315 References: <oalumvopu9afuhno85tbp2erl52rk9hht1@4ax.com> <vmv9hsp53qfi18@news.supernews.com> <medvmv0af0nsr2pkgm2fhtaq5iphtthamo@4ax.com> <t2l0nv8914nfnmbtl65265sfut8dujt40f@4ax.com> <ebt0nvckrjv0or52pdmi8ghe147006ioi9@4ax.com> <kl31nvk4j0lhsbmeg9pra3c4mh78rrkivp@4ax.com> Message-ID: <6bm1nvc7pfkqppndn0lcks0edqdqf02tra@4ax.com> On Tue, 23 Sep 2003 19:26:00 +0100, Tim Rowe <tim at remove_if_not_spam.digitig.co.uk> wrote: >On Tue, 23 Sep 2003 17:49:46 +0100, Stephen Horne >> while True : >> blah; blah; blah; blah >> blah; blah; blah; blah >> break if condition : >> blah; blah; blah; blah >> blah; blah; blah; blah > >That makes me twitchy: looks like the thin end of a wedge to Perl and >Ruby's <statement> if <condition> construct. I don't know Perl that well, and I certainly don't know Ruby. I certainly wasn't basing this on either of them. Anyway, you certainly couldn't turn the form above into a <statement> if <condition> construct. It is a part of an existing loop construct - *NOT* a statement and therefore *NOT* a conditional statement. The indentation and the ":" make it clear that it isn't a statement in its own right. If anything, it removes the possibility of a future construct like that - consider the following... while True : while True : inner_loop_stuff () break if ... : inner_loop_stuff () break if ... # inner loop ended by 'break if ...' indentation outer_loop_stuff () If the <statement> if <condition> construct became a reality, both of those "break if" lines would be legal - but with very different meanings. The first is a part of the inner loop, and that inner loops body continues afterwards. The second would be a part of the outer loop, and its outdent would mark the end the inner loop. This would be a nightmare for the parser - until it finds the colon or end-of-line (or semicolon perhaps) it simply wouldn't know which case it was dealing with. But if this is bad for the parser, just think what it would do to users! - forgetting a trailing semicolon shouldn't result in a statement which is legal yet with a significantly different meaning. In fact the semicolon on all these things at the moment is IIRC totally redundant in terms of resolving ambiguity - it is compulsory for stylistic reasons. In my mind, "break if" is not the start of a general conditional statement idea - it is a two-keyword combination in order to avoid creating a new single keyword such as "until". It may suggest a "continue if" for reasons of symmetry, but "continue" is IMO useless anyway so probably not. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From vincent at visualtrans.de Fri Sep 12 01:22:11 2003 From: vincent at visualtrans.de (vincent wehren) Date: Fri, 12 Sep 2003 07:22:11 +0200 Subject: ascii codec missing under py2exe References: <F6a8b.34398$S_.11374@fed1read01> Message-ID: <bjrl66$tod$1@news3.tilbu1.nb.home.nl> "Mark Hahn" <mark at hahnca.com> schrieb im Newsbeitrag news:F6a8b.34398$S_.11374 at fed1read01... | I'm using the MIMEText module as part of sending email with no problem until | I put it through py2exe. Then I get this error: | | LookupError: unknown encoding: ascii | | ... on this line ... | | File "email\Encoders.pyc", line 85, in encode_7or8bit | | ... which looks like this ... | | orig.encode('ascii') | | My guess is the ascii codec is not getting included in my build. Can | someone tell me how to fix this? I know nothing about how these text codecs | work. Maybe this helps: (From the py2exe homepage: http://starship.python.net/crew/theller/py2exe/) ..if your exe-file reports errors like LookupError: no codec search functions registered: can't find encoding or LookupError: unknown encoding, you should advise py2exe to include this package with the '--packages encodings' command line option. HTH Vincent Wehren | | From halley at play-bow.org Sun Sep 21 17:04:41 2003 From: halley at play-bow.org (Bob Halley) Date: 21 Sep 2003 14:04:41 -0700 Subject: How to catch socket timeout? In-Reply-To: <bkjpng$v7a$06$1@news.t-online.com> References: <bkjpng$v7a$06$1@news.t-online.com> Message-ID: <m3ad8xrgye.fsf@woof.play-bow.org> "Achim Domma" <domma at procoders.net> writes: > I'm using Python 2.3s timeout sockets and have code like this to read a page > from web: > > request = ... > self.page = urllib2.urlopen(request) > > and later: > > try: > self.data = self.page.read() > except socket.error,e: ... > except socket.timeout: ... > except timeout: ... As another poster pointed out, socket.timeout is a subclass of socket.error. (This was so you could write code that treated all socket errors alike if you wanted timeouts but didn't need to deal with them separately.) Section 7.4 of the Language Reference says: [...] When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. [...] So, all you need to do is put the socket.timeout except clause before any socket.error clause: try: self.data = self.page.read() except socket.timeout: ... except socket.error,e: ... /Bob From eric.brunel at pragmadev.com Mon Sep 1 03:57:01 2003 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 01 Sep 2003 09:57:01 +0200 Subject: How do I prevent master window from being accessed with child window present? References: <4378fa6f.0308291012.f660cdf@posting.google.com> Message-ID: <biutm7$ffs$1@news-reader5.wanadoo.fr> Marc wrote: > Hi, > > I am doing a gui application where child windows pop up with options > after the user selects particular buttons from the master window. > However, the master window is still active underneath the child > window. If they accidentally press the same button again they can get > the same copy of two child windows, and that screws up a bunch of the > database stuff that I am trying to collect. > > I have tried using the 'transient' method, and that prevents the > master window from being highlighted. But the user can still push > buttons on the master window if the child window is moved aside. > > How do I disable the master window until the child window is closed? childWindow.grab_set() HTH -- - Eric Brunel <eric.brunel at pragmadev.com> - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From rhunter007 at yahoo.com Wed Sep 17 00:24:21 2003 From: rhunter007 at yahoo.com (Rob Hunter) Date: Tue, 16 Sep 2003 21:24:21 -0700 (PDT) Subject: Fwd: Python-list digest, Vol 1 #17390 - 13 msgs In-Reply-To: <6D0AD2F5-E8C1-11D7-973E-003065F081D2@cs.brown.edu> Message-ID: <20030917042421.35821.qmail@web40911.mail.yahoo.com> > > From: anton at vredegoor.doge.nl (Anton > Vredegoor) > > Subject: Re: Is there "let binding" in > Python? > > Date: Wed, 17 Sep 2003 00:41:53 +0200 > > Organization: Hobby Computer Club News > Network > > To: python-list at python.org > > > > What's wrong with dynamic scoping? Anyway, > Python hasn't corrected > > this "mistake", Yes they have. Python now has static scoping. I think that this shows it: def test(): x = 100 f = lambda arg: arg * x def other_func(): x = 1 return f(x) print other_func() test() So what does this print? Well, if the function f used names in the environment in which it's called, then x would be one and so we'd see the answer as 1*1 = 1. That's dynamic scoping. With static scoping, function f's body uses the environment that existed when it was created. Thus, x is bound to 100, and so we get the answer 100. And 100 is what you actually get in Python. My example from before was poor. I was merely saying the IMO, a downside of mutation/assignment is that it kind of reintroduces the problems you get from dynamic scoping. This is certainly debatable, but see for example the thread that was just started on "scoping with lambda in loops"...yet another person confused by mutation/assignment. And, IMO, the problem is not with the person. see following code (I vaguely > remember *something* > > about this was fixed, and while I don't know > exactly what it was, I'm > > reasonably sure it wasn't what you write > about above, since that still > > functions the way you think is bad) > > > > import sys > > > > def test(): > > L =[] > > for i in range(10): > > f = lambda : sys.stdout.write("%s" > %i) > > g = lambda i=i : > sys.stdout.write("%s" %i) > > L.append((f,g)) > > for x,y in L: > > x() > > y() > > print > > > > if __name__=='__main__': > > test() > > > > # output : 90919293949596979899 > > So I apologize but I'm still very new at python, so I don't really understand this program, but I think what you are just showing me is that using mutation/assignment you effectively get dynamic scoping. Which is what I'm saying. But, I'll concede that assignment isn't all bad. Like whatever you are showing here I'm sure is fine. So is dynamic scoping bad? Yes. Most certainly. In the above example it perhaps isn't so clear whether or not the program should print 1 or 100. But consider this (quite realistic, though simplified) example: I write a module which provides a function circle_maker(x,y). If you give circle_maker x and y coordinates, it returns a function which takes a radius, and draws a circle with that radius at (x,y). Eg, if I want to draw 3 circles each centered at (1,2) with radii of 1, 2, and 3, I could write: c = circle_maker(1,2) c(1) c(2) c(3) But now assume the defintion of circle_maker is something like: def circle_maker(x,y): ... x = --something complicated-- ... return lambda radius: ... x ... That is, our return function (which we bound to c in this example), makes reference to the variable x. But now, if I have dynamic scoping and if I want to use circle_maker I better make darn sure that I don't have an x in the environment when I call it. Or else that value of x will shadow the intended value of x I had when I defined it in circle_maker. In short, if you have dynamic scoping, and you use "other people's functions", then you have to potentially know about all the variable names they chose so you don't use those variables too. This is a nightmare when it comes to libraries. Rob __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From jjl at pobox.com Sun Sep 28 13:13:25 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Sep 2003 18:13:25 +0100 Subject: [joke] Any tool to translate PHP to Python? References: <vnbnv0c5g01rff@corp.supernews.com> <3f75f5b8$0$20650$626a54ce@news.free.fr> <vncdncfj0csgdf@corp.supernews.com> Message-ID: <87ad8og7ka.fsf@pobox.com> Bruce Dickey <ceiesa at excite.com> writes: [...] > It seems to me that for folks migrating from PHP to Python, a > translator would be a handy tool. Especially if they have a large site > to convert. It would be a tool useful to a large number of people. We look forward to the first release, Bruce. <0.5 wink> John From bokr at oz.net Tue Sep 30 23:45:52 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Oct 2003 03:45:52 GMT Subject: append special chars with "\" References: <3f793544$0$64721@hades.is.co.za> <DIaeb.142010$hE5.4836948@news1.tin.it> <3f794cfe$0$64728@hades.is.co.za> Message-ID: <bldilg$hng$0@216.39.172.122> On Tue, 30 Sep 2003 10:36:48 +0200, Tertius <tcronj at ananzi.co.za> wrote: >Alex Martelli wrote: >> tertius wrote: >> >> >>>Is there a better way to append certain chars in a string with a >>>backslash that the example below? >>> >>>chr = "#$%^&_{}" # special chars to look out for <nit1 kind="builtin-shadowing-abuse"/> >>>str = "123 45^ & 00 0_" # string to convert <nit2 kind="builtin-shadowing-abuse"/> >>>n = "" # init new string >>>for i in str: >>> if i in chr: # if special character in str >>> n+='\\' # append it with a backslash >>> n+=i [Note that n+=i comes _after_ n+='\\' -- cf nit3] >>>print "old:",str >>>print "new:",n >> >> >> If you can afford some a priori preparation, make a dictionary >> once and for all that maps each character (that isn't to be >> represented by itself) to the string that represents it. E.g., >> if you inevitably start with a chr string as above, you can >> make the dictionary as follows: >> >> charmap = {} >> for c in chr: charmap[c] = c+'\\' <nit 3> for c in chr: charmap[c] = '\\'+c </nit3> >> >> You can also write out the dict literal directly, and in >> any case you only need to prepare this charmap once and >> can then use it to prepare any number of translations. >> >> Once you have this charmap, you can use its get method to >> get the translations -- and prepare a *LIST OF STRINGS* to >> be joined up at the end, that's MUCH, *MUCH* faster than >> a loop using += on a string: >> >> pieces = [charmap.get(c,c) for c in str] >> >> and finally: >> >> n = ''.join(pieces) >> >> >> Alex >> > >*MUCH* nicer :) >Thanks! Re nits: Alex must have been doing this while talking on the 'phone and playing bridge or I think he would have mentioned that using builtin names (e.g., chr & str) for your variables is a bad idea. I think your comment "append _it_ with a backslash" was misleading, since the "it" was not the character, but the accumulating output. If you want to play, you can also define a translation function like the following ;-) >>> trans = (lambda f,s: ''.join(map(f,s))).__get__( ... (lambda d,c: d.get(c,c)).__get__( ... dict([(c,'\\'+c) for c in '#$%^&_{}']))) >>> print trans("123 45^ & 00 0_") 123 45\^ \& 00 0\_ >>> trans <bound method ?.<lambda> of <bound method ?.<lambda> of {'#': '\\#', '%': '\\%', '$': '\\$', '&' : '\\&', '{': '\\{', '}': '\\}', '_': '\\_', '^': '\\^'}>> (I think all the work is done up front ;-) This form is obviously easy to parameterize as to which characters you want escaped, BTW: >>> def maketrans(escaped='#$%^&_{}'): ... return (lambda f,s: ''.join(map(f,s))).__get__( ... (lambda d,c: d.get(c,c)).__get__( ... dict([(c,'\\'+c) for c in escaped]))) ... >>> trans = maketrans() >>> print trans("123 45^ & 00 0_") 123 45\^ \& 00 0\_ >>> trans = maketrans('135&') >>> print trans("123 45^ & 00 0_") \12\3 4\5^ \& 00 0_ Now Alex can <nit> me back ;-) Regards, Bengt Richter From mwilson at the-wire.com Wed Sep 3 08:12:57 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 03 Sep 2003 08:12:57 -0400 Subject: getopt issues References: <m3n0dvybyo.fsf@moroni.pp.asu.edu> <mailman.1061961589.14148.python-list@python.org> <Pine.LNX.4.44.0308271319080.18558-100000@moroni.pp.asu.edu> <mailman.1062019135.12125.python-list@python.org> <Pine.LNX.4.44.0308281021290.18558-100000@moroni.pp.asu.edu> Message-ID: <JrdV/ks/KDXd089yn@the-wire.com> In article <Pine.LNX.4.44.0308281021290.18558-100000 at moroni.pp.asu.edu>, David Bear <iddwb at asu.edu> wrote: >On Wed, 27 Aug 2003, Steven Taschuk wrote: > >> > specified in options, rather than have it through an exception and return >> > nothing? >> >> I don't think so. This is an unusual request -- normally it is >> desirable for a program to insist on correct usage, rather than > >good points. yet, my purpose is to write a filter. the problem being >that with different lpr implementations you don't know exactly what >parameters will be passed since lpr is not really standardize (at least >thats my understanding). Right. It's what you don't want if you're duplicating `ls` (for example) because ls recognizes all options no matter where in the command line they appear. It's what you want if you're duplicating the python interpreter, which has to distinguish between its own options and the options to send to the program it runs. getopt treats everything after the first non-leading-'-' argument as an argument. I haven't looked at optparse yet. I should. Command-line parsers aren't too hard to hand-roll. Main problems are handling the potential equivalence of things like "-n5", "-n 5", "-n:5" etc. Regards. Mel. From peter at engcorp.com Sun Sep 21 13:29:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 21 Sep 2003 13:29:33 -0400 Subject: Help me choose a C++ compiler to work with Python References: <616fccba.0309210907.1e35b92d@posting.google.com> Message-ID: <3F6DDFFD.4988E66A@engcorp.com> rhmd wrote: > > I use Windows XP and 98. Have very little experience with C++. Am > doing statistical and other simulations that require billions of > calculations Have you considered and investigated Numeric Python or similar products? Perhaps your assumption that you have to revert to hand-crafted C code is premature. -Peter From bokr at oz.net Tue Sep 9 14:56:56 2003 From: bokr at oz.net (Bengt Richter) Date: 9 Sep 2003 18:56:56 GMT Subject: Slight metaclass confusion References: <fd3e3161.0309090259.eaa3623@posting.google.com> Message-ID: <bjl7po$j41$0@216.39.172.122> On 9 Sep 2003 03:59:14 -0700, ben at transversal.com (ben at transversal.com) wrote: >I am slightly confused about the way metaclasses work, having read >"Metaclass Programming In Python, Parts 1 and 2" > >I get the fact that the instance of a metaclass is a class, but in >this case I fail to see why the following does'nt work: > >>>> class Meta(type): >... def __str__(cls): >... print "I am " + repr(cls) >... UIAM, you subclassed type, but you didn't override __new__, so ... >>>> >>>> Class = Meta("Fish", (), {}) became essentially a pass-through call to type, i.e., effectively the same as Class = type("Fish",(),{}) and since you passed it an empty dict to make its Class.__dict__ from, >>>> Class.__str__() went looking in Class.__dict__ for '__str__' and couldn't find it. So it went looking for it according to Class.mro(), which led to finding it in the object base class -- i.e., object.__dict__['__str__'] succeeded. But what it got was an unbound method, because neither of two things (accessing an ordinary method as an attribute of an instance object, or accessing a class method as an attribute of either and instance or its class) was happening to bind to the method. So you got a complaint. Note that it's complaining about __str__ of object, not __str__ of your class Meta. >Traceback (most recent call last): > File "<stdin>", line 1, in ? >TypeError: descriptor '__str__' of 'object' object needs an argument > Note that your def __str__(cls) *does* exist in Meta.__dict__, but that wasn't the dict used to construct Class. >Whereas this does: > >>>> class Simple(object): >... def __str__(self): >... return "I am " + repr(self) >... In this case you are not overriding __new__ either, but the search for __new__ is finding object.__new__, and that is making the object instance for you, of subtype Simple. >>>> obj = Simple() Actually, I think this amounts to Simple.__call__(), which must call cls.__new__() and go down the mro chain to find object.__new__ and call it with cls (which would be Simple). >>>> obj.__str__() Looking for __str__ in this case is looking in type(obj).__dict__ first and finding it right there. You are triggering it via attribute access, which dynamically creates the bound method that supplies the self arg. Alternatively, type(obj).__str__ should be the unbound method, to which you could pass obj, and type(obj).__dict__['__str__'] should be the plain function that becomes a method by the dynamic magic. It can be called with obj as arg like the unbound method. >I am <__main__.Simple object at 0x402f676c> > >The tutorial does mention this (slightly), but doesn't make it clear >why this is happening. I am probably missing something obvious though! > >Thanks for the help, > To get the effect you originally wanted, one way could be: >>> class Meta(type): ... def __str__(cls): return 'I am '+ repr(cls) ... __str__ = classmethod(__str__) ... def __new__(cls, name): return type.__new__(cls, name, (),cls.__dict__.copy()) ... >>> Class = Meta('Fish') >>> Class <class '__main__.Fish'> >>> Class.__str__() "I am <class '__main__.Fish'>" Interestingly, >>> str(Class) "I am <class '__main__.Meta'>" apparently the str builtin doing str(x) goes after type(x).__str__, e.g., >>> Class.__str__ <bound method Meta.__str__ of <class '__main__.Fish'>> >>> Class.__str__() "I am <class '__main__.Fish'>" vs >>> type(Class).__str__ <bound method type.__str__ of <class '__main__.Meta'>> >>> type(Class).__str__() "I am <class '__main__.Meta'>" The above is my current view of how things work. I think/hope it's pretty close, but I am not speaking from a code walk here, so there may be some details awry. Corrections welcome. BTW, the __metaclass__ class variable and how that works is something that belongs in a discussion of Python metaclass programming, but someone else can fill that in ;-) HTH and does not mislead. Regards, Bengt Richter From roberto at dealmeida.net Sun Sep 28 08:48:17 2003 From: roberto at dealmeida.net (Roberto A. F. De Almeida) Date: 28 Sep 2003 05:48:17 -0700 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> <IKScnUNBOsX4MumiU-KYgA@comcast.com> <bqeanvgel9ra3va44j090bmn2l126t340g@4ax.com> <10c662fe.0309270545.1fd5d839@posting.google.com> <7tidnd_LS5ElWOiiU-KYvQ@comcast.com> <combnv8hpr0agl0ij5ihrdvk3p4b10vs6e@4ax.com> <vnbr4m26qi8q1b@news.supernews.com> <qvrbnvgg5ji3sih8svd8i60dvhfbrs9nmi@4ax.com> Message-ID: <10c662fe.0309280448.22cfc49@posting.google.com> Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:<qvrbnvgg5ji3sih8svd8i60dvhfbrs9nmi at 4ax.com>... > All Roberto needs to do is make his class a subclass of object and it > will do exactly what he needs - somebody did think about it and that > PEP has apparently already been submitted and implemented a long time > ago. Yes, I think this is the best thing to do. It removes the (apparent or not) inconsistency, and does what I would expect from the principle of least surprise. The other solutions, like the Proxy class and Terry's suggestion of adding a comma to uni-dimensional slices (c[:-1,]) are interesting, but they are not consistent with Numeric slices. I'll keep them in mind, though. Thanks, Roberto From dkuhlman at rexx.com Tue Sep 2 18:07:39 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 02 Sep 2003 15:07:39 -0700 Subject: Python REST framework? References: <mailman.1062527045.25841.python-list@python.org> Message-ID: <bj34bb$e5gpd$1@ID-139865.news.uni-berlin.de> Jeremy Jones wrote: > > Does anyone know if there exists a Python REST (web services) > framework? I've googled and come up short. I don't think it > should be that hard to do if one doesn't exist (famous last > words). I guess one could subclass BaseHTTPServer and have > specified things to do depending on the path and the method? Not a framework, but may be of help ... Doing REST on top of Python Web application servers like Quixote and Twisted seems quite simple. Here is a link that might help: http://www.rexx.com/~dkuhlman/rest_howto.html And, here are several documents explaining how to add complex logic to a REST application using a finite state machine (FSM) model: http://www.rexx.com/~dkuhlman/fsm_howto.html http://www.rexx.com/~dkuhlman/fsmGenerate_howto.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From ed at digitallumber.net Tue Sep 2 10:41:57 2003 From: ed at digitallumber.net (Ed Stoner) Date: 2 Sep 2003 07:41:57 -0700 Subject: Bayesian kids content filtering in Python? References: <20030828161409.V40715@onyx.ispol.com> <AVA3b.9197$Pn6.1974@twister.austin.rr.com> Message-ID: <7e7439f1.0309020641.28ace8fc@posting.google.com> I've been looking at this sort of thing for a while now. I initially tried what you did about a year and a half ago and ran into some problems. I ended up writing my own http proxy, html parser, and bayes filtering code. It is being used now by Woodland Hills School District in Pittsburgh, PA. The school has 2300 computers, 6000 students, and 3 T1 lines to the Internet. Most of the problems I ran into were scalability, but there also were a fair amount of problems dealing with broken http servers (sending only \r or \n, or nothing, or not sending all of the headers, or sending wrong headers, etc.) and goofy problems with all different versions of IE. I think spambayes would probably be better than the bayes filter I wrote, and do plan in the future to try it (it has improved significantly over the last year and a half). I have gotten very good sucess though with what I have. It is significantly better than the proprietary (and expensive) filters that are out there on all counts (less false positives, much less false negatives, faster, etc.) The code and docs (and some marketing :-) are at http://www.digitallumber.com/willow. I'd appreciate some feedback from experienced python developers. "Paul Paterson" <paulpaterson at users.sourceforge.net> wrote in message news:<AVA3b.9197$Pn6.1974 at twister.austin.rr.com>... > "Gregory (Grisha) Trubetskoy" <grisha at ispol.com> wrote in message > news:20030828161409.V40715 at onyx.ispol.com... > > > > I've been snooping around the web for open source kids filtering software. > > Something that runs as an http proxy on my home firewall and blocks > > certain pages based on content. > > > > It occured to me that this might be an interesting project to be done in > > Python, probably using the same training and scoring mechanism that > > spambayes uses. > > > > Anyway - I wonder if anyone has already tried something like this? > > As Rene points out in his response,after some great advice and discussion > from Skip I gave this a try. It works very well. I added a module to a proxy > server (http://theory.stanford.edu/~amitp/proxy.html) and then 'trained' > Spambayes on top of it by going to sites that I wanted to allow (news sites) > and then ones I wanted to block (sports sites - just to test!). After a > relatively short training period (20-40 sites/pages) it started to pick up > the characteristics of positive and negative sites. It was then easy to get > it to block the negative sites. Although there were still quite a few false > positives I imagine that with a wider training suite it would have been very > accurate (based on the reported accuracy of Spambayes). > > Unfortunately, I didn't carry the work through much beyond the initial proof > of concept but I have copied the code I ended up with below. It certainly > seems to work and has application both for parental filtering and other > kinds of content management. > > Paul > > From palindrome12345 at hotmail.com Fri Sep 12 13:25:19 2003 From: palindrome12345 at hotmail.com (Preston H) Date: 12 Sep 2003 10:25:19 -0700 Subject: Embeddor Woes... References: <ab261cb1.0309101658.5357ed1a@posting.google.com> <mailman.1063286417.20657.python-list@python.org> <3f618ea9$1@shknews01> Message-ID: <ab261cb1.0309120925.642c803e@posting.google.com> That did it... I wonder why PyRun_SimpleFile or PyRun_File won't work? Do I have to recompile the python source under MSVC++.NET? "Kerim" <my at mail.ru> wrote in message news:<3f618ea9$1 at shknews01>... > PyRun_SimpleFile doesn't work for me too. > > As a workaround I suggest to replace it with: > PyRun_SimpleString("execfile('test.py')"); > > Kerim > > "Roel Vanhout" <roel at riks.nl> wrote in message > news:mailman.1063286417.20657.python-list at python.org... > > Have you tried to use embedding.cpp from the boost.python examples? It > > will show if your configuration is working OK; if it is, the problem is > > obviously in your program. At first sight I'd say that your test.py > > can't be found - did you set the right working directories? > > > > cheers, > > > > roel > > > > > > Preston H wrote: > > > > > Hello, someone may have tackled this problem before but I have > > > searched the google newsgroups up and down and I can't find anything > > > on this. I am trying to write an embedded python program in C++ that > > > will go out and execute python language in a script. > > > > > > I am using Visual C++ .NET, and I do have Multithreaded DLL(/MD) > > > turned on for the Runtime Library, I have the Python 2.2 installed and > > > their include and libs directories are set. Also, I have Visual C++ > > > .NET set to release version, mainly because I cannot find > > > python22_d.dll anywhere. > > > > > > This is the error that I get when I successfully compile this program > > > and try to run it at a dos prompt... > > > > > > The instruction at "0x77f85c41" referenced memory at "0x00000010". > > > The memory could not be "written". > > > > > > This is the source code that I am trying to test... > > > > > > #include "python.h" > > > #include <stdio.h> > > > > > > int main(int argc, char* argv[]) > > > { > > > char *filename = "test.py"; > > > > > > FILE *OurFile = fopen(filename, "r+"); > > > > > > Py_Initialize(); > > > > > > PyRun_SimpleFile(OurFile, "test.py"); > > > > > > Py_Finalize(); > > > > > > return 0; > > > } > > > > > > Like I said earlier, the program compiles without any hitches. Any > > > help on this is appreciated very much! > > > > > > -- > > > > -- > > Roel Vanhout - Programmer/Systems Administrator > > RIKS BV > > Papenstraat 8 - 6211 LG Maastricht > > Tel +31 (0)43 388 3708 - Fax +31 (0)43 325 3155 > > > > From roy at panix.com Mon Sep 29 09:41:20 2003 From: roy at panix.com (Roy Smith) Date: Mon, 29 Sep 2003 09:41:20 -0400 Subject: Checking for invalid keyword arguments? References: <roy-B6EED5.17061128092003@reader2.panix.com> <3F782F6D.29E0CF5F@engcorp.com> Message-ID: <roy-7B587B.09412029092003@reader2.panix.com> Peter Hansen <peter at engcorp.com> wrote: > By the way, you didn't explain why you don't want to get passed arguments > you didn't expect. Can't you simply ignore them? I'm taking some early prototype code and changing the API around a bit as the design evolved. I thought I had changed everything, but had a bug due to having missed a change in one place. I was calling a routine using the old API and the now incorrect argument was just being silently ignored. Upon further consideration (i.e. having several people point out the obvious to me!), I've come to realize that I don't really need the kwArgs mechanism at all. The simplier default mechanism does exactly what I want! Not clear what got me thinking I needed something more complicated in the first place. Thanks for the help. From follower at iname.com Mon Sep 15 05:33:47 2003 From: follower at iname.com (Follower) Date: 15 Sep 2003 02:33:47 -0700 Subject: Finally found a use for lambda! References: <roy-FFBAC5.22283914092003@reader2.panix.com> Message-ID: <d2f38965.0309150133.4aef2253@posting.google.com> > Of course, now that I think about it, I could have also written: > self.assertEqual (foo.has_key ('bar')), 0) ObMinimalism attempt: self.failIf(foo.has_key('bar')) From bdesth.nospam at removeme.free.fr Tue Sep 9 19:11:09 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Wed, 10 Sep 2003 01:11:09 +0200 Subject: virtual inner classes in python? In-Reply-To: <opru86ohov5j9jb9@news.tiscali.dk> References: <opru86ohov5j9jb9@news.tiscali.dk> Message-ID: <3f5e5b7f$0$27047$626a54ce@news.free.fr> kasper graversen wrote: > hello there. > > I've just started learning python. I see methods are declared virtual by > default as in Java. No. Methods are virtual. period. No 'declared' and no 'default'. > Nice. However, the inner class construct seems to be > even weaker as that of Java. Not nice! :-( Why are inner classes not > virtual? They are. > will they be in a near future? They already are. > What other language can you > recomend, if python cannot provide what I need? <troll> Assembly ?-) </troll> > My problem is that in the __init__ below, I cannot instantiate "Foo" but > have to explicate "Test.foo".. Foo is not defined in the global namespace, so you must tell in which namespace it is to be found. > secondly, I want to instantiate the "Foo" > in test2 rather than in tester in the current example.. Replace 'lala = Test.Foo()' with 'lala = self.Foo()'. How can you hope Python to instanciate Test2.Foo when you tell it very explicitely to instanciate Test.Foo ?-) > class Test: > def __init__(self): > lala = Test.Foo() > lala.show() (I assume that indention went wrong when copying, and that the following line should be at the same level that the __init__().) > class Foo: > def show(self): > print "Test.foo.show" > > > class Test2(Test): > class Foo: > def show(self): > print "Test2.foo.show" > > > if __name__ == "__main__": > start = Test2() > > Try this instead : class Test: def __init__(self): f = self.Foo() f.show() class Foo: def show(self): print 'Test.Foo' class Test2(Test): class Foo: def show(self): print 'Test2.Foo' t = Test() t = Test2() HTH Bruno From alberto.mantovaniNOSPAM at bologna.marelli.it Sat Sep 27 09:35:00 2003 From: alberto.mantovaniNOSPAM at bologna.marelli.it (Alberto Mantovani) Date: Sat, 27 Sep 2003 13:35:00 GMT Subject: pythonwin from dos References: <3f731176.33482654@powernews.libero.it> <vn66jje743n725@news.supernews.com> Message-ID: <3f7591fe.1890578@powernews.libero.it> On Thu, 25 Sep 2003 12:40:10 -0400, "John Roth" <newsgroups at jhrothjr.com> wrote: > >"Alberto Mantovani" <alberto.mantovaniNOSPAM at bologna.marelli.it> wrote in >message news:3f731176.33482654 at powernews.libero.it... >> hi, >> how is it possible to run a python script in the pythonwin >> environment from dos command line? >> If I use the command "/run scriptname.py" and the pythonwin is already >> opened I get error, so someone can help me? > >Why do you want to run it in Pythonwin? To run a script from >one of the command lines, the correct command is: > > python scriptname.py parameters.... I know this, but my problem is to run the script in pythonwin from dos when pythonwin is already opened. From jjl at pobox.com Sat Sep 20 16:57:26 2003 From: jjl at pobox.com (John J. Lee) Date: 20 Sep 2003 21:57:26 +0100 Subject: numarray.linear_algebra.eigenvectors bug ? References: <37cbc1de.0309191328.1ff3e822@posting.google.com> Message-ID: <87ad8zp495.fsf@pobox.com> eugene_druker at yahoo.com (Eugene Druker) writes: > I need eigen values and vectors for symmetric matrices (like VCV). > Solving with numarray and testing the results, I've got > strange results - input and output matrices of some sizes are [...] You'll probably be much better off posting this to whichever mailing list the numarray people use. Google for it. HTH John From jack at performancedrivers.com Mon Sep 8 22:16:00 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 8 Sep 2003 22:16:00 -0400 Subject: What is marketing? In-Reply-To: <4RNX/kKkXgeM092yn@gnosis.cx>; from mertz@gnosis.cx on Mon, Sep 08, 2003 at 03:11:52PM -0400 References: <mailman.1062969251.5905.python-list@python.org> <qU9W/kKkXURB092yn@gnosis.cx> <mailman.1062983352.15417.python-list@python.org> <qnY6b.42704$R32.1360114@news2.tin.it> <eIMX/kKkXswV092yn@gnosis.cx> <mailman.1063044013.17856.python-list@python.org> <Uc47b.46580$R32.1483053@news2.tin.it> <KGNX/kKkX4cC092yn@gnosis.cx> <4RNX/kKkXgeM092yn@gnosis.cx> Message-ID: <20030908221600.A7418@localhost.localdomain> On Mon, Sep 08, 2003 at 03:11:52PM -0400, Lulu of the Lotus-Eaters wrote: > |> The neutral word that Alex is looking for is 'promotion', which has a > |> subtle but important difference from the dirty word. > > Alex Martelli <aleax at aleax.it> wrote previously: > |Nope -- it's "marketing" as defined in textbooks of economics > > Ahh... that begs the question[*]. > [*] Has anyone else noticed how horribly misused this phrase has > become... Amen! Everyone please read this good explanation and then stop using the phrase. http://gncurtis.home.texas.net/begquest.html Apparently people have noticed becuase googling for 'begs the question definition' turns up a lot of rants. > IOW, I'm more interested in what Thorstein > Veblen would say than in what Ludwig von Mises would say :-). Hmm, Veblen was an idiot and Mises was rational. Err, thats not it, Veblen thought everyone was an idiot and Mises thought everyone was rational. I always get that mixed up. -jackdied From sismex01 at hebmex.com Tue Sep 2 09:41:14 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 2 Sep 2003 08:41:14 -0500 Subject: Polymorphism the Python way Message-ID: <F7DB8D13DB61D511B6FF00B0D0F0623305FA3E08@mail.hebmex.com> [Graham Fawcett] >Then you can access the attribute as `someobj.thing`. > >Given that you hate getters, and that you didn't title your >message, "Encapsulation the Python Way", accessing instance >attributes directly is fair game. ;-) [Daniel Klein] > Yes, I could do this, but a method provides better control over the > state. In that case you should use a Property, which is accessed as an ordinary attribute, but it has (up to) three hidden methods bound to it, a getter, a setter and a deletter; it seems to be just what the doc ordered, for you that is. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From jacobsmail at gmx.net Mon Sep 15 17:02:37 2003 From: jacobsmail at gmx.net (Jacob H) Date: 15 Sep 2003 14:02:37 -0700 Subject: Ways to improve this clock algorithm? Message-ID: <33fbf9ec.0309151302.462db544@posting.google.com> Hello all, I'm close to being a novice programmer and I never was good at math. So I'm curious to know ways in which this following code can be made more efficient, more elegant. The code just calculates and displays elapsed wall clock seconds since initialization. class ExampleTimer: def __init__(self): self.start = time.clock() def run(self): while 1: now = time.clock() allseconds = int(now) = int(self.start) seconds = 0 minutes = 0 hours = 0 for n in range(1, (allseconds + 1)): seconds += 1 if n % 60 == 0: minutes += 1 seconds = 0 if n % 3600 == 0: hours += 1 minutes = 0 print "%s hrs %s min %s sec" % (hours, minutes, seconds) time.sleep(1) app = ExampleTimer() app.run() I am grateful for any suggestions and advice. :) Jake From anton at vredegoor.doge.nl Mon Sep 1 05:30:12 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 01 Sep 2003 11:30:12 +0200 Subject: Aspect oriented Everything? References: <32cc321c.0308221316.2f5793ac@posting.google.com> <3F52BB3C.70406@managesoft.com> Message-ID: <biv3j9$h3c$1@news.hccnet.nl> Clifford Heath <cjh_nospam at managesoft.com> wrote: <snip> >Proprietry standards for basic technologies are doomed. Right. However the previous long piece of text lead me to read this the exact opposite way of what is written above at first. Is this a perceptual illusion trick or is it my bad? Never mind, all's well that ends well :-) Anton From aleax at aleax.it Sat Sep 27 12:34:56 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Sep 2003 16:34:56 GMT Subject: why the inconsistency? References: <fbf22ff1.0309231704.3f324abf@posting.google.com> <4bh3nv0esljf8pkegog0lc4lmg87siv1oc@4ax.com> <CxWcb.172171$R32.5498673@news2.tin.it> <bl1dra$j30@newton.cc.rl.ac.uk> Message-ID: <Q_idb.179403$R32.5743467@news2.tin.it> Richard Brodie wrote: > > "Alex Martelli" <aleax at aleax.it> wrote in message > news:CxWcb.172171$R32.5498673 at news2.tin.it... > >> I'm not sure how you'd compute log on integer numbers. Anyway, >> if you're in a hurry to know the number of digits in 2**64 -- I >> see math.log(x,10) taking about 4 usec per loop, len(str(x)) about >> 6.3, in each case with x=2*64 and measuring with timeit.py >> (elapsed time, as I'm measuring on Linux). > > And if you're really in a hurry 64 * log10(2) is good too ;) Yep, but it doesn't generalize to an 'x' computed elsewhere, when all you know is that it's some big integer and need to know how many digits its decimal representation will take. Alex From adalke at mindspring.com Tue Sep 23 21:38:28 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 24 Sep 2003 01:38:28 GMT Subject: Bottleneck? More efficient regular expression? References: <3f7069db_4@corp.newsgroups.com> Message-ID: <oA6cb.1241$RW4.485@newsread4.news.pas.earthlink.net> Tina Li: > I've been struggling with a regular expression for parsing XML files, > which keeps giving the run time error "maximum recursion limit > exceeded". [ ... in reply to David Eppstein ...] > I'd like to know what caused theover-limit as well. When matching a pattern against a string, an ambiguity may arise. For example the pattern "AX|AY" when matched against text which starts with "A" can match the "A" in "AX" or the "A" in "AY". There are different ways to resolve this ambiguity. The standard way is to use push the current state on the stack and try the first possible path. Every ambiguity gets its own push on the stack. If that path fails, the system backtracks by popping the state off the stack and trying the next possibility. Every ambiguity point causes a stack push. (Well, not quite. It's possible to collapse some of the ambiguity in some cases. For example, Python's sre regular expression system recognizes the common prefix and changes the above pattern into "A|[XY]".) In your pattern you used .*? frequently. The thing about . is that it can match the "<" character, so every time you have a .*?< you have an ambiguity. Since you use non-greedy .*?, it takes the < path first, and pushes the generic capture on the stack. What I can't figure out though is why you have any stack problems. All your ambiguities are easy to figure out, so you have at most one stack term for each .*?. I then tried to reproduce it, and wasn't able to do so. Here's my code. (I needed to use re.DOTALL because you want the .*? to capture the newline as well.) >>> import re >>> s="""<code>1cg2</code> ... <chain>a</chain> ... <settings>abcde</settings> ... <scoreInfo>12345</scoreInfo> ... <targetSeq name="1onc">blah ... </targetSeq> ... <alignment size="335"> ... <target>WLTFQKKHITNTRDVDCDNIMS</target> ... <align> :| ..| : . | . |. . :</align> ... <template>QKRDNVLFQAATDEQPAVIKTLEKL</template> ... <anotherTag>foobarfoobar</anotherTag> ... <yetAnotherTag>barfoobarfoo</yetAnotherTag> ... """ >>> pattern = (r'<code>(?P<c>.*?)</code>.*?' ... r'<targetSeq name="(?P<tn>.*?)">.*?' ... r'<target>(?P<t>.*?)</target>.*?' ... r'<align>(?P<a>.*?)</align>.*?' ... r'<template>(?P<temp>.*?)</template>.*?' ... r'<anotherTag>(?P<at>.*?)</anotherTag>.*?' ... r'<yetAnotherTag>(?P<yat>.*?)</yetAnotherTag>') >>> pat = re.compile(pattern, re.DOTALL) >>> m = pat.search(s) >>> for k, v in m.groupdict().items(): ... print k, "=", repr(v) ... a = ' :| ..| : . | . |. . :' c = '1cg2' temp = 'QKRDNVLFQAATDEQPAVIKTLEKL' yat = 'barfoobarfoo' tn = '1onc' t = 'WLTFQKKHITNTRDVDCDNIMS' at = 'foobarfoobar' >>> In any case, as others pointed out, if it's XML you should parse it as XML. You don't actually have XML (it needs to be single rooted and the <alignment size="335"> has no close tag) so assuming it was fixed, here's some code which uses the standard XML parsing libraries in Python >>> s="""<record> ... <code>1cg2</code> ... <chain>a</chain> ... <settings>abcde</settings> ... <scoreInfo>12345</scoreInfo> ... <targetSeq name="1onc">blah ... </targetSeq> ... <alignment size="335"/> ... <target>WLTFQKKHITNTRDVDCDNIMS</target> ... <align> :| ..| : . | . |. . :</align> ... <template>QKRDNVLFQAATDEQPAVIKTLEKL</template> ... <anotherTag>foobarfoobar</anotherTag> ... <yetAnotherTag>barfoobarfoo</yetAnotherTag> ... </record> ... """ >>> from xml.sax import handler >>> import xml.sax >>> class GetFields(handler.ContentHandler): ... def startDocument(self): ... self.fields = {} ... self.save_text = 0 ... self.text = None ... def startElement(self, name, attrs): ... if name == "record": ... return ... if name == "targetSeq": ... self.fields["targetSeqName"] = attrs["name"] ... elif name == "alignment": ... self.fields["alignmentSize"] = attrs["size"] ... self.save_text = 1 ... self.text = "" ... def characters(self, text): ... if self.save_text: ... self.text += text ... def endElement(self, name): ... if name == "record": ... return ... self.fields[name] = self.text ... self.text = None ... self.save_text = 0 ... >>> gf = GetFields() >>> xml.sax.parseString(s, gf) >>> gf >>> for k, v in gf.fields.items(): ... print k, "=", repr(v) ... code = u'1cg2' yetAnotherTag = u'barfoobarfoo' target = u'WLTFQKKHITNTRDVDCDNIMS' chain = u'a' scoreInfo = u'12345' align = u' :| ..| : . | . |. . :' settings = u'abcde' anotherTag = u'foobarfoobar' template = u'QKRDNVLFQAATDEQPAVIKTLEKL' alignmentSize = u'335' targetSeq = u'blah\n' targetSeqName = u'1onc' alignment = '' >>> Another approach is to turn the XML into a DOM but I have much less experience with that. (I get confused with the DOM API every time I try, and I've never needed to get that far with it.) > The file format is straighforward. Here is a sample: > > <code>1cg2</code> > <chain>a</chain> Hmmm... Looks like you're doing sequence alignments against PDB structures. Do you know about biopython.org? > So my question is: what is the bottleneck in this pattern? Could someone > more experienced in REs give some hints here? You're going to have to post your reproducible for me to help any further than this. Andrew dalke at dalkescientific.com From nhodgson at bigpond.net.au Mon Sep 22 08:21:52 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Mon, 22 Sep 2003 12:21:52 GMT Subject: Where to publish my code References: <1f0bdf30.0309212039.16c9bef0@posting.google.com> <87r829t75e.fsf@pobox.com> Message-ID: <APBbb.116957$bo1.12014@news-server.bigpond.net.au> [Erik Lechak] > 2) Sourceforge > ... [John J. Lee] > Just ignore their file release system (which is apparently going away > soon anyway). That's what I do -- treat it as free web space. All > you need is scp and ssh. After a couple of months of doing this I received a request to move the files from the web space to the release system. May depend on how often your files are downloaded. Neil From BjornPettersen at fairisaac.com Tue Sep 16 14:58:34 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Tue, 16 Sep 2003 13:58:34 -0500 Subject: why pass statement? Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624A64@stpmsg00.corp.fairisaac.com> > From: M-a-S [mailto:NO-MAIL at hotmail.com] > > Why is there the pass statement? I think, the expression > statement would be enough: > > class C: > None > > while True: > None Sure, but None doesn't seem to be the right value: class C: 42 while 1: 42 -- bjorn From tjreedy at udel.edu Thu Sep 4 12:55:27 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 4 Sep 2003 12:55:27 -0400 Subject: basic language question References: <bj7ots$48j$06$1@news.t-online.com> Message-ID: <VUidncLV5oQd88qiU-KYvw@comcast.com> "Stephan Diehl" <stephan.diehl at gmx.net> wrote in message news:bj7ots$48j$06$1 at news.t-online.com... > Once in a while, I get bitten by the fact, that mutating list methods such > as 'append' or 'extend' return None instead of the (mutated) list itself. > Is there a compelling reason for that? I googled around, but didn't find > anything about this. Some people, including GvR, think in-place mutators should not return anything to distinguish them from methods which return a new object and leave original untouched. One argument, I presume based on some experience, is that if both types of method look the same, people will forget difference, leading to obscure bugs. Others, confident in their ability to remember and not make mistakes, want mutated object returned so they chain methods togethers. While Python is generally a consenting-adults language, this is one place where Guido opted for the supposedly 'safer' choice. 'Returners' could wrap no-return mutators with functions or derived-class methods that do return the object, but I have never seen anyone post a complete module that does so for, say, all list mutators. Terry J. Reedy From pweldon at mindspring.com Sun Sep 21 17:15:09 2003 From: pweldon at mindspring.com (Phil Weldon) Date: Sun, 21 Sep 2003 21:15:09 GMT Subject: python script as an emergency mailbox cleaner References: <mailman.1064166807.8722.python-list@python.org> Message-ID: <xxobb.50052$Aq2.31203@newsread1.news.atl.earthlink.net> Yes, I tend to discount your advice because it may be that you aren't considering the messages generated by Worm.Automat.AHB are a very restricted subset of spam, the legitimate 'undeliverable e-mail' messages are closely related, and the 'undelivered e-mail' messages caused by Worm.Automat.AHB generated e-mail with the target e-mail address in the FROM line are also closely related. The current need is a quick way to counter the 'spam' effects of Worm.Automat.AHB, not correctly categorizing Nigerian fund transfer and Viagra spam sets. To further explain, the bogus 'undeliverable e-mail' type messages are permutating and the database supplying the input to the worm's generator is growing. There are at least two classes of bogus 'undeliverable mail'; 1. e-mail generated by the worm 2. real 'undeliverable e-mail' messages that are the results of the worm using your e-mail address as the sender on bogus 'undeliverable e-mail' which then generates a legitimate but unwanted and useless 'undeliverable e-mail' message. Now, if you have the time to supply your arguments rather than cv, I'll be happy to learn. And, to quote the Inboxer help file, "The text box in the Create Filters area indicates the number of messages that were processed to build the filters. Generally, the higher the number, the more accurate the filters will become." So far the scoring Inboxer developed on the basis of the ~1500 bad and 264 good examples results in no false negatives or false positives, including correctly classifing a dozen completely legitimate 'undelivered e-mail' messages in a set of ~ 400 new messages. The -1500 bad e-mail messages have a date spread of 18SEP03 though 20SEP03 while the 265 good e-mail messages have a date spread of 1AUG03 through 20SEP03. Both sets were sent to my ISP mailbox. I will try dividing the two sets of messages into smaller sets and try the results of your suggestion on new e-mails as they collect. By the way, my current ratio of Worm.Automat.AHB instigated messages to legitimate e-mail (which for my purposes includes traditional spam) is far greater than 1500:265; it's more like 1500:50. And I guess I should download from spambayes and donate to PSF since my daughter is using Python in her physics classes at Carnegie-Mellon. Concidently, I just happened to be looking at my loose-leafed copy of Feynman's Lectures on Physics with a reference manual in the back for FORTRAN IV I had to use for physics classes. Phil Weldon, pweldon at mindspring.com "Tim Peters" <tim.one at comcast.net> wrote in message news:mailman.1064166807.8722.python-list at python.org... > [Phil Weldon] > > I don't think 'fewer' examples of bogus 'Undeliverable e-mail' > > messages will be 'better' because of the permutating and morphing > > nature of this worm generated message. 'Fewer' examples would result > > in ALL 'Undeliverable e-mail' message catagorized as objectionable > > because the number valid messages of this type is so small in the > > save e-mail that most users have. > > Which is exactly why training on "too many" such unwanted messages will make > it very difficult for the handful of legitimate messages of that sort to > score as ham. I started the spambayes project, and did most of the research > for, and coding of, its tokenizer and classifier, but you're certainly free > to ignore my ill-informed advice <wink> > . . . > > Now, if I can just find a way to charge the cost to Earthlink because > > of their failure to perform their implicit contract to provide > > reliable e-mail service. > > I suspect they already thought of that trick <wink> -- a good start would be > to read your service contract with them. > > From stephen at SPAM.theboulets.IS.BAD.net Wed Sep 17 19:44:12 2003 From: stephen at SPAM.theboulets.IS.BAD.net (Stephen Boulet) Date: Wed, 17 Sep 2003 18:44:12 -0500 Subject: Simple python cgi question In-Reply-To: <87znh3411g.fsf@flibuste.net> References: <MHGdnfoYyrH0-fWiXTWc-g@speakeasy.net> <87llsnmrw4.fsf@flibuste.net> <wG6dneAarP2YP_WiXTWc-g@speakeasy.net> <87znh3411g.fsf@flibuste.net> Message-ID: <3sScnYrZ8I14cvWiXTWc-w@speakeasy.net> I don't want report lab since I'll be using lilypond to generate the pdfs (I mentioned that I'd be calling the pdf generating program from python). What I needed to know was how to upload a file, really. I thought it might be trivial, but maybe not so ... I'll have to give the mod_python docs some study. -- Stephen Wilk wrote: > Stephen Boulet <stephen at SPAM.theboulets.IS.BAD.net> writes: > > >>Wilk wrote: >> >>>Stephen Boulet <stephen at SPAM.theboulets.IS.BAD.net> writes: >>> >>> >>>>First of all, I'm not sure that the easiest way to do this is with >>>>python ... >>>> >>>>I'd like to set up a web page that would accept a text file, process >>>>it with a local program, and then make available generated pdf and >>>>postscript files for downloading. >>>> >>>>I'd like to limit the size of the file to be uploaded. >>>> >>>>I have apache2 already up. Is this a job for (mod_)python? >>> >>>Yes why not ? >> >>I was hoping for a bit more detail ... >> > > > If you will do it in cgi, look at the cgi module, and for the pdf look > at http://www.reportlab.com > > After, try to be more precise in your question if you want more > details... > > bye > From jepler at unpythonic.net Thu Sep 18 20:35:43 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 18 Sep 2003 19:35:43 -0500 Subject: file object: seek and close? In-Reply-To: <3F69DA35.8070207@bu.edu> References: <3F69DA35.8070207@bu.edu> Message-ID: <20030919003543.GC9792@unpythonic.net> Well, I didn't have any problems running a similar program. Here's the program I wrote: f = open("/tmp/example", "w") f.write("a\nb\nc\n") f.close() f = open("/tmp/example", "r") for line in f: print line.strip(), print f.seek(0) for lines in f: print line.strip(), And here's the output: a b c a b c From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 16:30:03 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 21:30:03 +0100 Subject: When did Windows start accepting forward slash as a path separator? References: <b16e4ef7.0309251550.724a57f@posting.google.com> <qwkk08g01cnk.1cg40v1qdfe2l.dlg@40tude.net> <mailman.1064580340.26537.python-list@python.org> <vijanv0lloncphml3mcjohgjukkv1eea4p@4ax.com> <bl4gtc$lmn$0@216.39.172.122> Message-ID: <ffsbnv8bb02kuit3q25rag1sdqhse2q13q@4ax.com> On 27 Sep 2003 17:20:44 GMT, bokr at oz.net (Bengt Richter) wrote: >On Sat, 27 Sep 2003 09:47:47 +0100, Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: > >>On Fri, 26 Sep 2003 14:44:30 +0200, Ronald Oussoren >><oussoren at cistron.nl> wrote: >> >>>The fun you can have on windows, I've >>>managed to create files that cannot be removed :-) >> >>I've had that one simply by saving a web page in IE. Seriously >>annoying. >> >Do you mean windows exploder will not even delete it with right-click, delete? >Or doesn't it show up at all? (how do you know it exists? dos dir?) There was no way I could find to delete it - not even writing a C++ program directly calling the DeleteFile API call. I don't remember exact details - not even for sure whether it was Win98 or Win2000 (it was too long ago for WinXP). I do remember that the non-deletable file was in a deeply nested set of pointless folders created by saving that web site. Basically, it ended up sitting on my machine annoying me for ages - I'm not sure if a new machine or a reinstall put an end to it (it was my work machine, which tends to get fewer reinstalls). -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From achrist at easystreet.com Wed Sep 10 10:37:47 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Wed, 10 Sep 2003 07:37:47 -0700 Subject: My future Python IDE article References: <mailman.1061920192.21278.python-list@python.org> <becf4072.0309082111.4ef1783f@posting.google.com> <3f5dec0d@news.comindico.com.au> <3F5E053D.743DA13A@easystreet.com> <87k78gbxc3.fsf@pobox.com> Message-ID: <3F5F373B.886D62FD@easystreet.com> "John J. Lee" wrote: > > achrist at easystreet.com writes: > > Tom Lee wrote: > > > JEdit is fantastic. > [...] > > a bad crash -- I don't recall exactly what -- maybe a BSOD or a > > JVM crash. That's not the kind of thing I enjoy, so I haven't > > used it since. > > What platform was that (JVM, OS)? > It was WinNT SP6 with java sdk 1.4101. I figured that I had given jEdit and the JVM a fairly demanding test -- I don't have much idea how you could write an app in any language that could manage resources like memory without leaking or fragmenting at least a little once in a while, and after a run of a few weeks, something demised. It didn't really bother me much, but if it happened again, that would have bothered me. As this thread has shown, there are plenty of other options for python coders, so I moved on to try another. I see that there is a bug-fix pre-release of jEdit now out. Maybe I'll give that a try. Al From cfox at cfconsulting.ca Sun Sep 21 17:08:04 2003 From: cfox at cfconsulting.ca (Colin Fox) Date: Sun, 21 Sep 2003 21:08:04 GMT Subject: Problems with string and lists (searching and replaceing) References: <pan.2003.09.20.10.51.37.875000@hotmail.com> <bkhnpn$hgc$1@news.hccnet.nl> <bki8jq$269us$1@ID-167393.news.uni-berlin.de> <bkigtt$9jr$0@216.39.172.122> <bkim08$f8i$1@news.hccnet.nl> <pan.2003.09.21.06.55.07.16000@hotmail.com> <bkkrau$2uaqf$1@ID-67890.news.uni-berlin.de> Message-ID: <pan.2003.09.21.21.08.04.529981@cfconsulting.ca> On Sun, 21 Sep 2003 20:40:30 +0200, Ulrich Petri wrote: > "jblazi" <jblazi at hotmail.com> schrieb im Newsbeitrag > news:pan.2003.09.21.06.55.07.16000 at hotmail.com... >> I shall have a computer science class this year and I decided to use >> Python. It is my favourite language and I have used it for many years. Now >> I thought, one of our first "real" programs, in our pre-graphical and >> pre-class state, would be to write simple program that works like this: >> >> One of the pupils enters a word. It should be a valid German word >> consisting of five letters, for example 'abcde' (which is not a German >> word by the way). >> >> The the other player may enter a guess which must be a five letter word as >> well, for example 'xbxxx'. Then the system answers with the string '-*---' >> as the 'b' in 'xbxxx' was correct and at the right place as well. >> >> Had the second player entered 'xxxbx', the system had responded with >> '---.-', as the 'b' is correct but not correctly positioned. >> >> The second player must find out the original word. >> > > Hm sth. like this? > > -----code------ > def mastermind(word, guess): > if len(word) != len(guess): > return "Error" > ret = ["-"]*len(word) > counter = 0 > for lw, lg in zip(word, guess): > if lw == lg: > ret[counter] = "x" > else: > if lg in word: > ret[counter] = "." > counter += 1 > return "".join(ret) > >>>> mastermind('haus', 'hasu') > 'xx..' >>>> mastermind("jaguar", "januar") > 'xx-xxx' > -----code----- Here's an alternative. I took out the 'if lg in word' logic, since that doesn't take into account duplicates and therefore would be misleading (ie 'jaguar','jaaaaa' would return 'x.....', but there aren't 5 a's in the word). #!/usr/bin/env python import string def wordcheck(word, guess): outstr = [] if len(word) != len(guess): raise "Wrong number of letters in guess." for x in range(len(word)): outstr.append( ['-','*'][(word[x]==guess[x])] ) return string.join(outstr,'') res = wordcheck('Colin','Coolo') print res From richie at entrian.com Fri Sep 19 06:31:04 2003 From: richie at entrian.com (Richie Hindle) Date: Fri, 19 Sep 2003 11:31:04 +0100 Subject: SciTE In-Reply-To: <2JAab.111501$bo1.103684@news-server.bigpond.net.au> References: <221d8dbe.0309180716.17d73ae2@posting.google.com> <2JAab.111501$bo1.103684@news-server.bigpond.net.au> Message-ID: <sbmlmvcp1ju8qiro4rggsh2rgro6nvglvr@4ax.com> [Srijit] > I am unable to access http://www.scintilla.org/tags2api.py? [Neil] > It should be readable again. The hosting provider recently 'upgraded' > their systems. Westhost by any chance? Don't get me started. I have some security concerns about Westhost's new setup - if you (Neil, or anyone else using Westhost 2.0) want to discuss them off-list, drop me an email. I don't want to advertise potential vulnerabilities by discussing them in a public forum, and there's no point trying to discuss them with Westhost while their fans are still being hit by so much proverbial. -- Richie Hindle richie at entrian.com From stuff at slinkp.com Mon Sep 15 14:24:41 2003 From: stuff at slinkp.com (Paul Winkler) Date: 15 Sep 2003 11:24:41 -0700 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911162016.02027750@telecommunity.com> <mailman.1063342640.29560.python-list@python.org> <ipicnag7OpxdLfyiRTvUpQ@speakeasy.net> <Hqk8b.382$BS5.239@newsread4.news.pas.earthlink.net> <V_mdnZ3eKoGjif6iRTvUpQ@speakeasy.net> <3F632226.2010607@earthlink.net> <lcydnasf88GLyP6iRTvUrg@speakeasy.net> <EIL8b.6564$ZB4.1083@reader1.news.jippii.net> Message-ID: <f575e202.0309151024.2b7981ea@posting.google.com> Harri Pesonen <fuerte at sci.fi> wrote in message news:<EIL8b.6564$ZB4.1083 at reader1.news.jippii.net>... > A.M. Kuchling wrote: > > On Sat, 13 Sep 2003 13:55:59 GMT, > > Mitch Chapman <mitchchapman at earthlink.net> wrote: > It's not useless, but it is not optimal. That's a fact. If you have a > multiprocessor machine, you just waste it because Python can't run two > threads at the same time. So if you want to create a high performance > web site, then Python is out of the question for the scripting language. You're making an awful lot of assumptions there. I'm going to concentrate on one of them. First, you assume that this hypothetical high-performance website really is CPU-bound. I've never had one of those to deal with, but I won't argue. Second, I'll assume that SMP really is the most cost-effective way available to scale up your CPU power. Probably depends on the rack space you have available and maybe somebody already provided an SMP box for the job. Third, I'll assume that cacheing is already being used to the extent that it's applicable. Every website I've worked on is much more read-intensive than write-intensive. For these sort of sites, appropriate cacheing buys you a LOT. Disk space and RAM are cheap. But maybe you have an app where this isn't the case and you really can't avoid heavy CPU useage. Fourth, you seem to think that threading is the only / best-practice way to handle a lot of requests. This is the point I'm going to argue against. I'll give one counter-example because it's the one I'm most familiar with. In the Zope world, it's common to run a load balancer in front of one or more ZEO clients (processes) per processor, all connected to a single ZEO server. This is a matter of very simple configuration. It's *completely* transparent to the application, which has no idea whether you're running ZEO or have a direct connection to a dedicated ZODB database. ZEO has the added benefit of being equally applicable whether the CPUs are on one box or not. You can't say that about threading. This approach could certainly be used outside the zope world. ZEO is not rocket science, it's about 6500 lines of code plus 3100 lines of unit tests. Note also that ZEO's primary purpose is to remove one of the single points of failure; handling more requests is almost a side effect. Free threading won't help you with the point-of-failure issue. I will also mention that it's quite possible to handle a lot of requests without using threads *at all*, and the resulting code can look very nice. See twistedmatrix.com. Sure, it would be nice if a single python process could take advantage of SMP, but it's demonstrably false that python is currently "out of the question" for "high performance" web use. In fact python performs very well on the web. To say otherwise is nothing but FUD. I think the primary problem with the GIL is the bad publicity that results from faulty assumptions like this. From soundwave56 at yahoo.ca Thu Sep 4 21:34:48 2003 From: soundwave56 at yahoo.ca (Hank) Date: 4 Sep 2003 18:34:48 -0700 Subject: quick and smart way for parsing a CSV file? References: <731fc603.0309031242.4e5493ce@posting.google.com> <3F5656CA.519ABADF@easystreet.com> <bj85d3$iav$03$1@news.t-online.com> Message-ID: <731fc603.0309041734.489635e7@posting.google.com> I'm using ActivePython2.2 which has the win32 extensions included. Don't think they have a ActivePython2.3 out yet. Also I was trying out PAGE which needed 2.2. Don't have the resources to recompile for 2.3. Thanks for the help! "Michael Peuser" <mpeuser at web.de> wrote in message news:<bj85d3$iav$03$1 at news.t-online.com>... > <achrist at easystreet.com> schrieb im Newsbeitrag > news:3F5656CA.519ABADF at easystreet.com... > > Hank wrote: > > > > > > Hi, > > > > > > I have a CSV file from excel that looks like this (simplified): > > > > ......... > > > > > > import csv > > > > dicts = [] > > > > inputFile = open("SomeDurnFileName.csv", "rb") > > parser = csv.reader(inputFile) > > If you do not use Python 2.3 for some reason or other there is a third party > CSV that is fast and workes fine with Python 2.2 (but uses a different > interface of course) > http://www.object-craft.com.au/projects/csv/ > > Kindly > Michael P From domma at procoders.net Thu Sep 4 01:32:23 2003 From: domma at procoders.net (Achim Domma) Date: Thu, 4 Sep 2003 07:32:23 +0200 Subject: py2exe copies to much dlls Message-ID: <bj6iot$oe$01$1@news.t-online.com> Hi, I managed to build a simple com server with py2exe. My script only imports codecs and re, but the dist folder contains tcl84.dll, tk84.dll and win32ui.pyd. Can somebody tell me why? And how to prevent this? I don't do any gui stuff, so where does the dependency comes from? regards, Achim From amundsen463 at yahoo.com Tue Sep 9 16:00:05 2003 From: amundsen463 at yahoo.com (Craig Amundsen) Date: 9 Sep 2003 13:00:05 -0700 Subject: MySQL-Python on OS X Message-ID: <b2fb3fa7.0309091200.16f37fa4@posting.google.com> Hi - I'm trying to build the MySQL-Python module v0.9.2 on OS-X 10.2 for the latest MySQL from Fink. I have also installed the fink version of Python (2.2.2). I have made all the recommended changes to setup.py that I have been able to find. I have changed thread_safe_library from YES to NO I have changed mysqlclient = thread_safe_library and "mysqlclient_r" or "mysqlclient" to mysqlclient = thread_safe_library and "mysqlclient" and in the darwin section I have changed include_dirs.append('/sw/include') library_dirs.append('/sw/lib') to include_dirs.append('/sw/include/mysql') library_dirs.append('/sw/lib/mysql') when I run /sw/bin/python setup.py build I get this error: line 1033, in gen_lib_options File "/sw/lib/python2.2/posixpath.py", line 65, in split i = p.rfind('/') + 1 AttributeError: 'int' object has no attribute 'rfind' It looks like p is supposed to be a string containing a path, but instead is an int. I have not seen this error mentioned anywhere in my searches. Does anyone have any hints on how I can get this module to build? TIA, - Craig From aleax at aleax.it Mon Sep 22 09:01:25 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 13:01:25 GMT Subject: py2exe: dynamic module does not define init function References: <81zbb.99124$hE5.3508075@news1.tin.it> Message-ID: <FoCbb.100492$hE5.3545186@news1.tin.it> Alessandro Crugnola *sephiroth* wrote: > hi, i have already problems using py2exe.. > i'm using python 2.2, wxPython and audiere for a little mp3 player.. > > once I've build the exe with py2exe, when launching the application: > > > Traceback (most recent call last): > File "<string>", line 9, in ? > File "imputil.pyc", line 103, in _import_hook > File "<string>", line 52, in _import_top_module > File "imputil.pyc", line 216, in import_top > File "imputil.pyc", line 267, in _import_one > File "<string>", line 163, in get_code > ImportError: dynamic module does not define init function (initaudiere) > > Sincerely I don't understand the error message.. > can someone explain me the message and if there's a solution? The message is telling you that audiere.dll does NOT define the mandatory function named 'initaudiere' which it should absolutely define to allow the "import audiere" statement. If the import works fine outside of a py2exe'd environment but fails in the latter then I suspect you may be getting the "wrong" DLL in the second case (e.g. maybe you didn't copy audiere.dll to the directory in which py2exe's tweaked import expects to find it). Alex From gh at ghaering.de Tue Sep 9 10:49:20 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 09 Sep 2003 16:49:20 +0200 Subject: Unicode Newbie In-Reply-To: <20030909162009.0247ce9d.sylphaleya@hta.fhz.ch> References: <20030909162009.0247ce9d.sylphaleya@hta.fhz.ch> Message-ID: <3F5DE870.8090505@ghaering.de> Manuel Huesser wrote: > The unicode function implies that you only can use 2 ** 16 chars > (unichr supports only this range) but with a given encoding e.g. > unicode(",,,", "utf-8") i should be able to encode > up to 2** 31 chars. > > "\xfc\x12\x12\x12\x12\x12\x12" is an example for a 7 > byte utf-8 string. But on encoding i get the following > error: > > UTF-8 decoding error: unsupported Unicode code range > > Is there any possibility to do the job? You can try compiling Python with --enable-unicode=ucs4. But just because all characters map to a 0 .. 2^32 interval doesn't mean that there is a defined character for every number in the interval. So you'll still get encoding errors when you try to throw random bytestrings at the encode function. -- Gerhard From bellman at lysator.liu.se Thu Sep 18 10:46:14 2003 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 18 Sep 2003 14:46:14 +0000 (UTC) Subject: Checking if the computer is online References: <mailman.1063865847.25960.python-list@python.org> Message-ID: <bkcgfm$gu1$1@news.island.liu.se> Mickel Gr?nroos <mickel at csc.fi> wrote: > Hi all, > I have a silly question. Is there are simple way to check if the computer > is connected to the Internet? It seems this should be a pretty > straight-forward thing to do, but as I am totally unfamiliar with sockets > and such, I ask for your help before getting my hands dirty. First of all you need to define what "being online" means... Is it that your modem has dialed up your ISP and been able to establish a PPP connection? What if you don't use a modem, and instead have ethernet straight into your ISP's network equipment? If the link to your ISP's closest network equipment (switch/ router/PPP dialin) is up, but the link out from that is down -- are you "online" then? Are you online if all the links within your ISP is up, so you can reach everyone connected to the same ISP, but their peering is broken so you can't reach anyone else? What if there is a firewall somewhere between you and "The Internet", blocking you from accessing many sites, are you "online" then? How large part of Internet do you need to be able to reach to claim that you are "online"? Or must perhaps the Internet be able to reach *you* before you are considered to be online? (That means that a NAT box immediately makes you offline; I tend to like that definition. :-) Or perhaps you should tell us *why* you believe you need to check if the computer is connected to the Internet or not. Then we can go directly to telling you that it is a bad idea, and suggest what you should do instead. <0.5 wink> -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "I don't think [that word] means what you ! bellman @ lysator.liu.se think it means." -- The Princess Bride ! Make Love -- Nicht Wahr! From dokaspar at student.ethz.ch Tue Sep 30 16:27:15 2003 From: dokaspar at student.ethz.ch (Dominik Kaspar) Date: 30 Sep 2003 13:27:15 -0700 Subject: where are the "class variables"? Message-ID: <62e9c66e.0309301227.20505db6@posting.google.com> maybe my question was badly formulated. i give it a new try: why does the following program give the output "0 0" and not "1 0"? why does it loop forever? and how could that problem be fixed? import threading class Server(threading.Thread): running = 0 def run(self): running = 1 while running: print "do something here..." def stop(self): running = 0 server = Server() server.start() print server.running # should print "1" server.stop() print server.running # should print "0" From fperez528 at yahoo.com Mon Sep 8 03:00:23 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 08 Sep 2003 01:00:23 -0600 Subject: Ternary operator (Re: Ternery operator) References: <doJ6b.1999$Ft.737@newssvr22.news.prodigy.com> <3F5B6404.BD1A9709@engcorp.com> <vlo9699d77sj3e@corp.supernews.com> Message-ID: <bjh9e6$j9p$2@peabody.colorado.edu> Michael Geary wrote: > In retrospect, it seems obvious that the way the voting was conducted > insured that no ternary operator would be added to the language. Good point. I, for one, was one of the people who would have been very happy to see some form of ternary go in. While I had my favorite, my biggest concern was to have _some_ ternary, even if my favorite syntax didn't win (at least amongst the most popular, which I felt were all fairly reasonable). Oh well, this will remain one of my few pet peeves with the language for the long haul :) Cheers, f. From ta-meyer at ihug.co.nz Thu Sep 4 19:54:56 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 5 Sep 2003 11:54:56 +1200 Subject: How do I match this with re In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F13031B74D2@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AE18@its-xchg4.massey.ac.nz> > Very important to everyone working with regular expressions: > the redemo.py script. Search for a Scripts directory in your > python directories (it's under Tools on Windows, otherwise > get it from the source distribution), redemo.py is in there > along with other useful scripts. For those that like a more GUI sort of thing, I highly recommend kodos: <http://kodos.sourceforge.net> Basically the same thing but with a GUI. All in Python, of course. =Tony Meyer From corey.coughlin at attbi.com Fri Sep 5 17:03:52 2003 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 5 Sep 2003 14:03:52 -0700 Subject: Advice to a Junior in High School? References: <Ivw2b.1305$Ce2.314@clmboh1-nws5.columbus.rr.com> Message-ID: <a8623416.0309051303.72d0b489@posting.google.com> A junior in high school? First off, I wouldn't worry too much about the job market, computers aren't going to go away, there will be a need to program them for at least a little longer, and if you really love it, you'll get good at it, and being better than most is all you really need to get a job. If you're still really worried, I'd suggest a double major with electrical/computer engineering. Learning what goes on inside computers can be useful. Take it from an EE grad who wishes he'd done CS now. As far as what languages to study, I wouldn't worry about that at all at this point, any of the previous suggestions would be fine. In high school, I learned Pascal, Cobol, Basic (applesoft, if you must know) and Fortran, and guess how long I kept using those languages? First, figure out what you need to know for the AP tests, learn that language, and then figure out what languages are most popular/applicable for whatever CS specialities you're interested in. Lisp and C are good suggestions, the highbrow CS types love Lisp, and C will be useful until somebody finally puts a stake in Unix/Linux/(os written in C). Python is great if you enjoy it (and you should), C++/java/perl always make nice resume items, but that's bound to change by the time you get out of college, so keep an eye on them and see if they last. Many people have suggested learning a whole bunch of languages, and that's fine if you want to learn a whole bunch of languages, but if you enjoy programming more, then just pick the languages you need to know to program what you want, and you should be fine (for now, anyway). Keep an eye on new languages, peruse them occasionally to see if they can help you out, otherwise stick with your favorites. And in general, try to relax, I know the hypercompetitive/internet time future is scary, but like most people, you'll probably figure out some way to get by. From alanmk at hotmail.com Sun Sep 21 12:08:10 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 21 Sep 2003 17:08:10 +0100 Subject: Server-side programming References: <HAMab.1175$1l5.436@reader1.news.jippii.net> Message-ID: <3F6DCCEA.763D17C6@hotmail.com> Timo Virkkala wrote: > I'm creating a system with Python CGIs, that connect to a database. I'm > wondering about input validation. Of course I will check the length of > the passed parameters, to (hopefully) prevent any DOS attacks. What else > do I need to check? Do I need to remove any SQL from the inputs? > Anything else I might have overlooked? You might not need to remove SQL from your field values. Doing so would probably be a non-trivial string parsing exercise. Most "SQL injection" attacks would be where a cracker hopes that you are going to embed the contents of "username" and "password" fields right into a string containing an SQL query, like so mySQLString = """ select * from users where uname = "%s" and password = "%s" """ % (username, password) If the query returns a non-zero number of rows, then that username/password combination is deemed to be valid. The problem comes when the cracker deliberately subverts the content of the fields, supplying values like these, for example username='alan' password='" or 0=0 or password="' Which when embedded into the SQL query string gives the following final SQL query: select * from users where uname = "alan" and password = "" or 0=0 or password="" Which will return at least 1 row, assuming that "alan" is a valid username. Now, trying to parse the syntax of the password field, looking for SQL keywords such as "or", could be complex: there are quite a few possible ways in which the query can be textually subverted. AFAIK, the most effective way to prevent such attacks is to disable any quote characters that may be present in the password, so that they are treated as a part of the password string, not as delimiters in the SQL query string. For example import re password = re.escape(password) Which for the values given above would now give an SQL query of select * from users where uname = "alan" and password = "\"\ or\ 0\=0\ or\ password\=\"" Does anyone know of a more effective approach to preventing SQL injection attacks? Another potential attack is the "Cross Site Scripting (XSS) Attack", whereby the attacker inserts javascript into a field value, which is then embedded into the HTML transmitted by a web app to another user, for example as a post in a message board. This hostile javascript can do any number of nasty things to users browsers including stealing cookies, or url-rewritten session IDs, so that the innocent users login session can be hijacked and abused. Here is an article about XSS attacks. http://www.cgisecurity.net/articles/xss-faq.shtml AFAIK, the most effective solution to preventing XSS attacks is to ban HTML/tags/javascript from being inserted into text strings that will be displayed as part of a HTML page. This could be done by 1. Parsing the string as HTML, and stripping out <script> tags. 2. Escaping (in the HTML sense) all field inputs, to disable markup special characters such as "<", ">", etc. Does anyone know of other potential textual attacks against web pages, input forms and field values? It would be really nice to have a central, python focussed, repository of these attack techniques, and how they can be prevented with python code. Does anyone know of such a page? If we get enough information from this thread, I might start up a page about the subject. regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From sross at connectmail.carleton.ca Sat Sep 6 19:54:12 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 6 Sep 2003 19:54:12 -0400 Subject: Why python??? References: <mailman.1062790509.19411.python-list@python.org> <bjarq6$j45$00$1@news.t-online.com> <NO66b.30883$R32.926812@news2.tin.it> <bjb4hk$ohm$01$1@news.t-online.com> <Jbg6b.32033$R32.992758@news2.tin.it> <bjcbha$vmp$02$1@news.t-online.com> <8Um6b.34442$R32.1077180@news2.tin.it> <v6Cdne4p1M5Zl8eiXTWJgA@comcast.com> <kKt6b.24041$hE5.882369@news1.tin.it> Message-ID: <_ru6b.4463$I_2.688035@news20.bellglobal.com> "Alex Martelli" <aleax at aleax.it> wrote in message news:kKt6b.24041$hE5.882369 at news1.tin.it... [snip] > >> > >> attribute salary is Currency > >> "Salario mensile" > >> restriction quantity(1) > >> > >> on create code Python > >> if value[0] < minimumSalary: > >> value = [ minimumSalary ] > >> return value > >> %% > > > > My reflexive reaction was 'ugh'. My considered reaction is 'bravo'. > > Glad you reconsidered;-). I'm not enthusiastic about that %%, but we > found that relying on just indentation for that specific role (indicating > the end of embedded Python code and the return to the declarative > language) was quite error-prone (e.g. due to Python continuation lines), > so we decided we needed a marker of SOME kind or other right there, > and for now, until further development, it's that "%%" thingy. Hi. Could "end code" replace "%%" as 'the end of embedded Python code' delimiter in that language? Just curious, Sean From jjl at pobox.com Mon Sep 22 12:31:54 2003 From: jjl at pobox.com (John J. Lee) Date: 22 Sep 2003 17:31:54 +0100 Subject: Where to publish my code References: <1f0bdf30.0309212039.16c9bef0@posting.google.com> <87r829t75e.fsf@pobox.com> <APBbb.116957$bo1.12014@news-server.bigpond.net.au> Message-ID: <87he34u6md.fsf@pobox.com> "Neil Hodgson" <nhodgson at bigpond.net.au> writes: > [Erik Lechak] > > 2) Sourceforge > > ... > > [John J. Lee] > > Just ignore their file release system (which is apparently going away > > soon anyway). That's what I do -- treat it as free web space. All > > you need is scp and ssh. > > After a couple of months of doing this I received a request to move the > files from the web space to the release system. May depend on how often your > files are downloaded. I've been doing that for over a year, so it seems that low bandwidth projects like mine don't bother them much. I certainly don't remember reading anything when I signed up that requires you to use their file release system. Maybe when they roll out their new file release system (supposedly easier to use) they'll be less tolerant. John From tim.one at comcast.net Mon Sep 8 20:57:46 2003 From: tim.one at comcast.net (Tim Peters) Date: Mon, 8 Sep 2003 20:57:46 -0400 Subject: datetime: .datetime-.datetime = .timedelta, .time-.time=TypeError ? In-Reply-To: <esuolvc6tuuhfub8jtobffv722281t7p56@4ax.com> Message-ID: <LNBBLJKPBEHFEDALKOLCKEKBFMAB.tim.one@comcast.net> [Christos TZOTZIOY Georgiou] > Is there any reason for datetime.time subtraction not returning a > datetime.timedelta object, just like datetime.datetime subtraction > does? Guido didn't want time objects participating in arithmetic because the desired semantics are unclear. For example, if you allow time1 - time2 to return a timedelta, then you'll also want to allow time2 + timedelta to return a time, and then you've got to make up rules for what happens when adding spills over a midnight boundary. Should it "wrap around"? Raise OverflowError? Guido didn't want to endure arguments about that. Note that the analogous question for datetime objects is easy, because there's a well-defined Beginning and End to the span of times datetime objects can represent -- OverflowError is the obvious thing to get if you try to compute a result spilling over those bounds. Try adding "a year" to "midnight", though, and half the world will curse you if it raises an exception, while the other half will curse you if it says "hmm -- still midnight". A third half will whine about leap seconds <wink>. > It doesn't feel good having to use dumb year, month, day > arguments constructing datetime object when doing only time > arithmetic. What's wrong with using timedeltas? >>> print timedelta(hours=3, minutes=15) - timedelta(hours=2, minutes=45) 0:30:00 >>> > If there is no specific reason apart from lack of time (no pun), I'm > willing to research it and write a patch (I haven't seen the code, > but I believe it would be quite easy). Selling it would be harder than writing it. From skip at pobox.com Fri Sep 26 13:32:22 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Sep 2003 12:32:22 -0500 Subject: PEPs link gone from the Python homepage? In-Reply-To: <ur823fqiu.fsf@boost-consulting.com> References: <un0crhase.fsf@boost-consulting.com> <16244.22946.446379.622160@montanaro.dyndns.org> <ur823fqiu.fsf@boost-consulting.com> Message-ID: <16244.30758.381156.351062@montanaro.dyndns.org> >> If you find stuff in PEPs you believe belongs in the standard >> documentation set, please file a documentation bug report. Dave> Oof. MRO, descriptors, most of PEPs 252 and 253 last time I Dave> checked, just off the top of my head. Do I you really think it Dave> would make a difference to *formally* point out that many elements Dave> of the basic design of the object model aren't in the docs? Yes, it would help. We have people come to python-dev and ask, "How can I help?". It also serves as a reminder to people who can make the change that it needs to be addressed. Without it, I suspect most of us will forget it in the next couple of weeks. Dave> And, this is not a rhetorical question: how many bug reports would Dave> be appropriate for all of this information? Some of these PEPs Dave> cover several topics. I'd just file one having a subject like "migrate PEP content to documentation" to start with. Assign it to me if you feel the urge. I'm pretty sure Fred's swamped. Dave> Sure, I knew that, but while the docs are still incomplete, you Dave> use what you can, and it would be nice to be sure that the Dave> information was readily accessible. It's still readily accessible, but it's hard to see that "PEPs" should rank up there on the front page with more general concepts like "Documentation" or "Developers". Front page real estate is always at a premium. I think it's appropriate that they are referred as they are now. On matters such as this, I don't even bother with the website. My browser home page is a bunch (17) of popup menus laid out in a tabular format and a few <form>s. It has two Python-related menus: Python Python Docs ------ ----------- Python Home Page Module Index Python VM Wiki Python PEPs Python @ SF Python Wiki Python Glossary Python HOWTOs Python-Mode @ SF C/C++ API CSV mailing list Library Reference ALF @ SF Language Reference Watch @ SF Spambayes archives Psyco @ SF Python-dev archives Parnassus Python-list archives Skip's Python Bits Python-help archives That way I always know where to get at the stuff I'm interested in and am insulated from changes to the link properties of web pages not completely under my control. Skip From lefevrol at yahoo.com Thu Sep 4 10:35:58 2003 From: lefevrol at yahoo.com (Olivier Lefevre) Date: 4 Sep 2003 07:35:58 -0700 Subject: safari (was Re: Writing solid code book) References: <b15d2792.0309030339.3ac939e7@posting.google.com> <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <elC5b.11632$hE5.410636@news1.tin.it> Message-ID: <51809ae4.0309040635.6700fe17@posting.google.com> And let us not forget 3. poor customer service (you have to try real hard to reach someone) -- O.L. From mpeuser at web.de Thu Sep 18 15:37:49 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 18 Sep 2003 21:37:49 +0200 Subject: Scaling Tk scrollbar handles References: <K96dnU3ln-RTefSiU-KYvg@comcast.com> Message-ID: <bkd1fu$76o$05$1@news.t-online.com> "Gordon Airport" <uce at ftc.gov> schrieb im Newsbeitrag news:K96dnU3ln-RTefSiU-KYvg at comcast.com... > None of the online references that I'm using or can find tell you if > this can be done. ??? This is really no secret! E.g. look at at New Mexico Tech http://www.nmt.edu/tcc/help/pubs/lang.html There are two very concise as well as comprehensive documents. One about Tk, one about Python. scrollbar.set(a,b) where a is the fraction (0..1) where the thumb shall start and b where it should end... Kindly Michael P From tzot at sil-tec.gr Mon Sep 29 18:06:39 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 01:06:39 +0300 Subject: why the inconsistency? References: <mailman.1064537919.23612.python-list@python.org> <7h3brt7o2h8.fsf@pc150.maths.bris.ac.uk> Message-ID: <d7bhnv4u6jak6asrfiv592sq9itt3i1286@4ax.com> On Fri, 26 Sep 2003 18:04:24 GMT, rumours say that Michael Hudson <mwh at python.net> might have written: [I, "if only int(math.log(x,10))..."] > >> worked correctly for *all* large values, like 10**70... [Michael, using a larger number] > > Um, it does :-) [Tim] >> You're not used to answering floating-point questions <wink>. [Michael] >Or prehaps just conveniently ignoring what "work" means in a given >context :-) I didn't reply earlier since Tim --how uncommon-- covered the subject better (he also corrected my +1 omission/misteak), but I believe you should have said: 'conveniently ignoring what "work correctly" means in a given context'... ;-) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From john at rygannon.com Thu Sep 18 05:05:52 2003 From: john at rygannon.com (John Dean) Date: Thu, 18 Sep 2003 09:05:52 GMT Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <mailman.1063810287.4212.python-list@python.org> <6ee58e07.0309171548.314a046c@posting.google.com> <3y7ab.1043$Od.78860@twister.tampabay.rr.com> Message-ID: <3f697584$0$10966$fa0fcedb@lovejoy.zen.co.uk> I have to agree with the assertion that theKompany.com very slow to update the web site, hence the reason why I have sort of taken it upon myself to do something about it. I work for theKompany.com and no matter how hard I push, nothing ever seems to get done. They all agree that improvement have to be made. TheKompany.com will still handle sales but my web site will handle promotion and marketing - www.rygannon.com Even though BA is not my project (I am the co-author of Rekall - a Python programmable cross platform database independant GUI database client - sorry for the shameless plug) I will do whatever I can to keep the group and my web site up to date. One thing I would like to do it to set up a BA Forum on www.rygannon.com. Freeback, suggestions, criticism (good or bad), etc is essential for the developement and improvement of any software project. I will make sure any and all posts get a mention at our weekly conference. Therefore, I encourage anybody and everybody who has an interest in the present and future development of BA (or any other of theKompany's projects) to register as a user at www.rygannon.com. -- Best Regards John From jseb at cs.mcgill.ca Tue Sep 30 09:36:44 2003 From: jseb at cs.mcgill.ca (Jean-S?bastien Bolduc) Date: 30 Sep 2003 06:36:44 -0700 Subject: eval's local arguement ignored? References: <56e1eff0.0309230923.1215833f@posting.google.com> <21064255.0309260745.6d3d5650@posting.google.com> Message-ID: <56e1eff0.0309300536.51fdf2b0@posting.google.com> > **kwa** is the solution! > > In your factory-function *foo* you have to declare *a* > keywordarguement which is initialized with a. > > >>> def foo(): > ... a=1 > ... f=lambda x,a=a:a*x > ... return f Not exactly what I'm looking for, I'm afraid. A more complete picture is this: I'm writing a class such as this: class Foo: def __init__(self, fnc, **params): ... def evaluate(self, val) ... That has to be instantiated as, e.g.: x = Foo( 'lambda x : a*x', dict( a = 2. ) ) so that "x.evaluate( 5. )" will return, in this case, "2.*5.". The approach you describe will certainly work, but the thing is that this class will have to be used by people who don't necessarily know Python (yet). So I would really like the lambda function's parameter list to always be the same, whatever you put on its RHS. Once again, I don't understand why the "eval", as described above with "globals" and "locals" arguments specified, will not work. Is there a way to modify a function's closure? Thanks, JSeb From joshway_without_spam at myway.com Thu Sep 18 09:19:58 2003 From: joshway_without_spam at myway.com (JCM) Date: Thu, 18 Sep 2003 13:19:58 +0000 (UTC) Subject: Closures in python References: <9caba98e.0309180208.692e9b68@posting.google.com> <bkc5lv$5c4$1@news1.wdf.sap-ag.de> <HBF.20030918w8nt@bombur.uio.no> Message-ID: <bkcbdu$l0c$1@ginger.mathworks.com> Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote: > 'closure' is a much-abused word. > This is a closure over foo's x variable: > def foo(): > x = 3 > def bar(): > x += 1 > return x > return bar > f = foo() > print f() # print 4 > g = foo() > print f() # print 5 > print g() # print 4 > ...or it would be, if it worked. Python does have closures; the trouble is you can't rebind variables defined in arbitrary scopes--you can only rebind locals and globals. So you need some indirection for it to work: >>> def foo(): ... x = [3] ... def bar(): ... x[0] += 1 ... return x[0] ... return bar ... >>> f = foo() >>> f() 4 >>> g = foo() >>> f() 5 >>> g() 4 This is actually one of my biggest complaints about Python. I'd like syntactic disambiguation between definition and assignment in order to have control over which scope you're assigning into. From lupan at zamek.gda.pl Wed Sep 17 16:17:02 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Wed, 17 Sep 2003 22:17:02 +0200 Subject: Money data type References: <mailman.1063823424.16083.python-list@python.org> Message-ID: <8765jrtbk1.fsf@psi.lupan.zamek.gda.pl> look at http://fixedpoint.sourceforge.net/ it gives you numeric object for monetary applications (I have never used it) -- =*= Lukasz Pankowski =*= From see at my.signature.com Sat Sep 20 21:01:10 2003 From: see at my.signature.com (Andrei) Date: Sat, 20 Sep 2003 21:01:10 -0400 Subject: What is the meaning of the astarisk in Python References: <3f6ce54f$0$10962$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3395452.1064106070@dbforums.com> They're both shortcuts for specifying parameters. args is a tuple of positional arguments, kwargs is a dictionary of keyword arguments. Like this: >>> def myfunc(*args): .. print args .. >>> myfunc(3,4,"c") (3, 4, 'c') >>> def myfunc(**kwargs): .. print kwargs .. >>> myfunc(a=3, b=4) {'a': 3, 'b': 4} >>> def myfunc(*args, **kwargs): .. print args, kwargs .. >>> myfunc(2, 3, c=5, d=6) (2, 3) {'c': 5, 'd': 6} >>> myfunc(2, 3) (2, 3) {} >>> myfunc(c=5, d=6) () {'c': 5, 'd': 6} -- Contact info (decode with rot13): cebwrpg5 at bcrenznvy.pbz Fcnzserr! Cyrnfr qb abg hfr va choyvp zrffntrf. V ernq gur yvfg, ab arrq gb PP. Posted via http://dbforums.com From vald at valis.amber.eu.org Sat Sep 20 16:32:59 2003 From: vald at valis.amber.eu.org (K. N.) Date: Sat, 20 Sep 2003 22:32:59 +0200 Subject: XML/XSLT with Python Message-ID: <20030920203256.GA17306@bobas.nowytarg.pl> Is there any good and fast Python module for XSLT processing ? I'm going to use XML and XSLT to generate web pages, so I need XSLT processor that will be able to transform for example a DOM object in memory - I don't want to create XML file containing data and then load it and transform with XSLT, but I want to do this at once - without writing to a temporary file. Actually I've seen alot articles about parsing XML, but nothing about creating XML documents and storing it as an object that will be passed to XSLT processor, and that is what I'm planning to do. I think its a quite good solution, but I have no idea which modules will be most suitable for this task. Does anyone have some experience in this matter and could point me where should I look ? Best regards, K. From lists at webcrunchers.com Mon Sep 29 18:03:34 2003 From: lists at webcrunchers.com (John D.) Date: Mon, 29 Sep 2003 15:03:34 -0700 Subject: Python question Message-ID: <v03110709bb9e5c66d481@[192.168.0.2]> #This program gives: "SyntaxError: unqualified exec is not allowed # in function _ it contains a nested function with free variables" #I understand this is a scope problem(?) #I don't understand why this fails. It should be perfectly obvious #what z is equal to when exec sees it. Furthermore, it shouldn't care #about any other variables since it uses no others, and writes to none. #What does this mean? What is "unqualified" and how do I qualify it? #Are the free variables d or z? Is 'free' a boolean state or are there #other related qualities? #What are the various work-arounds? #I am using d as a global dictionary to store all my variables. d={} #Doesn't matter if I have d here def myfunc(): z='print' exec(z) d={} #or here... def setvar(): d[0]=1 return From rob at cs.brown.edu Thu Sep 18 17:31:17 2003 From: rob at cs.brown.edu (Rob Hunter) Date: Thu, 18 Sep 2003 17:31:17 -0400 Subject: Binding frustration Message-ID: <701E2432-EA1F-11D7-967C-003065F081D2@cs.brown.edu> So I thought I had come to peace with binding in Python, but then this happened to me: I was trying to do things the Python way (as opposed to the Scheme way) as was suggested to me, and so here's a shortened version of my program: def getGenres(title): #it takes a movie title and returns a list of genres that the movie falls into result = [] # my accumulator def inGenre(g): # g is a genre if <here I test if "title" is of genre g (using a simple Python dictionary I have collected from a mini web crawl)>: result = result + [g] # if title is of genre g, then add it to the accumulator # and then I do a number of inGenre tests: inGenre('Comedy') inGenre('Sci-fi') inGenre('Suspense') ... return result So what's wrong with this program? Well, Python tells me: UnboundLocalError: local variable 'result' referenced before assignment It seems my only choice is to move result to the global environment, but if that's not a kludge, I don't know what is. So why doesn't this work? Python lambdas are able to use "free" variables in this way. Why not a def? And more importantly, how should I get around this? Thanks all, Rob From jacek.generowicz at cern.ch Fri Sep 5 07:26:37 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Sep 2003 13:26:37 +0200 Subject: Open Source leader? (was Re: Celebrity advice) References: <mailman.1061927168.7845.python-list@python.org> <yra3b.6546$Jh2.2048@newsread4.news.pas.earthlink.net> <23891c90.0308280317.ac68b38@posting.google.com> <Kv-cnVDMbb1qmdOiRTvUqg@speakeasy.net> <biqve2$qp0$1@panix1.panix.com> <bj9jrv$95r$1@news.hccnet.nl> Message-ID: <tyf3cfbpjbm.fsf@pcepsft001.cern.ch> anton at vredegoor.doge.nl (Anton Vredegoor) writes: > -If microsoft hadn't stalled progress in software development by > hiding the algorithms used for their software we would *now* be > there where we will be in twenty years. I think that Microsoft has stalled progress, not by hiding any worderful technology that they might have, but by making the vast majority of users accept sub-mediocrity as the norm. They have run a hugely successful advertising campaign for the whole concept of sub-mediocrity; the desire for quality is what has suffered. By doing so, they have greatly influenced the direction of progress and of the meaning of "better". In the Microsoft mindset "better" means that the bouncy paperclip moves more smoothly, and can now do the cha-cha as well as the samba ... while it remains perfectly acceptable to have to reboot the computer each time you want to install a new piece of software. From bdesth.nospam at removeme.free.fr Wed Sep 3 06:13:53 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2003 12:13:53 +0200 Subject: what is the easiest way to parse a file In-Reply-To: <H_b5b.23$1o4.1177@news.oracle.com> References: <H_b5b.23$1o4.1177@news.oracle.com> Message-ID: <3f55bc6e$0$26843$626a54ce@news.free.fr> tagarwal wrote: > Is there a library in python which could be used for parsing file based upon > various sections You don't give enough context for anyone to answer. Learn to ask smart questions if you hope to have smart answers !-) You may want to read the excellent 'Text Processing in Python' by David Mertz. Bruno From aleax at aleax.it Tue Sep 23 09:53:24 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 23 Sep 2003 13:53:24 GMT Subject: command line or idle? References: <bkph6m$ljs$1@atlantis.news.tpi.pl> Message-ID: <ofYbb.148265$R32.4804476@news2.tin.it> sjf wrote: > Is it possible to distinguish if script is running on python command line > (python.exe) or IDLE? Not in entirely reliable way, but there are many hints you can generally rely on. For example, in the IDLE "Python Shell" sys.stdout is an instance of idlelib.rpc.RPCProxy (in IDLE 1.0) -- that MIGHT happen even "on python command line", of course, but it is not very likely to. Alex From newsgroups at jhrothjr.com Sat Sep 6 14:45:19 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 6 Sep 2003 14:45:19 -0400 Subject: Why the 'self' argument? References: <slrnblh5ru.nd5.gstaniak@inka.zagiel.pl> <vlh7otscuo8gb1@news.supernews.com> <3f58a2bd$0$156$a1866201@newsreader.visi.com> <vlhba85atlte07@news.supernews.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <vlhidvcpq9a980@news.supernews.com> <qpOW/ks/KnRV089yn@the-wire.com> <vlhtm1bmc7m295@news.supernews.com> <3f59014d$0$152$a1866201@newsreader.visi.com> <vli387c9mm140a@news.supernews.com> <3f591d28$0$175$a1866201@newsreader.visi.com> <vli9pochlcoc8e@news.supernews.com> <bjd20a$sf6$0@216.39.172.122> Message-ID: <vlkaqo1rf1nv49@news.supernews.com> "Bengt Richter" <bokr at oz.net> wrote in message news:bjd20a$sf6$0 at 216.39.172.122... > On Fri, 5 Sep 2003 20:15:00 -0400, "John Roth" <newsgroups at jhrothjr.com> wrote: > > > > >"Grant Edwards" <grante at visi.com> wrote in message > >news:3f591d28$0$175$a1866201 at newsreader.visi.com... > >> In article <vli387c9mm140a at news.supernews.com>, John Roth wrote: > >> > >> >> So that there's no difference between a function and a method. > >> >> > >> >> Simplicity and orthogonality are good things -- despite what > >> >> C++ proponents thing. > >> >> > >> >> > Hence my comment that requiring it is more complex than not > >> >> > requiring it. > >> >> > >> >> No, it's more complex the Java/Ruby way, since you have to have > >> >> two sets of rules for what a name means depending on whether > >> >> you're inside a "normal" function or a method. In Python > >> >> there's just one set of rules -- mostly. > >> > > >> > As I said earlier, it's quite possible to define it so that there > >> > is always an instance of some kind; whether that's an instance > >> > a class or the module itself. > >> > >> I don't follow. You're talking about defining a keyword that > >> always refers to the first parameter passed to a function? And > >> the declared parameters would refer to the 2nd through Nth > >> parameters? What if the keyword isn't used in the function > >> definition, then do the delcared parameters refer to the 1st > >> through Nth? > > > >When Python invokes a function, it binds the operands in the > >function call to the identifiers named in the function / method > >header. If this is a method, it binds the instance (which is not > >in the invocation parameter list, btw.) to the first > >parameter in the method header. > > > >If you make "self" a reserved word, then all it has to do > >is bind the instance to "self," rather than the first identifier > >in the parameter list. > > > >In current python, there are two classes of functions (module > >level and embedded) and three classes of methods (instance, > >class and static.) Instance methods get the current instance, > >class methods get the class object as the instance, and the other > >three categories get nothing. > > > >As a separate suggestion, I'd have Python bind the module > >object to "self" for module functions and static methods. I > >haven't figured out what I want done with embedded methods > >and unbound methods yet. Notice that this eliminates the > >need for the global statement for module functions - all > >identifiers are accessible for rebinding through "self." > > > >> > I think my comments have shown that you can reduce the amount > >> > of scoping / name space rules noticably. > >> > >> Compared to what? It sure sounds like you're introducing more > >> rules than there are now. How would you propose reducing the > >> number of rules? > > > >If you don't have to write "self" as the first parameter of a method, > >that reduces the complexity. Everything else remains the same. > > Will this still be possible? > > >>> def foo(*args): print args > ... > >>> class A(object): pass > ... > >>> class B(A): pass > ... > >>> a = A() > >>> b = B() > >>> A.bar = foo > >>> b.bar('howdy') > (<__main__.B object at 0x00906E70>, 'howdy') > >>> a.bar('howdy') > (<__main__.A object at 0x00907170>, 'howdy') > >>> foo('howdy') > ('howdy',) > > >>> A.bar('hello') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: unbound method foo() must be called with A instance as first argument (got str instan > ce instead) > >>> A.__dict__['bar']('hello') > ('hello',) > > I.e., the method-vs-function distinction is a matter of how you access the function dynamically, > not how you define it. There is no static distinction in functionality, AFAIK (though I guess > there could possibly be some speculative optimizations). It certainly needs to be. One of the reasons I haven't written a PEP is that providing an instance to an unbound method is a case I don't have a clear and simple answer to at the moment. > (The above doesn't even get into the multiple name issues I alluded to). I don't think the multiple name issues are relevant - that has to do with how the functions/methods are invoked, rather than what's in the header.) John Roth > > Regards, > Bengt Richter From Scott.Daniels at Acm.Org Mon Sep 8 19:17:07 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 08 Sep 2003 16:17:07 -0700 Subject: enum in Python In-Reply-To: <%V67b.653$NW3.617@news1.central.cox.net> References: <KF67b.33$fd2.25@newssvr23.news.prodigy.com> <%V67b.653$NW3.617@news1.central.cox.net> Message-ID: <3f5d0df1$1@nntp0.pdx.net> David M. Cook wrote: > In article <KF67b.33$fd2.25 at newssvr23.news.prodigy.com>, Andrew Chalk wrote: > > >>As a rank Python beginner I've used a dictionary, but presumably there is a >>better way. > > > I've seen idioms like > > FOO, BAR, BAZ = range(3) > > used. > > Dave Cook For 2.3 or after: class Enumerate(object): def __init__(self, names): for number, name in enumerate(names.split()): setattr(self, name, number) To use: codes = Enumerate('FOO BAR BAZ') codes.BAZ will be 2 and so on. if you only have 2.2, precede this with: from __future__ import generators def enumerate(iterable): number = 0 for name in iterable: yield number, name number += 1 codes.BAZ From jjl at pobox.com Thu Sep 11 06:53:16 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Sep 2003 11:53:16 +0100 Subject: ANN: PyQt v3.8 Released References: <mailman.1061147189.23632.python-list@python.org> <fc30bff.0308171759.7c4c564@posting.google.com> <mailman.1061196870.3067.python-list@python.org> <43e3984e.0309110116.18b9d065@posting.google.com> Message-ID: <87y8wvvboj.fsf@pobox.com> ulysses_dm at yahoo.com.cn (ulysses) writes: > Phil Thompson <phil at riverbankcomputing.co.uk> wrote in message news:<mailman.1061196870.3067.python-list at python.org>... [...] > > If you mean Windows then QApplication.winEventFilter() and QWidget.winEvent() > > were added to PyQt v3.4 at the specific request of somebody who wanted to do > > this. Sorry, but I don't have example code. [...] > I find QT have a trayicon example in C++, I study it. But I can't > convert it to python . Can you give some advice. Thanks. Post your code, tell us what appears to go wrong. You might find the PyKDE list a better place to post, though. John From jjl at pobox.com Sat Sep 6 08:37:29 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Sep 2003 13:37:29 +0100 Subject: Why python??? References: <mailman.1062790509.19411.python-list@python.org> <bjarq6$j45$00$1@news.t-online.com> <NO66b.30883$R32.926812@news2.tin.it> <bjb4hk$ohm$01$1@news.t-online.com> <Jbg6b.32033$R32.992758@news2.tin.it> <bjcbha$vmp$02$1@news.t-online.com> Message-ID: <87r82uum7q.fsf@pobox.com> "Michael Peuser" <mpeuser at web.de> writes: > "Alex Martelli" <aleax at aleax.it> [...] > My other point was that there nothing like that is going on in the software > development business. The price of tools is of no significance. It is the > (expected increase of productivity) The DoD Ada is the best example I can > think of. I haven't noticed anybody here arguing about tool costs. The issue is productivity. [...] > In most companies you do not train programmers but (try to) hire experienced > staff. Now we're going round in circles. This point has already been addressed. [...about Prechelt's study:] > There will be different results when doing embedded applications Gee, I guess you're right. ;-) > Coding is agreed, maintenance is still questionable. You believe fewer lines of code, written in a language that almost everybody who uses it claims is the most readable they've ever seen, results in maintenance problems? Perhaps you haven't discovered thorough unit-testing. [...] > > It's been done more than once, and it's being done again as we speak, > > many times over -- again, see the Python Success Stories. Google is [...] > It is not clear whether this is just a niche market like e.g. MATLAB. I honestly can't find any sense in that statement -- it's a foolishly empirical statement (and doesn't even reflect the empirical data). What reason do you have for thinking that Python is somehow magically restricted to implementing large search-engines?? Is it full of task-specific syntax and semantics like MATLAB? Have you read the success stories page, or peoples' reports in this group? John From __peter__ at web.de Fri Sep 19 07:28:56 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2003 13:28:56 +0200 Subject: convert Unicode to lower/uppercase? References: <HBF.20030919jmx2@bombur.uio.no> Message-ID: <bkepb9$6a4$01$1@news.t-online.com> nospam wrote: > Has someone got a Python routine or module which converts Unicode > strings to lowercase (or uppercase)? Toiled and came up with: >>> print u"abc????".upper() ABC???? >>> u"ABC???".lower() u'abc\xe4\xf6\xfc' Peter From ulope at gmx.de Sun Sep 21 14:40:30 2003 From: ulope at gmx.de (Ulrich Petri) Date: Sun, 21 Sep 2003 20:40:30 +0200 Subject: Problems with string and lists (searching and replaceing) References: <pan.2003.09.20.10.51.37.875000@hotmail.com> <bkhnpn$hgc$1@news.hccnet.nl> <bki8jq$269us$1@ID-167393.news.uni-berlin.de> <bkigtt$9jr$0@216.39.172.122> <bkim08$f8i$1@news.hccnet.nl> <pan.2003.09.21.06.55.07.16000@hotmail.com> Message-ID: <bkkrau$2uaqf$1@ID-67890.news.uni-berlin.de> "jblazi" <jblazi at hotmail.com> schrieb im Newsbeitrag news:pan.2003.09.21.06.55.07.16000 at hotmail.com... > I shall have a computer science class this year and I decided to use > Python. It is my favourite language and I have used it for many years. Now > I thought, one of our first "real" programs, in our pre-graphical and > pre-class state, would be to write simple program that works like this: > > One of the pupils enters a word. It should be a valid German word > consisting of five letters, for example 'abcde' (which is not a German > word by the way). > > The the other player may enter a guess which must be a five letter word as > well, for example 'xbxxx'. Then the system answers with the string '-*---' > as the 'b' in 'xbxxx' was correct and at the right place as well. > > Had the second player entered 'xxxbx', the system had responded with > '---.-', as the 'b' is correct but not correctly positioned. > > The second player must find out the original word. > Hm sth. like this? -----code------ def mastermind(word, guess): if len(word) != len(guess): return "Error" ret = ["-"]*len(word) counter = 0 for lw, lg in zip(word, guess): if lw == lg: ret[counter] = "x" else: if lg in word: ret[counter] = "." counter += 1 return "".join(ret) >>> mastermind('haus', 'hasu') 'xx..' >>> mastermind("jaguar", "januar") 'xx-xxx' -----code----- HTH Ciao Ulrich From uche at ogbuji.net Sat Sep 27 16:18:25 2003 From: uche at ogbuji.net (Uche Ogbuji) Date: 27 Sep 2003 13:18:25 -0700 Subject: XML/XSLT with Python References: <mailman.1064090130.16541.python-list@python.org> Message-ID: <d116fbae.0309271218.734934d@posting.google.com> "K. N." <vald at valis.amber.eu.org> wrote in message news:<mailman.1064090130.16541.python-list at python.org>... > Is there any good and fast Python module for XSLT > processing ? I'm going to use XML and XSLT to generate > web pages, so I need XSLT processor that will be able > to transform for example a DOM object in memory - I > don't want to create XML file containing data and then > load it and transform with XSLT, but I want to do > this at once - without writing to a temporary file. > Actually I've seen alot articles about parsing XML, > but nothing about creating XML documents and storing > it as an object that will be passed to XSLT processor, > and that is what I'm planning to do. > I think its a quite good solution, but I have no idea > which modules will be most suitable for this task. > Does anyone have some experience in this matter and > could point me where should I look ? 4XSLT (http://4suite.org) will do what you seek. In most situatons it is not as fast as libxslt, which is, after all, written entirely in C, but it does have its advantages, including a very rich Python API (in my biased opinion the richest Python API of all the choices). It is certainly fast enough for most purposes. You can use the cDomlette mutation API to generate your document in memory and then pass it to a pocessor instance. I want to mention that Dr. Korb mentioned having problems with 4Suite and Pyana, but in private conversation admits this was over a year ago, i.e. eons in the life of an actively maintained project such as 4Suite. Much has changed since then. If you decide to give it a try, start with: http://uche.ogbuji.net/akara/nodes/2003-01-01/basic-xslt http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/domlettes See also: http://www.xml.com/pub/a/2002/10/16/py-xml.html http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/basic-xpath http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/xslt-ext-elems http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/xslt-ext-funcs http://uche.ogbuji.net/tech/akara/nodes/2003-03-07/xslt-ext-api -- Uche Ogbuji http://uche.ogbuji.net From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 12:19:12 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 17:19:12 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <m2eky8dtny.fsf@mycroft.actrix.gen.nz> <GhQbb.196$eB.92@twister.southeast.rr.com> <hTZbb.2427$gi2.1120@fed1read01> Message-ID: <mgs0nvko9fm2e9kcml3bv26h7q78gv5ks8@4ax.com> On Tue, 23 Sep 2003 08:44:13 -0700, Tim Hochberg <tim.hochberg at ieee.org> wrote: >FWIW, Psyco recognizes this structure and removes the overhead >associated with it. I went looking for Psyco yesterday, and all I could find was broken links. Was sourceforge just having bad day, or is there a new site that hasn't made it into Google yet? -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From peter at engcorp.com Mon Sep 15 09:27:35 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Sep 2003 09:27:35 -0400 Subject: Sending SMS... References: <7b454334.0309131130.59cf64fa@posting.google.com> <bjvs8g$nso$1@atlantis.news.tpi.pl> <16e631aa.0309132041.319f0982@posting.google.com> <bk12hf$s98$1@nemesis.news.tpi.pl> <3F645802.162A90A7@engcorp.com> <bk1u0m$3c4$1@nemesis.news.tpi.pl> Message-ID: <3F65BE47.FE68D8C3@engcorp.com> Jarek Zgoda wrote: > > Peter Hansen <peter at engcorp.com> pisze: > > >> Also, be aware, that 1rstWap.com (and many other free SMS web gateways) > >> require prior user registration, that can not be handled by program > >> (they show user some picture with text that need to be entered > >> correctly). > > > > Kind of defeats the value of suggesting that he use this as > > a way of sending using Python, doesn't it? > > Yes - if this should be service/daemon app and you don't have a user > that can perform prior registration. > > No - if this will be usual GUI app with user equipped with monitor, > keyboard and mouse, sitting in front of it. You're right.... Sorry, I misread your first post as suggesting that each message, not just the registration, required the human confirmation. (Yes, you were quite clear in what you wrote.... I must have been skimming or something. :-( ) -Peter From jzgoda at gazeta.usun.pl Mon Sep 29 13:51:46 2003 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 29 Sep 2003 17:51:46 +0000 (UTC) Subject: What's the best MP3 (ID3) access library to use? References: <182bcf76.0309290349.452a6643@posting.google.com> <87ekxzg3pg.fsf@voodoo.fake> Message-ID: <bl9rfi$m5$4@atlantis.news.tpi.pl> Lawrence Oluyede <raims at dot.com> pisze: >> I'm looking for a Python library to access ID3 information in MP3 >> files. A search of Parnassus picked up a number of possibilities, but >> I can't work out which best suits what I'm trying to do. Some seem out >> of date, others are Unix only, etc. There doesn't seem to be an >> obvious "standard" module to use. > > Try this: id3-py.sf.net > It should work on Windows but I haven't tested yet It works also on Windows, but accepts only ID3v1 tags. -- Jarek Zgoda Registered Linux User #-1 http://www.zgoda.biz/ JID:jarek at jabberpl.org http://zgoda.jogger.pl/ From cookedm+news at physics.mcmaster.ca Tue Sep 23 21:08:52 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 23 Sep 2003 21:08:52 -0400 Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> Message-ID: <qnky8wf3sd7.fsf@arbutus.physics.mcmaster.ca> At some point, joseph at ugcs.caltech.edu (John Lin) wrote: > Howdy, > > I want to know how to tell if a forked process is done. > > Actually, my real question is that I want to run a shell script inside > of a python script, and after the shell script has finished running, I > want to do more stuff *condition* on the fact that the shell script > has finished running, inside the same python script. > > The only way I can think of is to fork a process and then call the > shell script, as in: > pid = os.fork() > if pid == 0: > os.execl(shellscript_name.sh, "") > but how can I know if the shell script is finished? Look up os.wait and os.waitpid in the Python Library Reference. Or, for this case, use os.system(). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From phil_nospam_schmidt at yahoo.com Wed Sep 10 13:52:07 2003 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 10 Sep 2003 10:52:07 -0700 Subject: SWIG, MinGW, and Python 2.3 problem Message-ID: <221e7b06.0309100952.1858a1b6@posting.google.com> I'm attempting to follow the instructions at http://sebsauvage.net/python/mingw.html, without luck. I have Python 2.3, MinGW 3.2.3, ans SWIG 1.3.19. I get an export error on "initexample" when attempting the example. Do I need some extra switches to get SWIG to create that function? Or is it something else? Here's my example build: C:\Phil\python\Extensions\example>python setup.py build --compiler=mingw32 running build running build_ext building 'example' extension swigging example.i to example_wrap.c C:\Phil\python\Extensions\SWIG-1.3.19\swig.exe -python -o example_wrap.c example.i creating build creating build\temp.win32-2.3 creating build\temp.win32-2.3\Release c:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Ic:\python23\include -Ic:\python23\PC -c example.c -o build\temp.win32-2.3\Release\example.o c:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -Ic:\python23\include -Ic:\python23\PC -c example_wrap.c -o build\temp.win32-2.3\Release\example_wrap. o example_wrap.c:170: warning: `SWIG_TypeDynamicCast' defined but not used example_wrap.c:182: warning: `SWIG_TypeName' defined but not used example_wrap.c:188: warning: `SWIG_TypeQuery' defined but not used example_wrap.c:423: warning: `SWIG_ConvertPtr' defined but not used example_wrap.c:515: warning: `SWIG_ConvertPacked' defined but not used writing build\temp.win32-2.3\Release\example.def creating build\lib.win32-2.3 c:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.3\Release\example_wrap.o build\temp.win32-2.3\Release\example.o build\temp.win32-2.3\Re lease\example.def -Lc:\python23\libs -Lc:\python23\PCBuild -lpython23 -o build\lib.win32-2.3\example.pyd Cannot export initexample: symbol not defined error: command 'gcc' failed with exit status 1 From aleax at aleax.it Fri Sep 26 15:44:36 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 19:44:36 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <wCGcb.3064$yU5.2141@nwrdny01.gnilink.net> <8RScb.169633$R32.5449258@news2.tin.it> <uk77vhagj.fsf@boost-consulting.com> <JH_cb.174346$R32.5548036@news2.tin.it> <u7k3ve63q.fsf@boost-consulting.com> Message-ID: <EG0db.175320$R32.5577927@news2.tin.it> David Abrahams wrote: > Alex Martelli <aleax at aleax.it> writes: > >> David Abrahams wrote: >> ... >>> Also, the idea of denying tuples the ability to reverse iterate seems >>> arbitrary and capricious. >> >> Sure, but so is denying them, e.g., non-mutating methods such as >> .index() and .count(). > > Not IMO. Immutability is a very useful trait. Sure, very useful indeed -- and why does YO suggest that add such NON-mutating methods would damage immutability in the LEAST...? >> At least we're _consistently_ arbitrary and capricious!-) > > Not in this case. Some amplification would be welcome, because the above comment on immutability's usefulness is totally obscure to me in context. Alex From hans at zephyrfalcon.org Tue Sep 9 11:18:00 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 09 Sep 2003 11:18:00 -0400 Subject: Slight metaclass confusion In-Reply-To: <fd3e3161.0309090259.eaa3623@posting.google.com> References: <fd3e3161.0309090259.eaa3623@posting.google.com> Message-ID: <3F5DEF28.6040900@zephyrfalcon.org> ben at transversal.com wrote: > I am slightly confused about the way metaclasses work, having read > "Metaclass Programming In Python, Parts 1 and 2" > > I get the fact that the instance of a metaclass is a class, but in > this case I fail to see why the following does'nt work: I'm not 100% sure, but: >>>>class Meta(type): > > ... def __str__(cls): > ... print "I am " + repr(cls) > ... > >>>>Class = Meta("Fish", (), {}) >>>>Class.__str__() > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: descriptor '__str__' of 'object' object needs an argument ...here, you're calling __str__ on a *class*... >>>>class Simple(object): > > ... def __str__(self): > ... return "I am " + repr(self) > ... > >>>>obj = Simple() >>>>obj.__str__() > > I am <__main__.Simple object at 0x402f676c> ...and here, you're calling it on an *instance*. The reason it doesn't work probably has nothing to do with your metaclass, as demonstrated by this: >>> class Foo(object): pass ... >>> Foo.__str__() Traceback (most recent call last): File "<input>", line 1, in ? TypeError: descriptor '__str__' of 'object' object needs an argument >>> f = Foo() >>> f.__str__() '<__main__.Foo object at 0x0162C750>' I'm not sure how it all works internally... using str(Foo) works, but Foo.__str__() doesn't. Notice that Foo.__str__(Foo) does work. I don't think there's anything wrong with your metaclass (though see below ;-), just don't call __str__() directly on the class. On a side note, it's a bad idea to use 'print' in __str__ or __repr__, even for informal test code. I tried the code above in PyCrust, and it broke the automatic attribute lookup. This is not really important, but it was a surprising side effect. HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From grobinson at transpose.com Wed Sep 3 10:13:07 2003 From: grobinson at transpose.com (Gary Robinson) Date: Wed, 03 Sep 2003 10:13:07 -0400 Subject: unicode memory usage Message-ID: <BB7B6F33.2DB94%grobinson@transpose.com> We have an application which involves storing a lot of strings in RAM. It would be most convenient to use Unicode strings, but I am wary of doubling memory usage. My fear is based on the idea that unicode strings may take two bytes per character in order to accomodate non-ascii characters. But I don't know whether that's actually how Python strings work internally. So, my question: Do unicode strings in Python take substantially more memory than classic python strings or not, assuming the strings are generally 99% ASCII characters (but not 100%)? --Gary -- Putting http://wecanstopspam.org in your email helps it pass through overzealous spam filters. Gary Robinson CEO Transpose, LLC grobinson at transpose.com 207-942-3463 http://www.transpose.com http://radio.weblogs.com/0101454 From db3l at fitlinxx.com Mon Sep 1 11:28:09 2003 From: db3l at fitlinxx.com (David Bolen) Date: 01 Sep 2003 11:28:09 -0400 Subject: Windows Remote Log in References: <mailman.1062079011.24483.python-list@python.org> <hHo3b.29530$IQ2.5903@fe1.columbus.rr.com> Message-ID: <uvfscplyu.fsf@fitlinxx.com> Jesse <redrumjack at hotmail.com> writes: > What I need is some way for user to enter the proper credentials so > Python could restart the service on the remote machine. > > If this isn't making sense please disregard and I'll move on to > something a bit easier. When I first started doing a lot of management scripts for Windows it seemed strange to me that so many Win32 API calls would accept a remote machine name, but no optional credentials. As it turns out, Windows shares a single set of credentials per remote machine among any operations being performed to that remote machine. If there are no established credentials due to a prior operation or access that is still in place, then your default credentials (those currently established by your login) are used. And in fact if you try an operation that does accept credentials, and they are different from the established credentials the operation will fail (which can be infuriating at times :-)). So it's a clumsy mechanism in many ways, but convenient in others (since any operation the system performs, even with utilities that don't provide a way to enter credentials) will inherit the established credentials. The trick is to get the proper set of credentials in place in a persistent manner prior to performing whatever operation you want to do. One of the simplest persistent mechanisms is by accessing a remote share. And since all systems supporting Windows networking operations always have an IPC$ share (used for basic connection establishment), you can just "use" that share - as I believe another responder pointed out recently. You don't need to map it to a drive or anything, just use the share, and if you want, drop it when you are done. Once you have this, then I'd just go for straight Win32 network calls to manipulate the remote machine. This has the advantage of being more assured of working on your NT machines, since in most cases they won't have some of the newer stuff like WMI installed, although you could add that on. Mark Hammond's win32all package wraps all of the appropriate functions that you'll need (both to manipulate the remote access via the shares, as well as perform remote operations such as calls to the service manager). You can generally start by using MSDN to examine how you would perform the task with Win32 calls and then just find the right wrapper in the win32all package. In the For example, here's a snippet of code (using the win32net module) from one of our scripts that is triggered when a remote machine for some reason loses its D$ share (the administrative share to drive D:). If necessary we use the IPC$ share to gain the proper remote credentials, and then create the remote share. The NetUseAdd call is effectively the replacement for a command line "net use" operation without a drive assignment, and the NetUseDel call mimics the "net use /delete" operation. Coming into this code: use_servers = optional list of machines we already have access to machine = machine we are manipulating wic6user = administrative user on remote machine wic6pwd = administrative password on remote machine - - - - - - - - - - - - - - - - - - - - - - - - - print "(Creating temporary share)" if use_servers and machine not in use_servers: print "(Creating temporary use)" use_info = {'remote':r'\\'+machine+r'\IPC$', 'asg_type':-1, 'username':wic6user, 'password':wic6pwd} try: win32net.NetUseAdd(None,2,use_info) have_use = 1 except pywintypes.error, value: print "Couldn't create temporary use:", value # Create the remote share shareinfo = {'netname':'D$','path':'D:\\','max_uses':-1} try: win32net.NetShareAdd(machine,2,shareinfo) have_share = 1 except pywintypes.error, value: print "Couldn't create share:", value # ... perform any other operations on remote machine ... if have_share: try: win32net.NetShareDel(machine,'D$') except pywintypes.error, value: print "Couldn't remove temporary D$ share:", value if have_use: try: win32net.NetUseDel(None,r'\\'+machine+r'\IPC$') except pywintypes.error, value: print "Couldn't remove temporary use:", value - - - - - - - - - - - - - - - - - - - - - - - - - In the case of managing services, the win32service module wraps most everything you would need. You can start a service with StartService, stop it with ControlService with the SERVICE_CONTROL_STOP code, check status with QueryServiceStatus and so on. Or, if the existing WService module you've been using works fine, you should just be able to use it unchanged once you have locked in the proper remote credentials via the IPC$ share. Another quick 'n dirty approach we've also used is just to use os.system, or more typically (so you can log the output) one of the os.popen# calls, to farm the service operation out to a utility like "sc" from the resource kit or psservice from sysinternals (www.sysinternals.com). You still need the IPC$ share in place for credentials to remote domain machines, but like any other system call, Windows will simply apply the established credentials to any operations that those utilities perform. -- David From stevena at neosynapse.net Fri Sep 12 22:02:47 2003 From: stevena at neosynapse.net (Steven D. Arnold) Date: Fri, 12 Sep 2003 22:02:47 -0400 Subject: My future Python IDE article In-Reply-To: <becf4072.0309082111.4ef1783f@posting.google.com> Message-ID: <BB87F307.1256%stevena@neosynapse.net> On 9/9/03 1:11 AM, "Hardy Jonck" <hjonck at gims.com> wrote: > I recently had a look at Jedit and must say I am impressed. Python > support via Jython 2.1 - but the extensibility and philosophy that > comes with Jedit is amazing. I agree -- it has an awesome multi-file search feature that makes it fairly competitive with even a five-star editor like Source Insight (which is available only on Win32). The spirit of this editor seems to be much like emacs, and it's GPLed. Right now I believe it is the best programmer's text editor on Mac OS X, and I have done a detailed search for a good Mac OS X text editor. steve From dave at pythonapocrypha.com Wed Sep 24 10:49:06 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 24 Sep 2003 08:49:06 -0600 Subject: RELEASED Python 2.3.1 In-Reply-To: <DdacnR-12Jpma--iU-KYvA@comcast.com> References: <mailman.1064390741.20344.python-list@python.org> <ad8tfdwv.fsf@python.net> <DdacnR-12Jpma--iU-KYvA@comcast.com> Message-ID: <200309240849.06646.dave@pythonapocrypha.com> On Thursday 25 September 2003 08:08 am, Terry Reedy wrote: > > "Cousin Stanley" <CousinStanley at hotmail.com> writes: > > > Would it be feasible to eliminate the Python Docs > > > from the standard distribution and always download > > > separately if desired ???? > > > > > > This would eliminate downloading the docs twice > > > if the user wants the separate doc files and provide > > > a leaner download for non-programming Python users > > > that will never develop anything in Python themselves > > > but who want a run-time environment only .... > > I agree that a separate Windows run-only distribution (including .pyc > instead of .py files) FWIW, shipping the .py and _not_ the .pyc has one advantage in that the .py's tend to compress better. Combined with zipimporters in 2.3 this can result in a nice, small run-time. > would be a good idea. But someone has to > volunteer the time or money to make it happen. The current release > procedure is still being refined and documented by the current > volunteers. I've been working on a simplistic implementation of such a run-time for my own projects. It's functional but very experimental (read: does what I need and not much else) and not well-documented or anything, but if anybody wants to play with what I've done so far just drop me a line. It's nice and small: 19,530 ctypes.zip 18,944 pycb.exe 1,908 pycbcom.tlb 19,456 pycbw.exe 445,952 python23.dll 749,092 python23.zip 3,072 w9xpopen.exe 20,480 _ctypes.pyd (1.2 MB total - has _socket, select, _winreg, etc built in to the main dll) It registers itself as an ActiveX control so that from Internet Explorer you can have a web page query to see if the run-time has been installed (so that, e.g., you can have the user download the app+runtime or just the app). Small download size is a primary goal, with a close second being very little differentiation between the dev (.py) and release (.exe) environments (which has bitten me many times in the past). Thus I don't run python.exe any more at all for projects that will end up being distributed this way. The library also registers the .pycb extension with Windows (pycb = "Python code bundle") so that you can distribute your code in a small app.pycb file that, from the user's perspective, is an "executable". For example, for a personal project I just completed the entire distribution consisted of: venster.pycb (82k) main.pycb (15k) Under 100KB is not bad for a GUI app! :) The .pycb format is basically ZIP + AES encryption, and pycb uses the new import hooks in 2.3 to handle it. The encryption is just to keep honest people out; anybody with the right combination of smart and bored could figure out how to circumvent it. -Dave From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 12:27:13 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 17:27:13 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <SnObb.1581$PT3.257319@news20.bellglobal.com> <63gvmvcf6iakbs8pgll7u8ogblkbqld6fp@4ax.com> <6EQbb.1770$PT3.279727@news20.bellglobal.com> <8vovmvgmb5c677ii8a43l8l0o1sjbosre2@4ax.com> <lWYbb.4739$yD1.697869@news20.bellglobal.com> Message-ID: <nks0nvsrca2v8k9kobiqmteg64dp8r8rfn@4ax.com> On Tue, 23 Sep 2003 10:40:30 -0400, "Sean Ross" <sross at connectmail.carleton.ca> wrote: >Here's a quick hack of an int class that supports iteration using the slice >notation, plus simple iteration on the class itself (for i in int: ...). >This can certainly be improved, and other issues need to be addressed, but I >just wanted to see what Stephen's idea would look like in practice. (Not >bad. Actually, pretty good.) I like it ;-) Also, it kind of suggests that maybe a recipe or a library 'xint' class or C extension module could do the job as well as a language change. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From martin at v.loewis.de Thu Sep 4 15:44:13 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Sep 2003 21:44:13 +0200 Subject: unicode memory usage In-Reply-To: <mailman.1062700399.27324.python-list@python.org> References: <mailman.1062700399.27324.python-list@python.org> Message-ID: <bj84m6$j2c$07$3@news.t-online.com> Gary Robinson wrote: > But I don't know whether that's actually how Python strings work internally. Python Unicode objects use normally 2 bytes per character, unless Python is built in UCS-4 mode, in which case they use 4 bytes per character. > So, my question: Do unicode strings in Python take substantially more memory > than classic python strings or not, assuming the strings are generally 99% > ASCII characters (but not 100%)? Yes; you can expect that 99% of the storage for characters are null bytes, then. Whether this is substantial depends on the total amount of storage that you need for string objects, compared to the storage needed for other things, or the storage available. Regards, Martin From NO-MAIL at hotmail.com Thu Sep 18 16:17:37 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Thu, 18 Sep 2003 20:17:37 GMT Subject: How to pass parameter to a module? References: <Vwfab.2454$9G2.2174@twister.southeast.rr.com> <bkc62g$5k0$1@news1.wdf.sap-ag.de> <dnmab.5254$9G2.2643@twister.southeast.rr.com> <bkd0rb$qb2$01$1@news.t-online.com> Message-ID: <Bpoab.6053$9G2.3254@twister.southeast.rr.com> That's what I asked. Thanks! M-a-S "Michael Peuser" <mpeuser at web.de> wrote in message news:bkd0rb$qb2$01$1 at news.t-online.com... > > "M-a-S" <NO-MAIL at hotmail.com> > > > I thought about the third module. It doesn't sound good. > > I hoped there're some tricks with __dict__, frames and > > other __...__ objects. > > > > Well, there are some tricks ;-) > > > myVariable='great surprise' > import x > ....... > > "This is modul X" > import sys > print sys.modules['__main__'].myVariable > > > But generally the namespace of a module is ... the module. > > Kindly > Michael P From mark at hahnca.com Tue Sep 30 18:07:33 2003 From: mark at hahnca.com (Mark Hahn) Date: Tue, 30 Sep 2003 15:07:33 -0700 Subject: [ANN] pylint-0.2 References: <mailman.1064921380.21335.python-list@python.org> Message-ID: <I8neb.4591$hp5.3169@fed1read04> > They not only feel no need to document, they also feel no need to follow ANN threads they start. I apologize for the rudeness of my post. Sometimes I am not the nice person that I think I am and I surprise myself. "POYEN OP Olivier (DCL)" <Olivier.POYEN at clf-dexia.com> wrote in message news:mailman.1064921380.21335.python-list at python.org... > -----Message d'origine----- > De : Mark Hahn [mailto:mark at hahnca.com] > Envoy? : mardi 30 septembre 2003 06:39 > ? : python-list at python.org > Objet : Re: [ANN] pylint-0.2 > > > They not only feel no need to document, they also feel no > need to follow ANN > threads they start. > Or they might just live in France (as in logilab.FR), have a different time schedule, and being in bed while you're posting that ! Or even not working today ! Or event not daily-reading c.l.p, but just fr.comp.lang.python. As for the documentation, just go to logilab web site, as Peter H said. --OPQ, Long signature following.... ---------------------------------------------------------------------------- ---- > ----------------------------------------------------------------- > > Ce message est confidentiel ; son contenu ne represente en aucun > > cas un engagement de la part de Dexia Credit Local ou de Dexia > > CLF Banque. Toute publication, utilisation ou diffusion, meme > > partielle, doit etre autorisee prealablement par l'emetteur. Si > > vous n'etes pas destinataire de ce message, merci d'en avertir > > immediatement l'expediteur. > > > > This message is confidential ; its contents do not constitute a > > commitment by Dexia Credit Local or Dexia CLF Banque. Any > > unauthorised disclosure, use or dissemination, either whole or > > partial, is prohibited. If you are not the intended recipient of > > the message, please notify the sender immediately. > > ----------------------------------------------------------------- > > Consultez notre site internet www.dexia-clf.fr > > La cle d'une gestion optimisee du secteur public local > > ----------------------------------------------------------------- > From __peter__ at web.de Tue Sep 23 07:47:49 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Sep 2003 13:47:49 +0200 Subject: Factory function to generate a named class References: <3f702b3a$0$23594$5a62ac22@freenews.iinet.net.au> Message-ID: <bkpbv7$9nj$00$1@news.t-online.com> Derek Fountain wrote: > Is there a way to generate an instance of a class given the class name at > runtime? If so, what, in newbie terms, is it? class FontController: def __init__(self, model): pass class Model: pass def getClass(classname, modulename="__main__"): return getattr(__import__(modulename, globals(), locals(), [classname]), classname) model = getClass("Model")() print getClass("FontController")(model) Should be fairly self-explanatory :-) Peter From bokr at oz.net Fri Sep 5 14:53:07 2003 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2003 18:53:07 GMT Subject: newbie question about dictionnary ? References: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Message-ID: <bjam2j$2lp$0@216.39.172.122> On Fri, 5 Sep 2003 08:37:01 +0200, "Sophie All?on" <alleon at club-internet.fr> wrote: >Hi, > >CONTEXT >I do numerical simulation for which I have to process mesh. A mesh is made >of >triangle which are made of points. >I want from this information to create edges and build triangle from edges >rather >than from points. > >PROBLEM >An edge is shared by possibly more than one triangle. > >ALGORITHM > >have a triangle class (made of 3 edges) >have an edge class (made of 2 points and embeding a triangle list (those >connected to the edge) Is that a straigt line edge, or a concatenation of possibly non-co-linear triangle edges? And does the direction imply anything, e.g., a counter-clock-wise edge walk with surface to the left and outside to the right? (and up being defined as the direction of the cross product of two successive edge vectors of the same triangle). > >for each triangle construct its edges but I have to check if the edge >already exists > >for doing this I thought the dictionary was excellent but the key is a >string while I want it >to be the 2 points forming the edge ? How to do it ? You can do it with points, with a couple of caveats: Dicts don't have to have strings as keys. Numbers and tuples are ok as keys too. So if you have an edge, you could represent it as ((x1,y1,z1), (x2,y2,z2)) and use that as a key. unless you are differentiating edges according to direction (which can be very useful for some purposes), you would want to normalize the point order one way or another, IWT. Besides order, it is important to consider floating point accuracy when/if using them as keys of part of tuple keys, because two different expressions for the same mathematical value may be calculated with different roundoff, and can lead to a key error if both floats are used in keys in a dict, expecting equivalence. Once past the floating point FUD, you can consider whether it will really affect you or not in the specifics of what you are doing. If you convert ascii string number literal representations to float, those should map 1:1 to consistent nearest-available-floating-point values. If you then use those unchanged in keys, you should be ok. OTOH, if e.g. you calculate some line/surface intersection for an end point, or subdivide an edge, etc., there might be roundoff, and you'd have to decide how to generate key values that will actually be equal (to each other or to converted literals) when they're "equal" according to your rules of "close enough." One way to deal with this is to use scaled integers instead of floats, and be careful how/when you convert. Or rounding to a given precision may work also. For fine mesh graphic end output, you may want to think about whether whether you are rounding in a way that gives the same end image, independent of intermediate coordinate system translations. (E.g., rounding signed relative local pixel dimensions of a figure before adding a center-of-figure pixel offset might look different from just rounding the final all-positive pixel coordinates, especially if amplified by Moire effects). > >Have you a better idea ? > I have to understand better first, and then it would only be a maybe ;-) I think a lot depends on the topology of the surface your mesh covers, and whether it varies in resolution (i.e., are some triangles subdivided into smaller triangles), and how the edges of the whole and of regular subregions are defined. I.e., what does the data represent, and how did it come into being? E.g., a sphere can be covered with 60 triangles made five per pentagonal face of the included docdecahedron, projected, and those 60 triangles can be regularly subdivided. Implicit in that is that you could cook up an algorithm to walk the triangles by some indexing scheme and/or map from indices to spatial info re triangles and the sphere. For a flat rectangular space (or topological equivalent), you might index triangles much more easily. Once you have your model represented, what kinds of access walks will you need to do? Will you be iterating over the entire set of triangles and wanting to access the neighbors of each (in which case it should be cheap to find neighbors), or are you doing something like making countour maps, or what? Designing with the future access patterns in mind is likely to help in making the end use faster, IWT. Regards, Bengt Richter From robin at jessikat.fsnet.co.uk Fri Sep 5 03:46:05 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 5 Sep 2003 08:46:05 +0100 Subject: WELCOME to cygwin@cygwin.com References: <mailman.1062729676.26922.python-list@python.org> Message-ID: <pnkbeVA98DW$EwC2@jessikat.fsnet.co.uk> In article <mailman.1062729676.26922.python-list at python.org>, cygwin- help at cygwin.com writes >Hi! This is the ezmlm program. I'm managing the >cygwin at cygwin.com mailing list. > >Acknowledgment: I have added the address > > python-list at python.org > >to the cygwin mailing list. > >Welcome to cygwin at cygwin.com! .... wow if we can only get the cygwin thingy to subscribe to the python-list we can really get an email storm :) -- Robin Becker From tdelaney at avaya.com Mon Sep 8 19:08:32 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 9 Sep 2003 09:08:32 +1000 Subject: Eureka! (Re: Comments on Python Redesign) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEAD4D03@au3010avexu1.global.avaya.com> > From: Delaney, Timothy C (Timothy) > > From: Delaney, Timothy C (Timothy) > > > From: Delaney, Timothy C (Timothy) > > > > From: Delaney, Timothy C (Timothy) > > > > > From: Paul McNett [mailto:p at ulmcnett.com] > > > > > > > > > > http://www.amazon.com/exec/obidos/tg/detail/-/0321112547/qid=1 > > > > > > 063059237/sr=1-4/ref=sr_1_4/002-8213749-9028058?v=glance&s=books Hmm - that URL doesn't look too good now ... Tim Delaney From waldbie at attglobal.net Thu Sep 11 00:45:38 2003 From: waldbie at attglobal.net (Carl Waldbieser) Date: Wed, 10 Sep 2003 21:45:38 -0700 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <bjne1b$jm5$07$1@news.t-online.com> <jnkulv8t6e1qc3mb4pmf0k706e98pgmss2@4ax.com> <3F5F83B1.48763F85@alcyone.com> <cg5vlvgorsi88elsn9ur5ueavpg27d7ui3@4ax.com> Message-ID: <lpQ7b.1147$G1.6248@tor-nn1.netcom.ca> I think you could still run into a problem here with aliasing. For example: obj = Obj_Type () x = obj obj.Do_Setup_Stuff_1 () obj.Do_Setup_Stuff_2 () obj.Do_Setup_Stuff_3 () container.Add (ref obj) #rebinds obj to None #later... x.alter() #alters containers copy anyway This kind o problem exists in other languages like C++, too. The containers in the C++ standard library copy elements to side-step these problems. When copying becomes expensive, pointers to elements are used instead, but since you can have multiple pointers to the same object, you run the risk of clobbering data in the container if you are not careful. In practice, though, this type of behavior has rarely been a problem for me. Carl Waldbieser > The most compelling example I have is essentially the side-effect > thing from my reply to Peter Ottens post. As an attempt to express it > more clearly, there are times when you set up an object purely so that > you can store it into a container... > > obj = Obj_Type () > > obj.Do_Setup_Stuff_1 () > obj.Do_Setup_Stuff_2 () > obj.Do_Setup_Stuff_3 () > > container.Add (obj) > > In many cases, the Add function will not take a copy because it seems > pointless. The caller set up the object purely to store it in the > container, and in most cases is going to discard its reference to the > object immediately afterwards. But then there's always the possibility > that the caller might carry on using that object. For instance... > > obj = Obj_Type () > > obj.Do_Setup_Stuff_1 () > obj.Do_Setup_Stuff_2 () > obj.Do_Setup_Stuff_3 () > > container.Add (obj) > > obj.Do_Setup_Stuff_3_Slightly_Differently () > > container.Add (obj) > > This probably wouldn't do what was expected - the 'slightly > differently' call changed an object that is also being referenced from > inside the container - an accidental side-effect. > > If a 'ref' parameter is used and the 'Add' function rebinds it to > 'None', however, we get... > > obj = Obj_Type () > > obj.Do_Setup_Stuff_1 () > obj.Do_Setup_Stuff_2 () > obj.Do_Setup_Stuff_3 () > > container.Add (ref obj) > > obj.Do_Setup_Stuff_3_Slightly_Differently () > # exception here tells that something has gone wrong > > container.Add (ref obj) > > Which quickly gets bugfixed to... > > obj = Obj_Type () > > obj.Do_Setup_Stuff_1 () > obj.Do_Setup_Stuff_2 () > obj.Do_Setup_Stuff_3 () > > container.Add_Copy (obj) > > obj.Do_Setup_Stuff_3_Slightly_Differently () > # no exception as Add_Copy doesn't rebind the parameter > > container.Add (ref obj) > > > Then again, even in this case there are other ways. For instance... > > builder = Builder () > > builder.Do_Setup_Stuff_1 () > builder.Do_Setup_Stuff_2 () > builder.Do_Setup_Stuff_3 () > > container.Add (builder.Build ()) > > builder.Do_Setup_Stuff_3_Slightly_Differently () > > container.Add (builder.Build ()) > > In this case, the builder class can set a 'used' flag after the > 'Build' call which tells it that it needs to make a copy before > applying further changes. In that way, both unnecessary copies and > accidental side-effects are avoided while keeping the intention clear > (especially as this is basically one of the classic design patterns > from Gamma et al - though I may be confusing Builder with Factory > Method) and with no changes to Python. > > So my 'most compelling example' isn't compelling at all. Damn. > > I've been thinking on this for some hours now and still not come up > with a more compelling example (or at least not one which can't be > better handled a different way) so I guess the idea is a dud. > > Bet you never expected me to admit that so easy ;-) > From stephan.diehl at gmx.net Fri Sep 5 04:40:48 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Fri, 05 Sep 2003 10:40:48 +0200 Subject: basic language question References: <bj7ots$48j$06$1@news.t-online.com> <VUidncLV5oQd88qiU-KYvw@comcast.com> <bj7sr5$jd8$04$1@news.t-online.com> Message-ID: <bj9i3h$kbd$03$1@news.t-online.com> Stephan Diehl wrote: > Terry Reedy wrote: > >> >> "Stephan Diehl" <stephan.diehl at gmx.net> wrote in message >> news:bj7ots$48j$06$1 at news.t-online.com... >>> Once in a while, I get bitten by the fact, that mutating list >> methods such >>> as 'append' or 'extend' return None instead of the (mutated) list >> itself. > > [...] > >> >> 'Returners' could wrap no-return mutators with functions or >> derived-class methods that do return the object, but I have never seen >> anyone post a complete module that does so for, say, all list >> mutators. > > That's actually a nice idea. I might just do that. o.k., the following short code would give you a list class, that returns 'self' when invoking any of the mutating methods. The solution involves a metaclass and I wouldn't consider this code more as an example than an industrial strength solution (for example, at the moment, you couldn't overload any of these methods) ------------------------------------------------------------------ def wrapedmeth(classname,meth): def _meth(self,*argl,**argd): getattr(super(globals()[classname],self),meth)(*argl,**argd) return self return _meth class ReturnMeta(type): def __new__(cls,classname,bases,classdict): wrap = classdict.get('return_self_super_methods') if wrap is not None: for method in wrap: classdict[method] = wrapedmeth(classname,meth) return super(ReturnMeta,cls).__new__(cls,classname,bases,classdict) class mylist(list): __metaclass__ = ReturnMeta return_self_super_methods = ['append', 'extend', 'insert', 'remove', 'reverse', 'sort'] if __name__ == '__main__': print 'l = [1,2]' print 'mylist: print l.append(3)' l = mylist([1,2]) print l.append(3) print 'list: print l.append(3)' l = [1,2] print l.append(3) ------------------------------------------------------------------------------ have fun Stephan From pf_moore at yahoo.co.uk Mon Sep 1 18:46:16 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Mon, 01 Sep 2003 23:46:16 +0100 Subject: Structured writing to console, such as a table References: <mailman.1062445143.10872.python-list@python.org> Message-ID: <k78sjfev.fsf@yahoo.co.uk> "Raaijmakers, Vincent (IndSys, GE Interlogix)" <Vincent.Raaijmakers at ge.com> writes: > Ok, perhaps a question on a newbie level. > > I try to create a simple 'write to a console application' where all > the items in a string do have a variable size: > items = ["a", "bbbbbbbbb", "cc"] > Well, actually, I need to print a table as simple text, nice lined > up in a console. So: > > > Item: Value: Another Value: > ----------+----------+------------------ > a | 1 | 2 > bbbbbbbbb | 2 | 17 > cc | 3 | 5 > > My hope was that somewhere in python land an existing module was > waiting for me. A module that also prints lines, headers.... > > Unfortunately, I can't find it. Books, Google... > Before I reinvent this wheel... please give me some tips, > references, examples... This is going to sound unhelpful, but I suspect the problem is that the problem is too simple - everyone *does* reinvent the wheel, because it's faster than going to find a generic solution. Having said that, I didn't manage to quickly write some code for you :-) The first question is, what does your data look like? From your example, I'd say that you have a list of items items = ["a", "bbbbbbbbb", "cc"] but I'm not sure how you get your values. Let's assume that in fact you have a "list of rows" type of representation: rows = [["a", 1, 2], ["bbbbbbbbb", 2, 17], ["cc", 3, 5] ] This may or may not match your requirements, but you should be able to either adapt my code or your data as needed. The first problem is working out the column widths you need. That's not difficult, just messy (because in some senses, the data is "the wrong way round" - a list of coumns would be better for this step, but worse later on). def column_widths(titles, rows): '''Calculate column widths for a "list of rows"''' # Initialise widths to have all columns zero width to start with widths = [len(str(title)) for title in titles] # Adjust the width to allow space for each row in turn for row in rows: widths = [max(w, len(str(item))) for w, item in zip(widths, row)] return widths That's a bit messy, so let's dissect it. I use list comprehensions a lot here - if you don't know how they work, it's well worth studying them. We start by setting widths to fit the titles. We assume that all rows have the same number of elements - I don't check for this. Then, for each row, we adjust the widths to fit the items in that row. The list comprehension goes through each column, and the new width of that column is either the old width (if the new item fits already) or the length of the new item (if it is the biggest so far). For each item, we're calculating len(str(item)) which is the length of the string representation of the item - ie, the space required on screen for that item. OK, that was the ugly bit - now we just format the results. This is simple, but a little long winded. def format(titles, rows): "Format a table" # First calculate the column widths widths = column_widths(titles, rows) # Create the result as a list of lines - it's more flexible # than printing directly result = [] # Title line first (add 3 spaces between colums) line = ' '.join([t.ljust(w) for t, w in zip(titles, widths)]) result.append(line) # Separator line (add -+- between columns) line = '-+-'.join(['-' * w for w in widths]) result.append(line) # Rows of data for row in rows: line = ' | '.join([item.ljust(w) for item, w in zip(row, widths)]) result.append(line) return result Now you can do: print "\n".join(format(titles, rows)) I hope this helps. As I say, the problem is often that matching the algorithm to what you really want is harder than writing the code in the first place, so don't be afraid to play with this (it's nearly midnight, so I'm offering no guarantees that this code is correct :-)) Paul -- This signature intentionally left blank From ulope at gmx.de Thu Sep 18 16:30:36 2003 From: ulope at gmx.de (Ulrich Petri) Date: Thu, 18 Sep 2003 22:30:36 +0200 Subject: Join equivalent for tuples of non-strings? References: <1a884f4a.0309181000.749eb8a1@posting.google.com> Message-ID: <bkd4ld$e324$1@ID-67890.news.uni-berlin.de> "Peter L. Buschman" <plb at iotk.com> schrieb im Newsbeitrag news:1a884f4a.0309181000.749eb8a1 at posting.google.com... > I'm trying to think in Python, but am stumped here... > > What is the equivalent for the following if you are dealing with a tuple > of non-strings? > > >>> import string > >>> foo = ( '1', '2', '3' ) > >>> string.join( foo, '.' ) > '1.2.3' > > With a tuple of integers, this fails with a traceback as below: > > >>> bar = ( 1, 2, 3 ) > >>> string.join( bar, '.' ) > try: foo = (1,2,3,4,5,6) ".".join([str(x) for x in foo]) HTH Ciao Ulrich From martin.schneider at illusion-factory.de Tue Sep 9 13:45:30 2003 From: martin.schneider at illusion-factory.de (Martin Schneider) Date: Tue, 9 Sep 2003 19:45:30 +0200 Subject: Python / C: small runtime difference? References: <bjk3mi$jorjb$1@ID-119488.news.uni-berlin.de><bjka05$jlrt2$1@ID-119488.news.uni-berlin.de> <mailman.1063106894.20701.python-list@python.org> <bjkkjp$jvkvt$1@ID-119488.news.uni-berlin.de> <3f5e0963.369221532@news.blueyonder.co.uk> Message-ID: <bjl24i$kejrk$1@ID-119488.news.uni-berlin.de> > If you are gonna tweak the C you might as well tweak the > Python too! (But not with a real python, they tweak back > hard! :-) I'll remember that :-) Martin From tmeador at miramar.com Fri Sep 19 16:38:57 2003 From: tmeador at miramar.com (Tim) Date: 19 Sep 2003 13:38:57 -0700 Subject: return codes from py2exe python script Message-ID: <867286d8.0309191238.3759638e@posting.google.com> Does anybody know how to get a return code or any errors from a python script that has been made into a exe using py2exe? Right now when I run my script.exe it always returns 0 even if the script fails. From jjl at pobox.com Thu Sep 11 19:18:44 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Sep 2003 00:18:44 +0100 Subject: why is this failing? References: <9x58b.139$u07.2@newsread1.news.atl.earthlink.net> <3F60E645.2501B9EE@engcorp.com> <3f60ea13$0$42053$a1866201@newsreader.visi.com> Message-ID: <87llsu6hij.fsf@pobox.com> grante at visi.com (Grant Edwards) writes: > In article <3F60E645.2501B9EE at engcorp.com>, Peter Hansen wrote: > > > Don't use names of builtins and your life will be easier. :-) > > And the easiest way to do that is to use an editor with a > Python mode. Make sure it shows builtins in a distinct color. > You will then know immediately (while editing) when you > accidentally redefine a builtin. You wouldn't happen to know how to do this for python-mode? emacs-illiterate-ly y'rs, John From zsh-announce-help at sunsite.dk Wed Sep 3 17:07:27 2003 From: zsh-announce-help at sunsite.dk (zsh-announce-help at sunsite.dk) Date: 3 Sep 2003 21:07:27 -0000 Subject: confirm unsubscribe from zsh-announce@sunsite.dk Message-ID: <1062623247.12266.ezmlm@sunsite.dk> Hi! This is the ezmlm program. I'm managing the zsh-announce at sunsite.dk mailing list. To confirm that you would like python-list at python.org removed from the zsh-announce mailing list, please send an empty reply to this address: zsh-announce-uc.1062623247.cbehnoegidjnndepmmcn-python-list=python.org at sunsite.dk Usually, this happens when you just hit the "reply" button. If this does not work, simply copy the address and paste it into the "To:" field of a new message. I haven't checked whether your address is currently on the mailing list. To see what address you used to subscribe, look at the messages you are receiving from the mailing list. Each message has your address hidden inside its return path; for example, mary at xdd.ff.com receives messages with return path: <zsh-announce-return-<number>-mary=xdd.ff.com at sunsite.dk. --- Administrative commands for the zsh-announce list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: <zsh-announce-subscribe at sunsite.dk> To remove your address from the list, send a message to: <zsh-announce-unsubscribe at sunsite.dk> Send mail to the following for info and FAQ for this list: <zsh-announce-info at sunsite.dk> <zsh-announce-faq at sunsite.dk> Similar addresses exist for the digest list: <zsh-announce-digest-subscribe at sunsite.dk> <zsh-announce-digest-unsubscribe at sunsite.dk> To get messages 123 through 145 (a maximum of 100 per request), mail: <zsh-announce-get.123_145 at sunsite.dk> To get an index with subject and author for messages 123-456 , mail: <zsh-announce-index.123_456 at sunsite.dk> They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: <zsh-announce-thread.12345 at sunsite.dk> The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: <zsh-announce-subscribe-john=host.domain at sunsite.dk> To stop subscription for this address, mail: <zsh-announce-unsubscribe-john=host.domain at sunsite.dk> In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at zsh-announce-owner at sunsite.dk. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: <python-list at python.org> Received: (qmail 12256 invoked from network); 3 Sep 2003 21:07:27 -0000 Received: from localhost (HELO sunsite.dk) (127.0.0.1) by localhost with SMTP; 3 Sep 2003 21:07:27 -0000 X-MessageWall-Score: 0 (sunsite.dk) Received: from [24.195.53.13] by sunsite.dk (MessageWall 1.0.8) with SMTP; 3 Sep 2003 21:7:26 -0000 From: <python-list at python.org> To: <zsh-announce-unsubscribe at sunsite.dk> Subject: Re: Details Date: Wed, 3 Sep 2003 17:07:30 --0400 X-MailScanner: Found to be clean Importance: Normal X-Mailer: Microsoft Outlook Express 6.00.2600.0000 X-MSMail-Priority: Normal X-Priority: 3 (Normal) MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="_NextPart_000_1B6CCA34" --_NextPart_000_1B6CCA34 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Please see the attached file for details. --_NextPart_000_1B6CCA34-- From MMARTINEZ at CSREES.USDA.GOV Mon Sep 22 08:03:09 2003 From: MMARTINEZ at CSREES.USDA.GOV (Martinez, Michael) Date: Mon, 22 Sep 2003 08:03:09 -0400 Subject: [Spambayes] Re: [OT] New Play: SPAMELOT Message-ID: <83EED274D3127740995A6B621B88F2E1DF7D2F@csrees-exchange.csrees.usda.gov> I love Spambayes. I wouldn't trade it for any other app. Michael Martinez Linux System Administrator ISTM/CSREES United States Department of Agriculture -----Original Message----- From: Tim Peters [mailto:tim.one at comcast.net] Sent: Sunday, September 21, 2003 7:09 PM To: python-list at python.org Cc: spambayes at python.org Subject: RE: [Spambayes] Re: [OT] New Play: SPAMELOT [William Trenker] > ... > I would also nominate Spambayes as Python App of the Year! We're close enough to the end of 2003 that we had better count that vote for 2004 too <wink>. > Spambayes certainly is a showcase of the sophistication, and > practicality, that can be achieved using Python 'out of the box'. Those who helped with the early development were probably most impressed by the speed of development Python allowed: the first implementation of spambayes was conceived, written, and working all in one day. It was (of course) much simpler then, had no real email interface apart from sucking up files containing messages, and we'll overlook that the Outlook addin threatens to consume the rest of Mark Hammond's life. Other than those, it went really fast <wink>. _______________________________________________ Spambayes at python.org http://mail.python.org/mailman/listinfo/spambayes Check the FAQ before asking: http://spambayes.sf.net/faq.html From edreamleo at charter.net Tue Sep 30 05:20:49 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Tue, 30 Sep 2003 04:20:49 -0500 Subject: A startup puzzle References: <vngnif6v8ip4c6@corp.supernews.com> <gandreas-21AC09.14161229092003@news.mpls.visi.com> <vnh8uh5j8e3i44@corp.supernews.com> Message-ID: <vniinnlp5ih45c@corp.supernews.com> > In short, the following pattern appears like it will work in all my modules: > > from leoGlobals import * > app = leoProxy() # leoProxy defined in leoGlobals > # Now the code can reference either app.x or app().x. Actually, app = leoProxy() can be done in leoGlobals, so the pattern is just: from leoGlobals import * # Now the code can reference either app.x or app().x. I have installed the new code in leoGlobals.py and everything "just works". Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From aleax at aleax.it Fri Sep 26 05:48:35 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 09:48:35 GMT Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: <mailman.1064390741.20344.python-list@python.org> <3F71B857.2D1E3268@engcorp.com> <Xns9400E70CB6F9Fcliechtigmxnet@62.2.16.82> <3F720759.34D7BD3E@engcorp.com> <3F720D28.83C3E99@engcorp.com> <noCcb.119695$hE5.4100692@news1.tin.it> <3F731B17.61C17B3A@engcorp.com> <bkvbb5$6mi$00$1@news.t-online.com> Message-ID: <TXTcb.124120$hE5.4241274@news1.tin.it> Dominic wrote: > >>>I and Just canvassed widely at Europython, looking for people to >>>suggest more use cases, and nobody came up with anything that stood >>>up to examination beyond our basic use case of "debugging possibly >>>buggy (nonterminating) code, in cases where we just can't run the >>>possibly buggy code in the main thread and delegate a separate >>>watchdog thread to the purpose of interrupting the main one" > > One use case could be if you only want to use a limited number > of threads for some reason. > > Then you could interrupt a low priority task and reassign the > thread to some more urgent task. Afterwards the old task could be > resumed. To make this work you would have to make the code > aware of those interrupts. I don't think it works well: Python threads have no priorities, so, even if you DID interrupt one thread that's working on a "low-priority job" to feed it with a higher-priority one, OTHER threads running low-priority jobs will happily keep stealing CPU and other resources away from the allegedly "high-priority job". And if you're thinking of somehow "suspending" ALL the threads currently deemed to be running "low-priority jobs", I think the whole architecture sounds creaky and fragile. I would rather tweak (not anywhere as hard a job) module Queue to give messages posted on Queue's a priority field; ensuring that not ALL threads (in the pool that's peeling job requests off the main "pending-jobs Queue") are simultaneously running long AND low-priority jobs, so that one of them is going to respond soon enough, is decently easy -- and you can add a global sempahore, that high-priority jobs increment at their start and decrement at their end, and low-priority jobs check periodically in their main loops to ensure their work is suspended when any high- priority task is running. > While playing with the new feature I noticed that it > takes a long time (>3 seconds) until the exception is thrown. > In contrast to the possibility to interrupt the main thread > with interrupt_main which seems not to be delayed. Hmmmm... care to show exactly the code you've been trying? I get EXACTLY opposite results, as follows...: import time import thread import threadex def saywhen(): for x in xrange(100000): time.sleep(0.1) def intemain(): global when_sent when_sent = None time.sleep(1.0) when_sent = time.time() thread.interrupt_main() time.sleep(1.0) im_delays = [] for i in range(10): tid = thread.start_new_thread(intemain, ()) try: saywhen() except: when_received = time.time() im_delays.append(when_received - when_sent) def get_interrupted(): global when_received when_received = None try: saywhen() except: when_received = time.time() it_delays = [] for i in range(10): tid = thread.start_new_thread(get_interrupted, ()) time.sleep(1.0) when_sent = time.time() threadex.threadex(tid, KeyboardInterrupt) time.sleep(1.0) it_delays.append(when_received - when_sent) main_id = thread.get_ident() def intemain1(): global when_sent when_sent = None time.sleep(1.0) when_sent = time.time() threadex.threadex(main_id, KeyboardInterrupt) time.sleep(1.0) im1_delays = [] for i in range(10): tid = thread.start_new_thread(intemain1, ()) try: saywhen() except: when_received = time.time() im1_delays.append(when_received - when_sent) im_delays.sort() im1_delays.sort() it_delays.sort() print 'IM:', im_delays print 'IT:', it_delays print 'IM1:', im1_delays Module threadex is a tiny interface exposing as 'threadex' the PyThreadState_SetAsyncExc function. And the results on my Linux (Mandrake 9.1) box are as follows...: [alex at lancelot sae]$ python pai.py IM: [2.4993209838867188, 2.4998600482940674, 2.4998999834060669, 2.4999450445175171, 2.4999510049819946, 2.4999560117721558, 2.4999659061431885, 2.499967098236084, 2.4999990463256836, 2.5000520944595337] IT: [0.20004498958587646, 0.39922797679901123, 0.39999902248382568, 0.40000700950622559, 0.40000808238983154, 0.40002298355102539, 0.40002298355102539, 0.40002405643463135, 0.40003299713134766, 0.40004003047943115] IM1: [0.10003900527954102, 0.39957892894744873, 0.40000700950622559, 0.40000796318054199, 0.40001499652862549, 0.40002000331878662, 0.40003204345703125, 0.40003299713134766, 0.40004301071166992, 0.40005004405975342] [alex at lancelot sae]$ i.e., interrupt_main takes a very repeatable 2.5 seconds; PyThreadState_SetAsyncExc typically 0.4 seconds, whether it's going from main to secondary thread or viceversa, with occasional "low peaks" of 0.1 or 0.2 seconds. Of course, it's quite possible that there may be something biased in my setup, or it may be a platform issue. But I'd be quite curious to see the code you base your observation on. Alex From eric.brunel at pragmadev.N0SP4M.com Mon Sep 22 04:26:13 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Mon, 22 Sep 2003 10:26:13 +0200 Subject: file position *tell()* works different References: <13a533e8.0309190137.2df0cc60@posting.google.com> <LIAab.7544$9G2.6227@twister.southeast.rr.com> <bkemib$bjr$1@news-reader2.wanadoo.fr> <OiLab.21316$x21.11005@twister.southeast.rr.com> Message-ID: <bkmb91$puh$1@news-reader4.wanadoo.fr> M-a-S wrote: > "Eric Brunel" <eric.brunel at pragmadev.N0SP4M.com> wrote in message news:bkemib$bjr$1 at news-reader2.wanadoo.fr... > >>Sorry, but no you can't: the default is to open the file in text mode, and you >>can change it with a 'b', but 't' has no meaning at all. BTW, 'b' also has no >>meaning at all on all Unices: the so-called "binary" or "text" mode are the >>same, i.e. what is read is what is in the file. Windows needs it only because of >>its superfluous \r's at the end of each line. >><...> >>HTH >>-- >>- Eric Brunel <eric dot brunel at pragmadev dot com> - >>PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com > > > > The idea was to tell the humans that it's text. It won't hurt neither Unix nor Windows. > I know that nobody cares, though. Not only to tell humans: Windows automatically removes the '\r' at the end of each line when a file is opened in text mode. It won't happen in binary mode. And I wish I could stop caring, but I occasionally run into problems just because of this behaviour, and I know I'm not the only one. -- - Eric Brunel <eric dot brunel at pragmadev dot com> - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From eppstein at ics.uci.edu Mon Sep 22 11:31:35 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 22 Sep 2003 08:31:35 -0700 Subject: None??? References: <EV6bb.1834$iT4.1283814@news1.news.adelphia.net> <m2he37549i.fsf@host-201.null.null.bellsouth.net> <3F6D68AA.9070603@aon.at> <eppstein-AAC3F1.11134721092003@news.service.uci.edu> <4l4umv4kl82d8t5td29in26cfb57ctb6h0@4ax.com> Message-ID: <eppstein-F636AC.08313522092003@news.service.uci.edu> In article <4l4umv4kl82d8t5td29in26cfb57ctb6h0 at 4ax.com>, Tim Rowe <tim at remove_if_not_spam.digitig.co.uk> wrote: > >Arguably, any code that uses / with integer arguments is now buggy, > >because it will produce different results in different Python versions. > >You should either use // (integer division) or force floating point > >division (e.g. by changing the expression to income*percent/100.0). > > What's the behaviour of "from __future__ import division" on versions > that are too old to know about the future of division? A nice error message. So that's another good way to go. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From newsgroups at jhrothjr.com Mon Sep 8 13:16:12 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 8 Sep 2003 13:16:12 -0400 Subject: Ternary operator References: <doJ6b.1999$Ft.737@newssvr22.news.prodigy.com> <3F5B6404.BD1A9709@engcorp.com> <vlo9699d77sj3e@corp.supernews.com> <mailman.1063023193.11506.python-list@python.org> <4qznp862.fsf@yahoo.co.uk> Message-ID: <vlpec6e8ul9o0e@news.supernews.com> "Paul Moore" <pf_moore at yahoo.co.uk> wrote in message news:4qznp862.fsf at yahoo.co.uk... > Bob Gailer <bgailer at alum.rpi.edu> writes: > > >>It seems to me that the majority did want some kind of ternary operator, but > >>the large number of options prevented any one from being the clear winner. I > >>would wager that if the BDFL had picked his favorite from any of the most > >>popular options and said, "Now vote yes or no on *this* syntax", he would > >>have seen that clear majority he was looking for. > > Actually, that's what Guido did do at first (IIRC). He proposed the > "expr1 if cond else expr2" form. The *community* argued against this > specific syntax, rather than concentrating on the semantics, and it > was only then that the discussion fragmented into endless discussions > over what syntax to choose. > > >>I suppose this is all water under the bridge now, since the PEP stated that > >>this was the community's one and only chance. I just can't help but think > >>that the voting system guaranteed the outcome--but it's Guido's language and > >>it was certainly his call to make. > > The voting system was designed by the community and so we can't blame > anyone but ourselves for "rigging" the outcome... I don't remember it that way. The way I remember it, it showed up one day as a statement by someone that they were going to list all of the suggestions so we could vote on it. There was some discussion of how to vote, but before that I don't remember any discussion of structure. It seems to me that the process was the typical "here's how I think it should be done, and I'm willing to do all the work to make it happen," followed by a fair number of people not saying that they thought it was a terminally stupid idea. You don't, after all, want to discourage volunteers who actually want to work. > > THANK YOU. Your analysis of the process brings me a sense of relief. I > > was also confused and frustrated by its failure to deliver what > > (obviously) many of us wanted. > > My feeling is that there is a majority who want a ternary operation > (not including me, but what the heck) but that there is violent > disagreement on the syntax. There were also a lot of people who were fed up with the endless debate, too. The biggest difficulty, IMNSHO, was debating specific proposals rather than debating constraints. If you debate constraints first, then you can evaluate specific proposals against the constraints. That process usually iterates to a conclusion rather swiftly. However, I don't know how to make that shift in a public forum such as c.l.py. > > I was dismayed by the process being defined as "the community's one > > and only chance" and then set up to fail. > > Well, I see it as Guido not really wanting to spend the time > implementing a ternary operator. He offered to, in any case, if the > community was in favour (and the PEP originally stated precisely what > he was offering). But with the proviso "if you don't like this, I'm > not going to offer again". I doubt he was surprised that the result > was a lot of discussion over syntax, rather than an acceptance of the > offer. > > The general history of this issue is one of endless discussion with no > agreement. Maybe the majority would like the feature, but that same > majority can't agree on syntax. The PEP just forced one more iteration > of that process, and documented the result (lots of heated discussion, > but no solid conclusion). > > Maybe it's a shame that Guido's original PEP wasn't preserved > unaltered. What's there now doesn't capture the flavour of the > original. Agreed. There may be a copy floating around in someone's archives, though. I'm not interested enough in assigning blame to go hunting, we need a way to move forward that will get to a real agreement. > Of course, all of this is only my recollection, and just as prone to > being wrong as anyone else's... Likewise. John Roth > > Paul. > -- > This signature intentionally left blank From tenorman3 at yahoo.com Wed Sep 10 21:36:21 2003 From: tenorman3 at yahoo.com (Bob) Date: Wed, 10 Sep 2003 18:36:21 -0700 (PDT) Subject: Pickling/unpickling extensions types Message-ID: <20030911013621.78119.qmail@web14603.mail.yahoo.com> I've read over section 3.14.5.2 of the doc about a zillion times, and it still makes absolutely no sense to me. Can someone please explain it? What I'd like to do is, basically, have the object be pickled as None, since it represents an object in the C world, and it doesn't make sense to pickle it at all. How can I do that, if at all? In particular, what does this "A callable object, which in the unpickling environment must be either a class, a callable registered as a ``safe constructor'' (see below), or it must have an attribute __safe_for_unpickling__ with a true value. Otherwise, an UnpicklingError will be raised in the unpickling environment. Note that as usual, the callable itself is pickled by name" mean? __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From jjl at pobox.com Mon Sep 29 10:28:13 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Sep 2003 15:28:13 +0100 Subject: Google newsgroup "Unable to find thread" message? References: <b16e4ef7.0309290617.799b800d@posting.google.com> Message-ID: <87u16v3c02.fsf@pobox.com> steve at ferg.org (Stephen Ferg) writes: > I use the newsgroup mainly via my Web browser and Google. > > Over the last few days, when I click on a link to a thread, I've been > frequently getting the message "Unable to find thread." > > Does anybody know what's going on? No, but in the past I've found that you can often get the whole thread by following a slightly different click path to the thread page (I don't remember the details, sorry). It has been happening for months. John From aahz at pythoncraft.com Thu Sep 4 14:17:07 2003 From: aahz at pythoncraft.com (Aahz) Date: 4 Sep 2003 14:17:07 -0400 Subject: Quickie mail.python.org status References: <727daa7e.0309031140.1af820b2@posting.google.com> Message-ID: <bj7vj3$gau$1@panix3.panix.com> In article <727daa7e.0309031140.1af820b2 at posting.google.com>, Skip Montanaro <skip at pobox.com> wrote: > >I noticed that python-related mail has been at best trickling in today, >so took a quick peek at mail.python.org. Since 4am today exim has >rejected over 15,000 messages because they contained executable >attachments or suspicious (sobig-style) subjects. I'm sure that's nothing >compared to sites like SourceForge or AOL, but it conspires to keep >useful mail from flowing through that machine. I'm now seeing some mail flowing, but it'll take quite a while to catch up. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From achalk at XXXmagnacartasoftware.com Mon Sep 8 17:38:50 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Mon, 08 Sep 2003 21:38:50 GMT Subject: enum in Python Message-ID: <KF67b.33$fd2.25@newssvr23.news.prodigy.com> What is the best way to implement an equivalent of C's 'enum' type in Python? As a rank Python beginner I've used a dictionary, but presumably there is a better way. Thanks From mertz at gnosis.cx Mon Sep 8 13:33:36 2003 From: mertz at gnosis.cx (David Mertz) Date: Mon, 08 Sep 2003 13:33:36 -0400 Subject: "Python Redesign" (fwd) References: <mailman.1062982932.16437.python-list@python.org> <87fzj7cvbv.fsf@pobox.com> Message-ID: <w1LX/kKkXohI092yn@gnosis.cx> |> <tim at pollenation.net> wrote: |> 1) it's an image |mertz at gnosis.cx (David Mertz) writes: |> You keep writing this; not just to me, but on c.l.py too. I can't quite |> figure out what relevance you perceive this fact to have. jjl at pobox.com (John J. Lee) wrote previously: |I guess because people, seeing the .html file extension in the URL, |assumed that resizing fonts and sensible scaling to your browser |window should work (obviously, the .html extension is rather |misleading). In fact, you were one of those people, David, IIRC -- Kinda. I *did* assume it was a real HTML page when I first looked at it (I tried clicking on the links). But I realized it was an image before I posted anything. But I was mistaken about the sort of image it was. I assumed Parkin had written some HTML (maybe with some tool), then taken a screenshot of that as rendered in some browser. Specifically, I imagined that the underlying HTML had fixed pixel-based "width=" attributes for those boxes/tables. In retrospect, the assumption about pixel-based widths wouldn't actually follow from the idea it was a screenshot. However, that's all moot apparently, since the picture seems to have been drawn directly in some graphics application, without any HTML having ever been created. It certainly seems like a weird approach to me; it also makes the question of whether pixel- or percentage-based widths were used meaningless. |> I *am* probably the most widely read writer on Python topics |So, as you say, we're *definitely* not trying to sell Python to *you*, |David. <wink> No... my point was more that I am already in the business of trying to "sell" Python, in some sense. I write articles and books (well, one so far) in part to encourage new developers to select Python, versus some other language/technology. Btw. In my remark (which I wrote privately to Parkin, but posted after he posted a response that quoted mine), I think I failed to give proper respects to my excellent colleagues Cameron Laird and Uche Ogbuji, both of whom are also very widely read with similar articles to mine. I only claim "most" because Cameron and Uche--being smarter than I--are a bit less narrow in what they cover (i.e. more outside of Python). Yours, David... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises <mertz at gnosis.cx> ]-------------------------- From stacom at stacom-software.de Mon Sep 15 08:39:47 2003 From: stacom at stacom-software.de (Alexander Eisenhuth) Date: Mon, 15 Sep 2003 14:39:47 +0200 Subject: distributing a standalone python app. under Linux Message-ID: <bk4bul$o92at$1@ID-155280.news.uni-berlin.de> Hallo alltogether, under windows, the py2exe is first choice, but has anybody done it under Linux ? My first try with Installer http://www.mcmillan-inc.com/install5_intro.html was not sucessfull. Any hints or help is welcome. Alexander From mpeuser at web.de Thu Sep 11 10:29:51 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 11 Sep 2003 16:29:51 +0200 Subject: os.listdir References: <HKYJXJ$IJtpKVwktIN8kOKo8RPo0eClW9NoSa2aMVXNcWgZA4d1srKaVwlRm@bol.com.br> <mailman.1063171515.17609.python-list@python.org> Message-ID: <bjq102$m21$03$1@news.t-online.com> "Graham Fawcett" <fawcett at teksavvy.com > I'm willing to be wrong twice, honestly I am! But I'm pretty sure it's > constant time. B-tree searches are log2(n), but dicts aren't trees. > > Can't find a real reference, but the Timbot spoke here: > http://mail.python.org/pipermail/tutor/2002-August/016800.html > > If I'm wrong on this one, I'll wear the Python Dunce Cap for a week, > while repeating my corrected lessons! > I am pretty sure you will not have to! It is generally very difficult to compute the mean access time to a hash. It totally depends on the size of the internal hash table allocated as to the number of elements you store there. In Perl there is trick to manipulate that (i.e. to increase it appropriately when you expect e.g. some 100.000 entries). I don't know whether this is possible in (C)Python, according to which algorithm the initial size is computed, and when or if the table is reconfigured (which would be a major undertaking btw). Any info someone? Apart from that, you will generally find the value to your key with the first access if the table is decently dimensioned. Kindly Michael P From overdrive_ss at yahoo.com Mon Sep 22 17:37:53 2003 From: overdrive_ss at yahoo.com (Todd Johnson) Date: Mon, 22 Sep 2003 14:37:53 -0700 (PDT) Subject: General Password questions In-Reply-To: <20030824115159.29723.73112.Mailman@mail.python.org> Message-ID: <20030922213753.10203.qmail@web41215.mail.yahoo.com> I am creating a dialog in wxPython for log in purposes. Basically when the user clicks the ok button, the dialog box saves the user name and password as class attributes. Then as long as the dialog exists calling MyDialog.GetUserName() and MyDialog.GetPassword() returns them. This seems insecure to me. Is there a better way to go about this or is it safe as long as I destroy the dialog as soon as I am done with it? On a similar note, I want to save the password to a file. How do I encrypt the password? I assume straight binary is too easy to reverse engineer though my program isn't really saving any vital information so it may be acceptable. Any ideas or links would be very appreciated. Thanks in advance, Todd A. Johnson __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From lefevrol at yahoo.com Thu Sep 4 10:27:51 2003 From: lefevrol at yahoo.com (Olivier Lefevre) Date: 4 Sep 2003 07:27:51 -0700 Subject: Invisible function attributes References: <51809ae4.0309030715.7706cadb@posting.google.com> <87he3tfopa.fsf@pobox.com> Message-ID: <51809ae4.0309040627.28d7a075@posting.google.com> Thanks to all those who replied. > ...what I'm guessing you haven't figured out yet is that everything > works like this in Python. Very possibly. I am coming to python from Java and I want to investigate the weird stuff precisely because either it's a one-off (in which case I'll make a note to myself to ignore it and not use it) or it holds the key to what is specific about the language. I seem to have hit pay dirt with this one ;-) Nudged by the dot syntax, I was thinking of this function attribute as if it were a sort of class member (i.e., pretending for a while this function is a class) and, since functions can't have instances, treating it as a sort of static member of the function, which should be available as soon as declared. Obviously I got it all wrong. Instead, they work like local variables except that they "persist" after the function has exited. That still feels weird to me. What are they used for? Give me a compelling reason to have such a beast in the language. OTOH, does this behaviour have anything to do with so-called "futures"? -- O.L. From duncan at NOSPAMrcp.co.uk Mon Sep 15 06:07:17 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 15 Sep 2003 10:07:17 +0000 (UTC) Subject: Could somebody please explain what is happening .... References: <3f657f95$0$10968$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <Xns93F76FC33687Aduncanrcpcouk@127.0.0.1> "John Dean" <john at rygannon.com> wrote in news:3f657f95$0$10968$fa0fcedb at lovejoy.zen.co.uk: > I have been reading quite a lot of Python source code recently and I > have come across a particular construct which I don't understand. I > would be grateful if somebody could explain the reason for including > the following lines of code. I have seen it only at the beginning of a > module:- > > global sys > import sys > > global os > import os > > .... > .... > > I know what global means and I know what import means but what is the > reason for making an imported module global? None whatsoever. This isn't a construct used by anyone who knows what the global statement does: outside a function global has precisely no effect. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From maxm at mxm.dk Tue Sep 16 15:04:50 2003 From: maxm at mxm.dk (Max M) Date: Tue, 16 Sep 2003 21:04:50 +0200 Subject: None, False, True In-Reply-To: <0KI9b.12967$x21.4828@twister.southeast.rr.com> References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> Message-ID: <3f675ecd$0$97184$edfadb0f@dread12.news.tele.dk> M-a-S wrote: > Can anybody explain this: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>None = 3 > > <stdin>:1: SyntaxWarning: assignment to None > >>>>False = 4 >>>>True = 5 >>>> >>>>None, False, True > > (3, 4, 5) Yes. You assign new values to the objects None, False and True. You then print out those values in a tuple. What's not to understand? But for others reading your programme you might be better of to keep them their normal values. regards Max M From andy47 at halfcooked.com Mon Sep 29 11:53:41 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Mon, 29 Sep 2003 16:53:41 +0100 Subject: IDE with a specific feature In-Reply-To: <j7ocnvshp0jar2duskdgpd92qc7blvf8t0@4ax.com> References: <j7ocnvshp0jar2duskdgpd92qc7blvf8t0@4ax.com> Message-ID: <bl9kjh$i2q$1@sea.gmane.org> Daniel Klein wrote: > I don't want to get into a 'which IDE is the best' conversation. I'm > looking for an IDE that has the ability to view 2 (or more) > methods/functions within the same module simultaneously. > > I've looked at the screen shots for Komodo, Wing, BlackAdder, etc and > it is not obvious that any of them have this feature. > > This is something I got use to in Smalltalk and have found it quite > useful when working on several methods that work closely together. > > Daniel Klein No one else has mentioned it, but Vim does this too. Just type ":split". I believe Vim 6 has support for horizontal or vertical splits as well. Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From PeterAbel at gmx.net Fri Sep 26 18:17:49 2003 From: PeterAbel at gmx.net (Peter Abel) Date: 26 Sep 2003 15:17:49 -0700 Subject: Newbie: Changing a string to a class attribute. References: <33fbf9ec.0309241210.7acfddb9@posting.google.com> <21064255.0309251227.76336087@posting.google.com> <mailman.1064588380.4062.python-list@python.org> Message-ID: <21064255.0309261417.3eb19a66@posting.google.com> Jeff Epler <jepler at unpythonic.net> wrote in message news:<mailman.1064588380.4062.python-list at python.org>... > On Thu, Sep 25, 2003 at 01:27:24PM -0700, Peter Abel wrote: > > >>> def exec_method(object, method): > > ... eval('object.'+method) () > > Why not write > def exec_method(object, method): > getattr(object, method)() > no nasty 'eval' there, thank goodness. > > Jeff It's okay. Seems to be clearer. Peter From NO-MAIL at hotmail.com Tue Sep 23 00:49:42 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 23 Sep 2003 04:49:42 GMT Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <m2eky8dtny.fsf@mycroft.actrix.gen.nz> Message-ID: <GhQbb.196$eB.92@twister.southeast.rr.com> > > Some more looping thoughts - this time on integer for loops... I guess this should be a matter of optimization. Why don't the Python compiler recognize 'for <var> in [x]range(<from>,<till>):'? It should be pretty easy. Microsoft does marvels optimizing loops in C. Why an open source project like Python can't do it? M-a-S From rune.hansen at viventus.no Sat Sep 27 04:05:55 2003 From: rune.hansen at viventus.no (Rune Hansen) Date: Sat, 27 Sep 2003 10:05:55 +0200 Subject: unicode 3 digit decimal conversion Message-ID: <Dxbdb.26075$os2.360296@news2.e.nsc.no> Hi, I've got the string "Gratis ?l",or in english:"Free beer", I know there is no such thing but... Python 2.3 (#1, Aug 1 2003, 15:23:03) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> unicode("Gratis ?l","iso-8859-1") u'Gratis \xf8l' >>>ord("\xf8") 248 What I need is the converted string to read u'Gratis \248l' (* How do I do this without going through each and every character of the string? (not that I have figgured out how to do that right either) regards /rune *) I need to communicate with a telnet interface that only accepts accented characters as unicode decimals From __peter__ at web.de Thu Sep 25 12:47:14 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2003 18:47:14 +0200 Subject: Snakeoil alert (was Re: newbie script) References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> <bks61f$3s3$1@newsfeed.eris.qinetiq.com> <3f719ed5$0$14824$79c14f64@nan-newsreader-03.noos.net> <bks7pp$4a8$1@newsfeed.eris.qinetiq.com> <3f72eb7c$0$29964$79c14f64@nan-newsreader-02.noos.net> <bkuvdk$qpf$01$1@news.t-online.com> <bkv4vv$6tj$03$1@news.t-online.com> Message-ID: <bkv68t$t30$02$1@news.t-online.com> Peter Otten wrote: >> However, I have noticed that when I copy and paste from KNode 7.2 using >> Strg+C/Strg+V instead of the middle mouse button, all '\xa0' are >> magically converted back to old '\x20' space characters. > > Sorry, I have tried to reproduce the behaviour stated above and was not > able to reproduce it. So whatever I did differently, it was not the copy > and paste method :( The version that worked was copied from the article *source* window while the '\xa0'-polluted variant came from the article *viewer*. (hope I'm having it right this time and KNode is not fooling me again...) Peter From fperez528 at yahoo.com Sun Sep 7 15:08:28 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 07 Sep 2003 13:08:28 -0600 Subject: Comments on Python Redesign References: <mailman.1062934990.9290.python-list@python.org> Message-ID: <bjfvnh$mkb$1@peabody.colorado.edu> Tim Parkin wrote: > Perhaps the people who have commented on the site should realise it's a > proposal and a work in progress. As constructive comments go the only > feedback I have gathered is that the fonts are too small and the > contrast is > a little low. I've adjusted contrast on key elements and also increased > the > font size. These pages are here : > > http://pollenation.net/assets/public/python-main-2.html > http://pollenation.net/assets/public/python-interior-2.html A few suggestions: - several (including myself) were thrown off-course by the fact that the posted 'site' was really just a screenshot, not really a live mockup (the word mockup tends to be used for junk-filled, but otherwise structurally valid sites rather than a graphical screenshot). I suggest you make an actual html mockup so that everyone can actually test how fonts scale in their own browsers. Viewing _any_ screenshot in my laptop's 1600x1200 screen is painful, because the fonts are microscopic. But a real html (even if the text it's filled with is junk), I can judge: I have my font sizes set in mozilla for readability, and it will be immediately obvious whether there are layout assumptions in the site which break at these resolutions. I am sure you'll get far better feedback with such a mockup site being accessible for the community to view. - I'm not sure I fall for the double-colored 'python' word. The two tones generate a mental split 'py-thon', which is, at least to me, rather unpleasant. Keep in mind that many things in the python community have a py pre/post-pended which would be more reasonable to break: pyexpect, scipy, numpy,... In all those cases, the separated 'py' tends to associate the 'python' part with the rest (expect, scientific computing, numerical work, etc). But 'thon' is nothing by itself, so the split is useless, and creates an artificial an unnecessary disruption in the reading flow. It feels like a clear case of graphical glitz done for its own sake, not at the service of function. Ant that is the ONE principle that the site should respect: ANY graphical enhancement should always serve, never sacrifice, function. - Contrast: even the newer screenshots feel very low contrast. Blue on grey isn't particularly readable. But perhaps when I view the real html with normal font sizes, it will look better. That's why you really need to post a readable html site, not a png: it's almost impossible for anyone but you to properly judge the site with graphical screenshots. - More content: why limit the front page to have so little in it? It feels like it was designed to fit 100% into an 800x600 window. I personally feel that a techincal website is ok with having the front page include some more stuff further down. I can use my scroll wheel to go down, but I hate having to click for separate pages for everything. I know it's a fine line, and you don't want the main page to be overly long, but I feel that the current mockup is unnecessarily short. And if you feel like people are being overly harsh, don't worry. It's usenet after all :) But also keep in mind that you're proposing touching the _main_ python.org website, so don't expect the entire community just to go with whatever you propose. In case you are new to this environment, go read some of the discussions on PEP-308 for a feel of how hot things can get when you want to touch core things. In the end, this is actually a good thing: it means that any idea which finally survives the beating will be pretty good. Think of a very harsh, very darwinian selection system :) Best regards, and good luck with the work. Fernando. From tdelaney at avaya.com Tue Sep 2 17:35:31 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 3 Sep 2003 07:35:31 +1000 Subject: Difference of hash and __hash__() Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEAD454A@au3010avexu1.global.avaya.com> > From: Terry Reedy [mailto:tjreedy at udel.edu] > > "Stefan Fleiter" <stefan.fleiter at web.de> wrote in message > news:bj2nv5$hna$1 at news.web.de... > > > under Python 2.2.2: > > > > >>> s = slice(None,5,None) > > >>> hash(s) > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > TypeError: unhashable type > > >>> s.__hash__() > > 136775584 > > > > Can anybody explain this? > > It looks like a bug. Extended slices were added for use by Numerical > Python. It may never have tried to hash them or only done so only > through the C equivavlent of s.__hash__. Extended slicing of > sequences was, I believe, only added in 2.3. Looks like a bug to me too. Stefan, please raise a bug report on Sourceforge (or it will get lost). Preferably add a patch and test suite ;) Tim Delaney From wilkSPAM at OUTflibuste.net Wed Sep 3 17:07:10 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Wed, 03 Sep 2003 23:07:10 +0200 Subject: How to accelerate python application GUI speed References: <43e3984e.0309030532.3fe88bbc@posting.google.com> <87n0dmj82w.fsf@flibuste.net> <877k4q6jj1.fsf@pobox.com> Message-ID: <87ekyxinsx.fsf@flibuste.net> jjl at pobox.com (John J. Lee) writes: > Wilk <wilkSPAM at OUTflibuste.net> writes: > >> ulysses_dm at yahoo.com.cn (ulysses) writes: > [...] >> An solution is to make a web application and use a tiny browser like >> kmeleon. > > Or MSIE, possibly using HTA. What is HTA ? I thought about an HTTPServer that could work with any browser. -- William Dode - http://flibuste.net From donald.welch.nospam at hp.com Thu Sep 4 11:11:57 2003 From: donald.welch.nospam at hp.com (djw) Date: Thu, 04 Sep 2003 08:11:57 -0700 Subject: Where to post useful code References: <2e1f6497.0309040646.3dcce9fb@posting.google.com> Message-ID: <3f575667@usenet01.boi.hp.com> RichB wrote: > Howdy all, > > I've written a few scripts that might be very useful to small groups > of people (i.e. extracting time stamps from pictures taken with Sony > digital cameras). > I don't want to start sourceforge projects or anything big like that. > I just want to make some stuff available. Where can I post/upload my > stuff? > > thanks, > > RichB Try here: http://www.uselesspython.com/ -Don From martin at v.loewis.de Mon Sep 15 17:42:11 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 15 Sep 2003 23:42:11 +0200 Subject: _ssl.so build problems on Solaris 8 for 2.3 References: <mailman.1063659200.574.python-list@python.org> Message-ID: <m3u17dwwy4.fsf@mira.informatik.hu-berlin.de> Skip Montanaro <skip at pobox.com> writes: > Is distutils missing some libraries or have I hosed the OpenSSL installation > somehow? The latter. You must make sure that the library you link with is position-independent, or else you must build _ssl as a builtin module (i.e. through Modules/Setup, as non-shared). Regards, Martin From dkuhlman at rexx.com Tue Sep 16 13:30:57 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 16 Sep 2003 10:30:57 -0700 Subject: list of lists References: <bk4grj$me3$1@news.uni-kl.de> <bk4k46$ort$03$1@news.t-online.com> <bk6gn4$57m$1@news.uni-kl.de> Message-ID: <bk7hb7$pt6pp$1@ID-139865.news.uni-berlin.de> Tom wrote: > Hi guys, > > thanks to everyone. > My mistake was that I had no idea that writing [][] NEXT to each > other goes into depth. I always tried different varieties of [[]] > to get into the deeper lists! > Thanks again. It's a simple concept, once you grasp it, but for those new to Python, it may be worth emphasizing -- You can concatenate operators (to the right, at least) and these operators will operate on the run-time value produced by the expression to which they are applied. For example (read from bottom up): getArray()[3].formatter() ^ ^ ^ ^ ^ | | | | | | | | | +--- (5) call function retrieved from | | | | attribute | | | +-------------- (4) access attribute of object indexed | | | from array | | +---------------- (3) index element of array returned by | | function call | +------------------- (2) call function retrieved from name | binding +------------------------ (1) retrieve value bound to variable It is also worth thinking about what is meant by saying that this evaluation is *dynamic*. For example, if the object returned by the function call to getArray (above) is not indexable, then the [] operator will fail. And, the only limiting factor is confusion. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From ivoras at fer.hr Tue Sep 16 12:51:38 2003 From: ivoras at fer.hr (Ivan Voras) Date: Tue, 16 Sep 2003 18:51:38 +0200 Subject: tuples vs lists Message-ID: <bk7eo9$g4g$1@bagan.srce.hr> Are there any performance/size differences between using tuples and using lists? -- -- Every sufficiently advanced magic is indistinguishable from technology - Arthur C Anticlarke From uj797 at victoria.tc.ca Fri Sep 26 15:56:06 2003 From: uj797 at victoria.tc.ca (Arthur T. Murray) Date: 26 Sep 2003 11:56:06 -0800 Subject: Explaining how a (Mind) program works References: <3LOdnYcq9oVxiOmiU-KYuA@metrocast.net> Message-ID: <3f748bc6@news.victoria.tc.ca> "Bill Modlin" <modlin1 at metrocast.net> wrote on Fri, 26 Sep 2003: <snip> >>> If I wanted to explain how one of my programs worked >>> I would not give someone a print out of the code. >>> First I would explain it in higher level (folk psychology?) >>> terms and then explain how I embodied these ideas in actual code. >> I'm not sure why - especially if the person you're explaining it to >> is a programmer and knows the language. BM: > For the same reason that all good programs are liberally annotated > with comments. Programming languages are for controlling computers, > not for communicating with people. It is laborious and error prone > to attempt to discover the purpose of an algorithm implemented by > a bit of code just by inspecting that code. ATM: Nevertheless the original source code has to be made available, e.g. http://www.scn.org/~mentifex/jsaimind.html -- AI Mind in JavaScript; http://mentifex.virtualentity.com/mind4th.html -- Mind.Forth PD AI. BM: > This is true even for the original author of the code. > Code that seemed crystal clear and obvious at the time > you wrote it is often indecipherable when a year later > you are called upon to adjust or fix it in some fashion. ATM: The factoring of Forth and the hierarchy of objects help here, plus liberal comments and statements at the end of each Mind- Module explaining to what other Module program-flow returns: http://mentifex.virtualentity.com/progman.html -- Modules. BM: > Of course, the extensional function of each line of code is obvious > to anyone who knows the language. There is no mystery in a line of > code that says to increment the value of some variable by two: > it says exactly what is to happen. [...] > Literal quoting of code is sometimes a useful adjunct to understanding > of function. We all generally like to have actual source to work with. Yes, and so the AI4U (AI For Your) textbook of artificial intelligence at http://search.barnesandnoble.com/bookSearch/isbnInquiry.asp?ISBN=0595259227 contains a full source-code listing of the AI Mind-1.1 in MSIE JavaScript. On September 24, 2003, a rather mean-spirited reviewer at B&N, hiding behind anonymity, complained that "This book is not really a textbook because it explains nothing. It rather is a collection of 'modules' which the author expects the reader to implement" -- without pointing out that the AI Mind modules are already implemented at the end of the book. Now this author is indeed trying to get Minds coded in XYZ languages: http://mentifex.virtualentity.com/cpp.html -- C++ with new AI code; http://mentifex.virtualentity.com/java.html -- see Mind.JAVA #1 & #2; http://mentifex.virtualentity.com/lisp.html -- Lisp AI Weblog; http://mentifex.virtualentity.com/perl.html -- first Perl module; http://mentifex.virtualentity.com/prolog.html -- Prolog AI Weblog; http://mentifex.virtualentity.com/python.html -- Python AI Weblog; http://mentifex.virtualentity.com/ruby.html -- Ruby AI Blog (OO AI); http://mentifex.virtualentity.com/scheme.html -- Scheme AI Weblog; http://mentifex.virtualentity.com/vb.html -- see "Mind.VB #001" link. BM: > But it is only an adjunct: the necessary ingredient for understanding > of non-trivial function is explanation of the principles of operation > in human-interpretable language. ATM: I have created every conceivable instrument of explaining the AI Mind. http://mentifex.virtualentity.com/acm.html is Steps to DIY AI. http://mentifex.virtualentity.com/standard.html -- AI Standards. http://mentifex.virtualentity.com/variable.html -- AI Variables. BM: > Given the code one may never understand what it is for. ATM: Recently I have been meeting in person with an incognito engineer who has volunteered to attempt to translate (port) Mind.Forth into http://mentifex.virtualentity.com/aicppsrc.html AI C++ Source Code. BM: > Given an understandable explanation of just what is to be done ATM: Nothing beats having a one-on-one interactive discussion of what is to be done to code AI and how to do it. That optimal option is why I have a dreamworld fantasy of hiring out to CS departments and AI labs to have my primitive but AI-coding brain picked clean and dry of any contribution I make to AI. > and how to do it, any programmer can produce new code > for a function readily enough: having an actual worked out > version to go by is a dispensable luxury. [...] A.T. Murray -- http://mentifex.virtualentity.com/python.html -- Python AI Weblog http://www.amazon.com/exec/obidos/ASIN/0595654371/ -- AI Textbook; http://www.sl4.org/archive/0205/3829.html -- Goertzel on Mentifex; http://doi.acm.org/10.1145/307824.307853 -- ACM SIGPLAN Mind.Forth From cnetzer at sonic.net Fri Sep 26 15:26:47 2003 From: cnetzer at sonic.net (Chad Netzer) Date: Fri, 26 Sep 2003 12:26:47 -0700 Subject: Comment on PEP-0322: Reverse Iteration Methods In-Reply-To: <5L%cb.13662$yD1.1524835@news20.bellglobal.com> References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <wCGcb.3064$yU5.2141@nwrdny01.gnilink.net> <8RScb.169633$R32.5449258@news2.tin.it> <uk77vhagj.fsf@boost-consulting.com> <WNYcb.12686$yD1.1505440@news20.bellglobal.com> <eppstein-B529F3.09181826092003@news.service.uci.edu> <dJ_cb.13620$yD1.1517951@news20.bellglobal.com> <eppstein-AF4213.10592426092003@news.service.uci.edu> <5L%cb.13662$yD1.1524835@news20.bellglobal.com> Message-ID: <1064604407.1708.21.camel@adsl-209.204.179.133.sonic.net> On Fri, 2003-09-26 at 11:42, Sean Ross wrote: > > I was questioning the feasibility of the implied semantics. > > Fine. Take it up with the person who proposed the idea. You proposed it (hear me out). You are missing David's point. In addition to whatever semantics a general reverse iterator might have, he is saying that the itertools iterators have an implied additional semantic of not (necessarily) needing to fully expand an iterable in memory to operate on it, as a general ireverse() would probably have to do. So, having ireverse potentially use up VAST quantities of memory, in order to work, doesn't quite fit into the itertools philosophy. That is the point he is making, and it is a specific comment on your (I believe; others have probably proposed it as well) suggestion of an ireverse() in itertools. Now, my response to David's point is that currently, cycle() may also require enough extra storage to remember an entire iterated sequence, so the itertools philosophy is not a hard rule. Still, ireverse() would imply some real devilry under the covers... -- Chad Netzer From __peter__ at web.de Mon Sep 15 10:58:46 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 Sep 2003 16:58:46 +0200 Subject: list of lists References: <bk4grj$me3$1@news.uni-kl.de> Message-ID: <bk4k46$ort$03$1@news.t-online.com> Tom wrote: > Hi, > > I have a list that consists of lists. > E.g. T=[[1, 2, 3], [4, 5], [6]] > Is there a way to address the a specific component in the "inner" list > directly? > E.g. right now I want to get the second value of the first list. > Unfortunately I have to save it to a variable first and then read it. > a = T[0] > print a[1] > > That kind of sucks, becaus I have to read a lot of values from a lot of > lists! :-( > Is there a faster way than my saving it to a "help variable" first? > > Thanks folks!! > > Regards, Tom Your example rather than your problem specification suggests that you want them all. If I'm guessing right: def flatten(lol): for lst in lol: for item in lst: yield item T=[[1, 2, 3], [4, 5], [6]] for item in flatten(T): print item Indices seem to be a dying breed :-) Peter From duncan at NOSPAMrcp.co.uk Fri Sep 12 04:44:19 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 12 Sep 2003 08:44:19 +0000 (UTC) Subject: os.listdir References: <HKYJXJ$IJtpKVwktIN8kOKo8RPo0eClW9NoSa2aMVXNcWgZA4d1srKaVwlRm@bol.com.br> <mailman.1063171515.17609.python-list@python.org> <bjq102$m21$03$1@news.t-online.com> <Xns93F3A4DD43D3Cduncanrcpcouk@127.0.0.1> <wSmdnYp3_9zFSf2iU-KYvA@comcast.com> Message-ID: <Xns93F4629B3A4A0duncanrcpcouk@127.0.0.1> "Terry Reedy" <tjreedy at udel.edu> wrote in news:wSmdnYp3_9zFSf2iU- KYvA at comcast.com: > > "Duncan Booth" <duncan at NOSPAMrcp.co.uk> wrote in message >> In C Python, all dictionaries have an initial size of 8 elements. > There is >> no way to override this (except recompiling!) > > In you initialize a dict from a list of, say, 1000 (key,value) pairs, > does it really disregard list size? at least after first 2/3rds > fillup? > Yes. Very roughly speaking dict.__init__ looks like this (except in C): def __init__(self, dict, **kw): if hasattr(dict, 'keys'): self.update(dict) else: for item in iter(dict): fast = tuple_or_list(item) assert len(fast)==2 self[fast[0]] = fast[1] The important point being that the code accepts an iterator rather than a list, so it doesn't know how many items will be returned. Of course there is nothing to stop someone adding a check whether the argument is really a list, and if so preallocating the size, but someone would have to evaluate whether the increased complexity, and longer runtime for smaller dictionaries justified the gain. There's another twist to this: d = dict(aList) At some point you have to create 'aList', and that too will start off small and double in size as it grows. Even if you just write a constant dictionary: d = { 1:1, 2:2 } the bytecode for this creates an empty dictionary, then evaluates each key, value pair and stores it in the dictionary. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From adalke at mindspring.com Fri Sep 5 21:48:48 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 06 Sep 2003 01:48:48 GMT Subject: Comparing objects - is there a maximum object? References: <7bdbb1a6.0309041124.6801b755@posting.google.com> <bj84rl$j2c$07$4@news.t-online.com> <1SN5b.8786$tw6.4739@newsread4.news.pas.earthlink.net> <m3ekywch7s.fsf@mira.informatik.hu-berlin.de> Message-ID: <42b6b.860$Yt.335@newsread4.news.pas.earthlink.net> Martin v. L?wis: > No, this would not be used. cmp(a,b) == -cmp(b,a) True. Unlike + and *, cmp is communitive. Here's the results of some instrumentation under 2.3. >>> class Max: ... def __getattr__(self, name): ... print "Looking for", name ... if name == "__cmp__": ... return lambda other: 1 ... raise AttributeError(name) ... >>> data = [Max(), 0, 1, 2, 3] >>> data.sort() Looking for __gt__ Looking for __coerce__ Looking for __cmp__ Looking for __gt__ Looking for __coerce__ Looking for __cmp__ Looking for __gt__ Looking for __coerce__ Looking for __cmp__ Looking for __gt__ Looking for __coerce__ Looking for __cmp__ >>> random.shuffle(data); data.sort(); data Looking for __lt__ Looking for __coerce__ Looking for __cmp__ Looking for __repr__ [0, 1, 2, 3, <__main__.Max instance at 0x013D8C88>] Not an __rcmp__ in the mix. Andrew dalke at dalkescientific.com From aleax at aleax.it Fri Sep 5 04:26:48 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 08:26:48 GMT Subject: newbie question about dictionnary ? References: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Message-ID: <cNX5b.16332$hE5.588360@news1.tin.it> Sophie All?on wrote: > Hi, > > CONTEXT > I do numerical simulation for which I have to process mesh. A mesh is made > of triangle which are made of points. > I want from this information to create edges and build triangle from edges > rather than from points. > > PROBLEM > An edge is shared by possibly more than one triangle. > > ALGORITHM > have a triangle class (made of 3 edges) > have an edge class (made of 2 points and embeding a triangle list > (those connected to the edge) OK, so, say for example (for 2-D meshes): import operator class Point(tuple): """ a convenience class Point, basically just a 2-items (x,y) tuple with handy constructor, accessors, representation """ __slots__ = () def __new__(cls, x, y): # assert operator.isNumberType(x) and operator.isNumberType(y) return tuple.__new__(cls, (x,y)) def getx(self): return self[0] def gety(self): return self[1] x = property(getx) y = property(gety) def __repr__(self): return "Point(%r,%r)" % self class Edge(tuple): """ basically a 2-items tuple of points (NB: sorted, since we do NOT deal with DIRECTED edges here!!!) with convenience constructor, accessors, representation, + list of triangles """ def __new__(cls, p1, p2): pts = [Point(*p1), Point(*p2)] pts.sort() return tuple.__new__(cls, pts) def __init__(self, p1, p2): self.triangles = [] def __repr__(self): return 'Edge((%r,%r),(%r,%r))' % (self[0]+self[1]) The Triangle class may of course be made along very similar lines. A slightly more efficient representation of Edge might use containment of and delegation to tuple rather than inheriting from it (problem is that inheriting from tuple impedes using a non-empty __slots__, so in this code each Edge instance carries around an instance dictionary). An even more clever approach might be to keep the edge->triangle data NOT as per-instance data of edges but as a class-level attribute and use a property for edge.triangles access, but that would violate the explicit specs you give for the edge class. > for each triangle construct its edges but I have to check if the edge > already exists > > for doing this I thought the dictionary was excellent but the key is a > string while I want it > to be the 2 points forming the edge ? How to do it ? > > Have you a better idea ? Strings just don't enter the picture here: edges are perfectly acceptable keys into dictionaries, since they ARE tuples. I do think that not having each edge 'embeding a triangle list', as you put it, is an even better idea. But, although a bit more complicated and less efficient, your idea can also work fine. And, yes, of course you need a dictionary (in fact that is why it's better to not ALSO have the triangle list IN the edge instance -- it might as well be in the dictionary anyway... !!!). Alex From geoff at gerrietts.net Mon Sep 15 16:28:06 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Mon, 15 Sep 2003 13:28:06 -0700 Subject: irritating problem In-Reply-To: <20030915150042.22749.00001062@mb-m23.aol.com> References: <20030915150042.22749.00001062@mb-m23.aol.com> Message-ID: <20030915202806.GK21288@thoth.homegain.com> Quoting Park997 (park997 at aol.comnotospam): > Hi, > > I have a script that runs correctly in IDLE, runs correctly when > invoked in the Command Prompt (Win XP), runs correctly from Komodo, > but flashes a black box too fast to see when the icon is double > clicked and produces no output. There are no error meassages from > any of the methods that produce output. All of the other modules in > the same directory (these are imported to the problem module) work > correctly in any start mode. It would be useful to know specifically what output you are expecting versus what output you are getting. If it's flashing the box and disappearing, it's conceivable that you could change the properties such that the cmd window doesn't disappear after the program completes, right? Thanks, --G. -- Geoff Gerrietts "I think doorways are sexist." <geoff at gerrietts net> --Jayson Lockwood From john.abel at pa.press.net Sat Sep 20 08:28:53 2003 From: john.abel at pa.press.net (John Abel) Date: Sat, 20 Sep 2003 13:28:53 +0100 Subject: Help Compiling 64bit Python In-Reply-To: <m3brtf3dhp.fsf@mira.informatik.hu-berlin.de> References: <mailman.1064055636.13785.python-list@python.org> <m3brtf3dhp.fsf@mira.informatik.hu-berlin.de> Message-ID: <3F6C4805.5090108@pa.press.net> Martin v. L?wis wrote: >John Abel <john.abel at pa.press.net> writes: > > > >>c++ -o python \ >> Modules/python.o \ >> libpython2.3.a -lresolv -lsocket -lnsl -lrt -ldl >>-lpthread -lm >>ld: fatal: file Modules/python.o: wrong ELF class: ELFCLASS64 >>ld: fatal: File processing errors. No output written to python >>collect2: ld returned 1 exit status >>make: *** [python] Error 1 >> >>I'd be very grateful for any pointers. >> >> > >You need to arrange to use the -m options in the linker line as well. > >Looking at the generated Makefile will tell you where to best insert >these options. > >Regards, >Martin > > I seem to be missing something really obvious here. I've modified the Makefile so it looks like this: CONFIG_ARGS= 'CC=gcc -mcpu=v9 -m64 -D_LARGEFILE64_SOURCE=1' 'LDFLAGS=-mcpu=v9 -m64' ran the make, and it still comes up with the same error. I've even tried running it with LDFLAGS=-64, with the same result. Regards John From mk at net.mail.penguinista Mon Sep 1 10:32:01 2003 From: mk at net.mail.penguinista (=?UTF-8?B?0LTQsNC80ZjQsNC9INCzLg==?=) Date: Mon, 01 Sep 2003 16:32:01 +0200 Subject: ANN: Python for arm-linux feed References: <biqbhg$c04ej$1@ID-192111.news.uni-berlin.de> Message-ID: <3f535861@news.mt.net.mk> > My feed @ http://opie.net.wox.org/python has been updated. > > Highlights: > > - Python 2.3 > - PyQt 3.8 > - PyXML 0.8.3 > - PySQLite 0.4.3 Cool, though I already have python 2.3 and PyQT from the riverbank web-site I think I'm gonna install your packages instead, because you have more packages... BTW I was testing some scripts with PyQT on my Ipaq/Opie/Familar. On my Desktop the script runs fine and it acquires KDE's look-and-feel, but on the IPAQ it shows in the generic QT/E look-and-feel - it doesn't acquire the general OPIE look.. Would you know why is that? Here's the script: import sys from qt import * class HelloButton(QPushButton): def __init__(self, *args): QPushButton.__init__(self, *args) self.setText("Hello World") self.connect(self, SIGNAL("clicked()"), self.my_func) def my_func(self): t = str(self.text()) + "!" self.setText(t) class HelloWindow(QMainWindow): def __init__(self, *args): QMainWindow.__init__(self, *args) button=HelloButton(self) self.setCentralWidget(button) def main(args): app=QApplication(args) win=HelloWindow() win.show() app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()")) app.exec_loop() if __name__=="__main__": main(sys.argv) -- ?????? (jabberID:damjan at bagra.net.mk) Loose bits sink chips. From brucedickey at micron.com Mon Sep 29 13:31:42 2003 From: brucedickey at micron.com (Bruce Dickey) Date: Mon, 29 Sep 2003 11:31:42 -0600 Subject: [joke] Any tool to translate PHP to Python? References: <vnbnv0c5g01rff@corp.supernews.com> <3f75f5b8$0$20650$626a54ce@news.free.fr> <vncdncfj0csgdf@corp.supernews.com> <cb035744.0309281309.267f4d5c@posting.google.com> Message-ID: <bl9q9u$e57$1@admin-svc.micron.com> "Will Stuyvesant" <hwlgw at hotmail.com> wrote in message news:cb035744.0309281309.267f4d5c at posting.google.com... > > [Bruce Dickey] > > > [Bruno Desthuilliers] > > > Bruce Dickey wrote: > > > > > >> Hi, > > >> > > >> I have some PHP scripts I'm moving from my web server to the local PC. > > >> They just do file manipulation. > > >> > > >> Anybody know of a tool for translating PHP to Python? > > > > > > > > > Er... What about a programmer ?-) > > > > > > (sorry, could not resist) > > > Bruno > > > > > > > Heh heh. Point taken. I actually *was* assuming I would be the tool -- > > ... > > It seems to me that for folks migrating from PHP to Python, a translator > > would be a handy tool. > > Um, was the point was really taken? Translating programming languages > is *very* hard. Otherwise, it would be possible to just translate > Python to C, with all the obvious benefits. > > Perhaps automatic translation of some standard PHP patterns is > possible? No, still too hard. Think about it. > > -- > The subspace _W inherits the other 8 properties of _V. And there > aren't even any property taxes. > -- J. MacKay, Mathematics 134b Yes, it was really taken. I know its hard, but not impossible. Source translators exist for a number of languages, such as Basic to Pascal, Pascal to C, C to Pascal, VB to Python, Java to C++.... Some are only partial, but that provides a good start. That people have created compilers for that pathological language C++ shows what can be done with determination. PHP is a (much) simpler language. I have no plans to write a PHP to Python translator, however. I have only a few small scripts to convert. Bruce From tebeka at cs.bgu.ac.il Tue Sep 30 07:02:10 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 30 Sep 2003 04:02:10 -0700 Subject: Prime number module References: <Xns9405ABFC8A4D3dagvelvetnet@195.67.237.51> Message-ID: <33803989.0309300302.3b128cdf@posting.google.com> Hello Dag, > Is there a python module that includes functions for working with prime > numbers? I mainly need A function that returns the Nth prime number and > that returns how many prime numbers are less than N, but a prime number > tester would also be nice. I'm dealing with numbers in the 10^6-10^8 range > so it would have to fairly efficient Try gmpy (http://gmpy.sourceforge.net/) HTH. Miki From roberto at dealmeida.net Mon Sep 22 13:07:23 2003 From: roberto at dealmeida.net (Roberto A. F. De Almeida) Date: 22 Sep 2003 10:07:23 -0700 Subject: Playing with dictionaries Message-ID: <10c662fe.0309220907.a84bea5@posting.google.com> Hi, Suppose I have a dictionary containg nested dictionaries. Something like this: >>> pprint.pprint(dataset) {'casts': {'experimenter': None, 'location': {'latitude': None, 'longitude': None}, 'time': None, 'xbt': {'depth': None, 'temperature': None}}, 'catalog_number': None, 'z': {'array': {'z': None}, 'maps': {'lat': None, 'lon': None}}} I want to assign to the values in the dictionary the hierarchy of keys to it. For example: >>> dataset['casts']['experimenter'] = 'casts.experimenter' >>> dataset['z']['array']['z'] = 'z.array.z' Of course I would like to do this automatically, independent of the structure of the dictionary. Is there an easy way to do it? Thanks, Roberto From lk at digicart.hu Thu Sep 18 05:22:15 2003 From: lk at digicart.hu (Ladvánszky Károly) Date: Thu, 18 Sep 2003 09:22:15 GMT Subject: DLL info Message-ID: <b03da24326888105a23a49b85f0660bb@news.meganetnews.com> Could someone suggest me how to gather various information (version number etc.) from a Windows DLL? Thanks for any help, K?roly From michaelmossey at yahoo.com Wed Sep 3 16:19:52 2003 From: michaelmossey at yahoo.com (Michael Mossey) Date: 3 Sep 2003 13:19:52 -0700 Subject: installing PyQt Message-ID: <9badaf0.0309031219.666fa852@posting.google.com> Hi, I'm trying to install PyQt for windows together with non-commercial Qt version 2.3.0. When I try to run a sample Qt program I get this error: File "c:/DOCUME~1/mossey/LOCALS~1/Temp/python-1872fAk", line 1, in ? from main_qt import * File "main_qt.py", line 2, in ? from qt import * File "C:\PROGRA~1\Python22\lib\site-packages\qt.py", line 17, in ? import libsip ImportError: DLL load failed: The specified module could not be found. I'm assuming it can't find libsip.dll. This file is located in the directory C:\Program Files\Python22\Lib\site-packages\ and I added that directory to both the PYTHONPATH and the PATH. This is windows 2000 so I used the system dialog to do it, and then rebooted the computer (I don't know if rebooting is necessary). I keep getting the same error. I tried copying libsip.dll to the C:\winnt directory and it still didn't find it. Can someone familiar with Python on Windows 2000 give me a clue here? Regards, Mike From cavok at freemail.it Thu Sep 4 18:39:36 2003 From: cavok at freemail.it (Domenico Andreoli) Date: Thu, 04 Sep 2003 22:39:36 GMT Subject: this is my own python-setuid.c Message-ID: <IaP5b.292632$Ny5.9039455@twister2.libero.it> Hi, I did a little research about execution of Python setuid scripts. I found only a couple of C wrappers I don't like. So I wrote my own, it is available at [0]. Feel free to send comments. 2c [0] http://savannah.nongnu.org/cgi-bin/viewcvs/prua/prua/python-setuid.c -----[ Domenico Andreoli, aka cavok --[ http://filibusta.crema.unimi.it/~cavok/gpgkey.asc ---[ 3A0F 2F80 F79C 678A 8936 4FEE 0677 9033 A20E BC50 From stevewilliams at wwc.com Mon Sep 15 23:26:39 2003 From: stevewilliams at wwc.com (Steve Williams) Date: Tue, 16 Sep 2003 03:26:39 GMT Subject: Anyone? Anyone? Message-ID: <Ppv9b.17302$NX3.3614@nwrddc01.gnilink.net> The following runs slow, as you might expect. I'm open to advice. . . . def GetTotalPages(self): self.PPIPrinterWidth = 100 #whatever self.PPIPrinterHeight = 100 #whatever self.screenscale = 1.0 #whatever bitmap = wxEmptyBitmap( PrinterDefinition['PageWidth'] * self.PPIPrinterWidth ,PrinterDefinition['PageHeight'] * self.PPIPrinterHeight) DC = wxMemoryDC() DC.SelectObject(bitmap) self.page_total = 0 while self.DoDrawing(DC) <> False: self.page_total += 1 return self.page_total . . From smory at ptdprolog.net Mon Sep 1 12:50:03 2003 From: smory at ptdprolog.net (Daniel R. Smorey Jr.) Date: Mon, 01 Sep 2003 12:50:03 -0400 Subject: Python Documentation? In-Reply-To: <mailman.1062392643.28659.python-list@python.org> References: <LQydncwLlNp2UM-iXTWJkA@comcast.com> <mailman.1062392643.28659.python-list@python.org> Message-ID: <QO2dndjrvOR15c6iU-KYgw@comcast.com> Steven Taschuk wrote: > Quoth Daniel R. Smorey Jr.: > > > For full-text searches, try <http://www.pydoc.org/>. > > For functions and whatnot, there's the index of the Library > Reference, <http://www.python.org/doc/2.3/lib/genindex.html>. > That's exactly what I was looking for! I didn't even know until now that you don't have to import string and that split is part of python now. pydoc.org gave me that in the first page of hits, I think the second hit. Thanks... From pieter at countersnipe.com Thu Sep 11 08:06:10 2003 From: pieter at countersnipe.com (Pieter Claassen) Date: Thu, 11 Sep 2003 13:06:10 +0100 Subject: How to compile 3rd party python into single large binary Message-ID: <pan.2003.09.11.12.06.10.354732@countersnipe.com> I am developing an app that pulls loads of 3rd party python libraries/code in. The problem is that I don't want to require potential buyers to struggle to get the software going: Problems might be: 1. Packaging system that they use to pull applications onto their machine does not have the right modules. 2. They now have to run and maintain tar.zipped installs 3. They want to use the software, not spend a long time installing it 4. They might be on windows or linux The software will be distributed both as a standalone product as well as with a debian based larger product that already includes all the libraries. So, here is my question: 1. Does anybody know of a way to build a single large file containing all the source/compiled code? I don't want to change the software to have to bundle my and third party packages together in the same dir. Thanks, Pieter From emile at fenx.com Fri Sep 26 21:28:53 2003 From: emile at fenx.com (Emile van Sebille) Date: Fri, 26 Sep 2003 18:28:53 -0700 Subject: Saving Numeric arrays to file? References: <bl2ktf$8lq$1@news6.svr.pol.co.uk> Message-ID: <bl2ov9$78mdr$1@ID-11957.news.uni-berlin.de> Duncan Smith asks about writing Numeric arrays to disk: > [ 0, 0, 0, 5, 0, 0]]) > >>> f = file('c:\Data\IS_rounded.txt', 'w') > Perhaps with 'wb' ? Emile van Sebille emile at fenx.com From nskhcarlso at bellsouth.net Tue Sep 2 08:15:03 2003 From: nskhcarlso at bellsouth.net (KC) Date: Tue, 02 Sep 2003 08:15:03 -0400 Subject: htmllib.py and parsing malformed HTML In-Reply-To: <bj1sh5$e9i7j$1@ID-63505.news.uni-berlin.de> References: <G1T4b.2227$gJ.1163@bignews3.bellsouth.net> <bj1sh5$e9i7j$1@ID-63505.news.uni-berlin.de> Message-ID: <JP%4b.4205$tH.3863@bignews4.bellsouth.net> Thomas G?ttler wrote: > > Hi, > > You could use tidy (http://www.w3.org/People/Raggett/tidy/) before you > parse the html. I appreciate the suggestion but unfortunately this will not work well for me as the parser runs as part of a cron job. I wouldn't be able to review the tidy error log in a timely fashion if there was a problem. What would be really nice is a way to tell the parser it was "inside" a <TR> when I encountered a <TD> after a closing </TR>. Browsers still display the HTML correctly without a starting <TR>, but if the closing </TR> is omitted everything gets mangled. Any other suggestions? From richard.townsend at edl.uk.eds.com Wed Sep 10 03:18:06 2003 From: richard.townsend at edl.uk.eds.com (Richard Townsend) Date: 10 Sep 2003 00:18:06 -0700 Subject: Image on disabled button References: <1062436629.69505.0@dyke.uk.clara.net> <cpm7b.930437$3C2.21206984@news3.calgary.shaw.ca> <1063135933.53254.0@doris.uk.clara.net> Message-ID: <7e337cbf.0309092318.3019e1cb@posting.google.com> > > (From memory) the following options added after creating the root window > prevent the bug occurring on HP-UX11i > > self.root.option_add('*background', 'grey75') > self.root.option_add('*disabledBackground', '') > I have now checked again on HP-UX and have found that you must also set: self.root.option_add('*disabledForeground', '') to stop the bug appearing... From tireseas at onetel.com Sun Sep 7 14:08:26 2003 From: tireseas at onetel.com (Andy) Date: Sun, 07 Sep 2003 19:08:26 +0100 Subject: Testing Message-ID: <pan.2003.09.07.18.08.26.970255@onetel.com> This is not a post it is a test - please ignore From ceiesa at excite.com Sat Sep 27 22:30:48 2003 From: ceiesa at excite.com (Bruce Dickey) Date: Sat, 27 Sep 2003 20:30:48 -0600 Subject: Meta programming question In-Reply-To: <slrnbncfom.118.bignose-hates-spam@rose.localdomain.fake> References: <vnce64dgqj047c@corp.supernews.com> <slrnbncfom.118.bignose-hates-spam@rose.localdomain.fake> Message-ID: <vnciijiteci947@corp.supernews.com> Ben Finney wrote: > On Sat, 27 Sep 2003 19:18:15 -0600, Bruce Dickey wrote: > >>I've read a number of the meta progamming articles. I have not found >>what I am looking for. I want to override assignments to variables >>which are in the module namespace (not object members -- no classes >>involved). Can this be done? > > > AFAIK, no. If it were possible, it would be very confusing. > > What is it you're trying to achieve? Perhaps a better alternative can > be suggested that doesn't break expected behaviour. > I'm investigating the use of Python as a grammar language. I'm trying to achive minimal required syntax/verbage. Thanks, Bruce From max at alcyone.com Sun Sep 7 21:01:17 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 07 Sep 2003 18:01:17 -0700 Subject: Is there a unicode EOF mark like DOS ascii ctl-z or unix crl-d ? References: <bjgf10$d5s$0@216.39.172.122> Message-ID: <3F5BD4DD.57D90AF5@alcyone.com> Bengt Richter wrote: > I couldn't find one. Unicode subsumes the normal ASCII control characters, so U0004 is EOT (end of transmission) just like 0x04 in ASCII is: http://www.unicode.org/charts/PDF/U0000.pdf Unicode also includes a _symbol_ for it at U2404. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The work will teach you how to do it. \__/ (an Estonian proverb) From jepler at unpythonic.net Tue Sep 2 18:33:01 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 2 Sep 2003 17:33:01 -0500 Subject: what's wrong with REBOL? In-Reply-To: <bj30il$eoev7$2@ID-125932.news.uni-berlin.de> References: <6005702b.0309020727.4ba46e78@posting.google.com> <bj30il$eoev7$2@ID-125932.news.uni-berlin.de> Message-ID: <20030902223301.GA11303@unpythonic.net> On Tue, Sep 02, 2003 at 09:03:17PM +0000, Christopher Browne wrote: > "What's wrong" is that 'proprietary nature.' If I write code in Perl, > Python, or Ruby, I can be certain that I won't get bitten because of > someone pulling the rug out from under them. > > I can't be certain in the same way of the perpetual availability of > REBOL. Of course, it's also possible that it might become impossible to use "non-proprietary" software. There are legal reasons: Perhaps the software will be found to violate a patent, or infringe copyright. Perhaps it will be judged to violate a DMCA-type law. Perhaps a new "software defects" law will be impossible for free software to conform to (for instance, due to a requirement that the software developer post a bond against damages caused by defects in the software). There are also technical reasons: How many programmer-hours do you think it would take to port X10 (the predecessor to X11) to MacOS X running on Itanium? Or to XBox2? What if the dominant machine/OS combination in the future makes it hard or impossible to run programs written in your chosen language (JVM doesn't support C efficiently, for instance), or uses DRM to keep you from running arbitrary unsigned code (under a system of this type, interpreters like Python would obvously never be Signed) Jeff From quentel.pierre at wanadoo.fr Wed Sep 24 07:29:35 2003 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Wed, 24 Sep 2003 13:29:35 +0200 Subject: Checking if the computer is online References: <mailman.1063865847.25960.python-list@python.org> <bkcgfm$gu1$1@news.island.liu.se> <mailman.1064300795.6408.python-list@python.org> Message-ID: <bkrv6t$hq8$1@news-reader2.wanadoo.fr> Have you tried : socket.gethostbyname(socket.gethostname()) or socket.gethostbyname_ex(socket.getfqdn())[2] Normally the result should be different if you're connected or not Cheers, Pierre "Mickel Gr?nroos" <mickel at csc.fi> a ?crit dans le message de news:mailman.1064300795.6408.python-list at python.org... On Thu, 18 Sep 2003, Thomas Bellman wrote: > Mickel Gr?nroos <mickel at csc.fi> wrote: > > > Hi all, > > > I have a silly question. Is there are simple way to check if the computer > > is connected to the Internet? It seems this should be a pretty > > straight-forward thing to do, but as I am totally unfamiliar with sockets > > and such, I ask for your help before getting my hands dirty. > > First of all you need to define what "being online" means... [...] > Or perhaps you should tell us *why* you believe you need to check > if the computer is connected to the Internet or not. Then we can > go directly to telling you that it is a bad idea, and suggest what > you should do instead. <0.5 wink> OK, here's what I want to do: When the Tkinter application I am writing starts up, it checks if certain files on the web exists and if so, it downloads them to a local directory replacing possible earlier copies of these files. So, what I mean by checking if the computer is online is that I want to check if I can access these certain remote files with urllib.urlretrieve(). If I can, then I download them. If I can't, I assume the computer is not connected to the Internet and I skip the update phase. The problem with just running urllib.urlretrieve() is that the execution of the script halts as there is no timeout available for Python 2.2.2. (I tried timeoutsocket.py to get this done, but that only worked on Windows 2000, not Redhat Linux 7.0. I also tried upgrading to Python 2.3, but that caused some other problems, especially with the gettext module and with the fact that my ISO-8859-1 encoded files needed a "coding" line.) So that's that. Anybody still got a few lines of code that would get this done on Python 2.2.2 on Windows _and_ Linux? Cheers, /Mickel G. -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From peter at engcorp.com Thu Sep 4 17:40:38 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Sep 2003 17:40:38 -0400 Subject: Output in color References: <mailman.1062707716.17757.python-list@python.org> Message-ID: <3F57B156.ADCDE0CF@engcorp.com> Bradford Powers wrote: > > I'm curious how I can make Python print text in color. Begin by specifying the platform on which you want this to work, and other possibly relevant details such as whether this is a console program or one with a GUI (presumably not), and maybe some other details I can't think of right now. Also you might check the archives of this newsgroup at groups.google.com. This sort of question comes up fairly often. Might even be a FAQ at this point (see www.python.org). -Peter From mwh at python.net Tue Sep 2 07:37:03 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Sep 2003 11:37:03 GMT Subject: Compiler C or Python? References: <20030826213316.GA7285@unpythonic.net> <mailman.1062498963.22409.python-list@python.org> Message-ID: <7h3vfsbh1bg.fsf@pc150.maths.bris.ac.uk> jhf at hex.no (J?rgen Hermanrud Fjeld) writes: > On Tue, Aug 26, 2003 at 04:33:17PM -0500, Jeff Epler wrote: > > 4. It's possible to write code so that __import__ uses compiler.compile > > instead of the written-in-C compiler, but I don't have this code handy. > > Also, a test suite is needed, and presumably a written-in-C implementation > > as well. (option 2: make the compiler.compile interface the standard > > compiler, and let the builtin compiler support a Python subset > > sufficient to bootstrap the written-in-python compiler, or arrange > > to ship .pyc of the compiler package and completely get rid of the > > written-in-C compiler) > > Could you make an effort to locate that code, or give some suggestions to > where I might locate it myself? > > And in general, if should want to alter the Python compiler, should > I start with the Python or C version? Whichever's easiest :-) This is usually the Python one. A toy that might come in handy is an interactive mode (based on code.InteractiveConsole) that compiles input with the customized compiler. > As far as I can see from your email the Python version is easier to > modify, but why two compilers? Isn't that a lot to maintain? The Lib/compiler/ package is pretty slow. Also, making that the only compiler might lead to irritating bootstrapping problems (which I now see Jeff talked about...). Cheers, mwh -- Do I do everything in C++ and teach a course in advanced swearing? -- David Beazley at IPC8, on choosing a language for teaching From skip at pobox.com Tue Sep 30 10:03:45 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Sep 2003 09:03:45 -0500 Subject: build a static python executable on linux? In-Reply-To: <blafsa$3i5$1@news1.ucsd.edu> References: <blacgq$2qe$1@news1.ucsd.edu> <g7ehnv0r4okuds8jarvmqj6tnntlm0bvhs@4ax.com> <blafsa$3i5$1@news1.ucsd.edu> Message-ID: <16249.36161.620488.759202@montanaro.dyndns.org> Alex> I am able to compile a static interpreter (using -static Alex> -static-libgcc) but I can not build the extensions correctly. You effectively need to transport yourself back in time before distutils existed, and modify Modules/Setup (or more correctly, Modules/Setup.local) appropriately to define the build commands for all the extension modules you want to include in your interpreter. It's a little tedious the first time (it will probably take a few iterations to get everything correct), but once you get the hang of it, it's easy to do. Use the compile and link commands output by distutils to give yourself a head start on -I, -L and -l flags to include in your definitions. Many of the commented out definitions are probably also close. If you identify some modules with no commented out build definitions in the Setup file, please file a bug report on SourceForge. Skip From jim_kerr at agilent.com Mon Sep 29 20:36:34 2003 From: jim_kerr at agilent.com (Jim Kerr) Date: 29 Sep 2003 17:36:34 -0700 Subject: Has anyone used decompyle recently? Message-ID: <50626d00.0309291636.806cbc7@posting.google.com> I am trying to reconstruct Python source files from an application I generated from py2exe. I accidentally deleted the sources for the app, but the py2exe-generated executable contains .pyc files for all the sources. I would love to be able to reverse engineer the .pyc files back to the source. I did find some mention in this group of a utility called decompyle, and I tried downloading the goodies from http://www.crazy-compilers.com/decompyle/. Neither version of decompyle seems to work. The 0.6 version can't handle Python 2.2 compiled code, and the installer for the 2.2beta1 fails on Windows. Has anyone out there been able to decompile 2.2 compiled code? I guess I could try to modify the source for decompyle 0.6 to work with Python 2.2, but since I have zero experience with Python compilation internals, that could be a tough slope to climb. Any help would be much appreciated! Jim Kerr Agilent Technologies Santa Rosa, CA From quentel.pierre at wanadoo.fr Tue Sep 16 06:26:49 2003 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Tue, 16 Sep 2003 12:26:49 +0200 Subject: embedding python code in html, like PHP References: <mailman.1063566798.31909.python-list@python.org> Message-ID: <bk6oh7$18e$1@news-reader2.wanadoo.fr> Take a look at Karrigell : http://karrigell.sourceforge.net Pierre "python" <python at sarcastic-horse.com> a ?crit dans le message de news:mailman.1063566798.31909.python-list at python.org... > Hi- > > Is there a python module that will allow me to embed code into an html > document, sort of like php? > > Thanks. > From tzot at sil-tec.gr Tue Sep 16 17:25:17 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 17 Sep 2003 00:25:17 +0300 Subject: how to build a list of mx.DateTime objects from a start and end date? References: <mailman.1063742662.14136.python-list@python.org> Message-ID: <6pvemvgr4hmd2fqgnltdum7b5g8ti6a7cn@4ax.com> On Tue, 16 Sep 2003 16:02:53 -0400 (EDT), rumours say that python at sarcastic-horse.com might have written: >I want to make a list of mx.DateTime objects that cover all the monthly >intervals between two points. For example: > >>>> import mx.DateTime >>>> nov1999 = mx.DateTime.Date(1999, 11) >>>> mar2003 = mx.DateTime.Date(2003, 3) >>>> alldates = mk_list(startdate=nov1999, enddate=mar2003) >>>> alldates >[ ... a bunch of mx.DateTime objects including and between the startdate >and enddate ...] > >How would I do something like this? I'm not familiar with the exact names of the mx functions, but what I would do, would be: create an empty list set an mx.DateTime object to the start date while the mx.DateTime is less or equal to the end date: append it to the list, add one day to it Add some parentheses and you got the python code :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From bgailer at alum.rpi.edu Mon Sep 22 11:57:41 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 22 Sep 2003 09:57:41 -0600 Subject: Slicing vs .startswith In-Reply-To: <3F6F12A1.3010702@bu.edu> References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> <bkk4h1$9ke$06$1@news.t-online.com> <mailman.1064154389.29357.python-list@python.org> <bkmd4q$t13$05$1@news.t-online.com> <DUCbb.100826$hE5.3550910@news1.tin.it> <3F6F12A1.3010702@bu.edu> Message-ID: <6.0.0.22.0.20030922095602.03339dd0@66.28.54.253> At 09:17 AM 9/22/2003, Shu-Hsien Sheu wrote: >Hi, > >I have a question about the comparison of efficiency of string slicing and >using string.startswith. >For example, which one of the following would be more efficient, or , >moreover, more pythonic? > >if aa[:3] == 'abc': > >vs > >if aa.startswith('abc'): Here's one way to address this kind of question: >>> import time >>> def f(): ... st = time.time() ... for i in range(500000): ... if aa.startswith('abc'):pass ... print time.time() - st ... >>> f() 1.01200008392 >>> def f(): ... st = time.time() ... for i in range(500000): ... if aa[:3] == 'abc':pass ... print time.time() - st ... >>> f() 1.01100003719 Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From ajsiegel at optonline.net Thu Sep 11 10:22:12 2003 From: ajsiegel at optonline.net (Arthur) Date: Thu, 11 Sep 2003 10:22:12 -0400 Subject: OT: Americans love their guns Message-ID: <000d01c37870$181e6020$0c02a8c0@Arts> I had written: >To in fact specifically not be a statistic. >Yes, there is something quite American about that viewpoint. God bless. Adding a bit more polemic/point-of-view to a polemic/point-of-view that is not fully my own, but with which I have considerable sympathy: That the statisticians have to understand themselves as impotent in this argument. Except that to the extent that statistics indicate a cost to the freedom to gun ownership, another cost of freedom has been identified. There are many. Why wouldn't there be. Nothing worthwhile is without cost. Rubbing those costs in one's face? To what end? Art From bokr at oz.net Fri Sep 12 13:57:46 2003 From: bokr at oz.net (Bengt Richter) Date: 12 Sep 2003 17:57:46 GMT Subject: safari References: <b15d2792.0309030339.3ac939e7@posting.google.com> <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <elC5b.11632$hE5.410636@news1.tin.it> <51809ae4.0309040634.7999e400@posting.google.com> <L%06b.18004$hE5.637245@news1.tin.it> <51809ae4.0309110734.1e5d28be@posting.google.com> <87y8wvfd6d.fsf@pobox.com> <RXLY/kKkXU4e092yn@gnosis.cx> <mailman.1063303282.4058.python-list@python.org> Message-ID: <bjt1eq$dui$0@216.39.172.122> On Thu, 11 Sep 2003 13:58:53 -0400, mertz at gnosis.cx (David Mertz) wrote: >jjl at pobox.com (John J. Lee) wrote previously: >|Pearson and O'Reilly owned by a single company, or something? I have >|a vague recollection that Pearson owns some other companies... > >There's been a huge amount of consolidation in publishing. Pearson is >not the parent of Addison-Wesley, Longman, Benjamin Cumming, New Riders, ^^^-- assume you mean "now" >Peachpit, Cisco Press, Prentice Hall, SAMS, Que, and several more >imprints. It's really a rather bad thing, although they do not seem to >use the degree of ideological acid-test that, say, MediaCorp >acquisitions do. > >I started writing my book for AW, only to find it a Prentice book when >it was published (it still has the AW imprint, but the meaning seems >diluted). > >That said, I'm pretty sure that O'Reilly remains one of the few >independent publishers of technical books. I think Manning is also. > [OT] So instead of a distributed implementation of business, with no individual way of making billion dollar mistakes, the consolidation centralizes control and makes billion dollar mistakes both possible and survivable, and therefore more probable. And if one of these titanic dinosaurs starts faltering, it is so socially disruptive that tax payers have to provide survival insurance one way or another. Evolution at work ;-/ [really OT] Factoids: Iraq 2002 per capita GDP: ~$2,400. Iraq population: ~24.7 million. $87bn if distributed to all Iraquis: ~$3,500. per capita. And that's just the new increment. Sorry. Just trying to get a concept of what these numbers mean. Or could have meant. (E.g., if you wanted to put 100 tourists on each and every square mile of Iraq at the same time, with $87bn you could give every tourist a ~$5,000. travel budget to do it). (87e9/168e3)/100 => 5178.5714285714284) It would be interesting to compare the effects of the expenditure alternatives if it were possible. IMO tourism would have been a lot more fun (and good for airlines too). I suspect peaceful expenditures have more business multipliers in them, not to mention what happens in people's minds if they can enjoyably meet as humans rather than agents of some extraneous worry ;-) (Ok, let's not get into the logistics of sending 16.8 million tourists with $5k each at the same time to one country ;-) Besides that's only $84bn. We have $3bn in roundoff to spare ;-) Regards, Bengt Richter From fgeiger at datec.at Tue Sep 30 07:27:46 2003 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 30 Sep 2003 13:27:46 +0200 Subject: [PMW 1.2] Dialog controls vanish upon editing References: <3f794786@news.swissonline.ch> <blbi7l$j17$06$1@news.t-online.com> Message-ID: <3f796866@news.swissonline.ch> Thanks Peter, but this method doesn't seem to be the reason. I placed a "return 1" as the first statement in its body. No change for the better. Kind regards Franz GEIGER "Peter Otten" <__peter__ at web.de> schrieb im Newsbeitrag news:blbi7l$j17$06$1 at news.t-online.com... > F. GEIGER wrote: > > > Hi all, > > > > I use PMW 1.2 on Python 2.3.0 on Win2k. > > > > I've created a dialog that looks like so: > > > > +----------------------+ > > Name | | > > +----------------------+ > > +----------------------+ > > Caption text head | | > > +----------------------+ > > +----------------------+ > > # Digits w/o sign | | > > +----------------------+ > > +----------------------+ > > Caption text tail | | > > +----------------------+ > > +--+ > > Is editable | | > > +--+ > > +--------------------+-+ > > Parameter name | |V| Drop-down. > > +--------------------+-+ > > > > > > I pull down the drop-down control, select an item, the drop-down closes > > and - vanishes. All controls have vanished. After half a second or so the > > first one reappears, but w/o its label 'Name'. > > > > The other ones reapper if I click onto the pane where they are supposed to > > be. They also reapper if I change to an other app and then come back > > again. I guess this is because a window update is issued by the OS. > > > > What do I miss? > > I would guess that > > > def _validateNameId_(self, text): > > if Proxy.DataProxy().parameterExists(text): > > return -1 > > return 1 > > is either awfully slow and/or throws an exception. > > You could easily verify this assumption with > > (a) > def _validateNameId_(self, text): > return 1 > > and > (b) > def _validateNameId_(self, text): > try: > if Proxy.DataProxy().parameterExists(text): > return -1 > return 1 > except: # generally a bad idea > print >> sys.stderr, "something went wrong" > return 1 > > > Peter From jim-usenet at jimdabell.com Tue Sep 2 13:04:29 2003 From: jim-usenet at jimdabell.com (Jim Dabell) Date: Tue, 02 Sep 2003 18:04:29 +0100 Subject: python + mplayer References: <9d302332.0309020740.29ee6613@posting.google.com> Message-ID: <a5qdnaoqPt_ZU8miRVn-tA@giganews.com> Mike Zupan wrote: > I'm wondering if anyone has a link or made a script to control mplayer > via python. I'm aware that freevo does it but I don't wanna debug > their code to figure it all out. I'm looking for something very simple > that can get me started in controlling mplayer in a python app. I'd > like to get a movie into a pygame app i'm doing. <URL:http://www.mplayerhq.hu/DOCS/> should have everything you need, specifically <URL:http://www.mplayerhq.hu/DOCS/#slave>. -- Jim Dabell From messageboardfan1 at yahoo.com Thu Sep 25 11:32:12 2003 From: messageboardfan1 at yahoo.com (ataraxia2500) Date: Thu, 25 Sep 2003 17:32:12 +0200 Subject: newbie script References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> <bks61f$3s3$1@newsfeed.eris.qinetiq.com> <3f719ed5$0$14824$79c14f64@nan-newsreader-03.noos.net> <bks7pp$4a8$1@newsfeed.eris.qinetiq.com> <3f72eb7c$0$29964$79c14f64@nan-newsreader-02.noos.net> <bkuvdk$qpf$01$1@news.t-online.com> Message-ID: <3f730a8f$0$23386$79c14f64@nan-newsreader-03.noos.net> Peter Otten wrote: > ataraxia2500 wrote: > >> I get that weird error when I tried to run the little loop, this is what >> it says: >> >> sys:1: DeprecationWarning: Non-ASCII character '\xa0' in file myloop.py >> on line 3, but no encoding declared; see http://www.python.org/peps >> pep-0263.html for details >> File "myloop", line 3 >> os.system('/home/joe/src/myprog/myprog') >> ^ >> SyntaxError: invalid syntax >> >> does it mean anything to you? > > > The whitespace before os.system() consists of '\xa0' characters, no idea > why. > > However, I have noticed that when I copy and paste from KNode 7.2 using > Strg+C/Strg+V instead of the middle mouse button, all '\xa0' are magically > converted back to old '\x20' space characters. > > Peter ok thanx that was the problem, I use knode from CVS and when I did a Ctrl+C it asked me what encoding I wanted, how neat! but I had no idea which one to chose, after two failure I decided to type it by myself and it worked :) From sholden at holdenweb.com Mon Sep 29 19:24:51 2003 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2003 23:24:51 GMT Subject: A startup puzzle References: <vngnif6v8ip4c6@corp.supernews.com> <gandreas-21AC09.14161229092003@news.mpls.visi.com> <vnh8uh5j8e3i44@corp.supernews.com> Message-ID: <7b3eb.1748$603.1208@news2.central.cox.net> "Edward K. Ream" <edreamleo at charter.net> wrote in message news:vnh8uh5j8e3i44 at corp.supernews.com... > > Perhaps using a proxy object...might work: > > Great idea! Some complications: > > 1. Sometimes the test "if not realApp:" causes unbounded recursion. To > avoid any possibility of this happening the startup code just creates the > app object before any code actually uses the app proxies. This is easily > done. > > 2. A __call__ method in the proxy allows the code to use either app().x or > app.x. > > In short, the following pattern appears like it will work in all my modules: > > from leoGlobals import * > app = leoProxy() # leoProxy defined in leoGlobals > # Now the code can reference either app.x or app().x. > > To do this, I use the following code: > > gApp = None # Set before any reference to proxy. > class leoProxy: > def __getattr__(self,attr): > return getattr(gApp,attr) > def __call__(self): > return gApp > > Many thanks for this great idea. > I've followed this thread, and I'm having trouble understanding why nobody's suggested using Alex martelli's "borg" pattern, which he originally called a "statel;ess proxy", where all objects of a given type share the same state information. Sounds to me that's what you really want, no? This would mean that in leo_global you would have something like this: leo_global.py: ------------- class Borg(object): _state = {} def __new__(cls, *p, **k): self = object.__new__(cls, *p, **k) self.__dict__ = cls._state return self module1.py ------------- from leo_global import Borg myborg = Borg() myborg.var1 = "This is var 1" import module2 print "Module 1's borg has var1 =", myborg.var1, id(myborg.var1) print "Module 1's borg has var2 =", myborg.var2, id(myborg.var2) module2.py: ------------- from leo_global import Borg myborg = Borg() myborg.var2 = "This is var 2" print "Module 2's borg has var1 =", myborg.var1, id(myborg.var1) print "Module 2's borg has var2 =", myborg.var2, id(myborg.var2) The result of all this appears to be what you want: a simple way of creating an easily-referenced shared state. Vide: C:\Steve\Projects\Python>python module1.py Module 2's borg has var1 = This is var 1 7766584 Module 2's borg has var2 = This is var 2 8008928 Module 1's borg has var1 = This is var 1 7766584 Module 1's borg has var2 = This is var 2 8008928 regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From python-url at phaseit.net Mon Sep 22 05:07:17 2003 From: python-url at phaseit.net (Raymond Hettinger) Date: Mon, 22 Sep 2003 09:07:17 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 22) Message-ID: <vmteu5ga9mei19@corp.supernews.com> QOTW: "Python seems to encourage and reward incremental effort, and it leads one to explore extensions and improvements to programs because the language makes it relatively easy to see how to do the extensions." -- Ron Stephens "When writing programs in Python, write Python programs" -- Jeff Epler's advice to those forcing themselves to write code using idioms learned in other languages "Oh come on, now, just because Java does it..." -- Dave Benjamin's snappy comeback to Bob Grailer's facetiously offered name for an inverse yield statement called "suck". Discussion ---------- Alex Martelli, Simon Burton, and Richie Hindle unleash their Pythons to crush the latest internet worm: <http://groups.google.com/groups?th=ca04531642584030> <http://groups.google.com/groups?th=ce63bf1338b0ef8a> <http://groups.google.com/groups?selm=mailman.1063988666.28932.python-list at python.org> David Eppstein shows how to use zip to quickly retrieve an arbitrary column in a table stored as a list of lists: <http://groups.google.com/groups?selm=eppstein-87EA1B.13431116092003 at news.service.uci.edu> Rudy Shockaert coaches Bill Blancett on developing a script to send email with attachements using smtplib and the email module: <http://groups.google.com/groups?selm=4fd6e92.0309190518.3b226735 at posting.google.com> Dave Brueck and Skip Montanaro provide expert advice on threadsafe access to global variables: <http://groups.google.com/groups?th=b44a9fcebc90a01d> A dozen pythonistias share real world experience about the relative merits and applicability of Zope, Twisted, Python CGI, Jython, Webware, and Medusa. <http://groups.google.com/groups?th=903e379430bffdfd> Duncan Booth provides a masterfully simple explaination of Python's "global mutex" (the so-called GIL) and its implications for multi-threaded applications. <http://groups.google.com/groups?selm=Xns93FA744C65C2Bduncanrcpcouk at 127.0.0.1> Stefan Franke succinctly demonstrates a fast way to filter sets. <http://groups.google.com/groups?selm=bka5e3%24qito9%241 at ID-105404.news.uni-berlin.de> Along with all its usual benefits, the latest semi-monthly python-dev summary includes interesting personal commentary and traffic analysis from summarizer Brett Cannon. <http://groups.google.com/groups?th=db2820f9a9e1e89f> Bob Findlay offers an on-line course in Python programming: <http://www.icanprogram.com/pythonlinux.html> This week's language change suggestions: * mutable strings * repeat/while control structure for mid-loop termination testing * an inverse yield statement similar to threading.Event.wait() Releases -------- ClientFrom 0.1.8b - module for client side HTML form handling (parsing, filling-in, and returning data to the server). <http://wwwsearch.sourceforge.net/ClientForm/> pyTerra - module for querying Microsoft's TerraServer to download cartographic images. <http://hobu.biz/software/pyTerra> imgSeek 0.8.2 - photo collection manager and viewer <http://imgseek.sourceforge.net/net/> Vision Egg 0.9.9 - high level interface to OpenGL for tapping into the capabilities of graphic cards. <http://www.visionegg.org/> SpamBayes 1.0a6 - source code for the world class spam filter. <http://spambayes.org/download.html> Soprano 0.04 - windows GUI app for querying hosts for information about local groups, users, and other data. <http://sourceforge.net/projects/soprano/> PythonCard 0.7.2 - GUI construction kit for building cross-platform desktop applications on Windows, Mac OS X, and Linux. <http://pythoncard.sourceforge.net/> Twisted 1.0.7 - an event-driven networking framework for server and client applications. <http://www.twistedmatrix.com> XMLFilter 1.1 - provides XML parsing even if the target system lacks a working xml.sax package. <http://www.shearersoftware.com/software/developers/xmlfilter/> ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org 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 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. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From achalk at XXXmagnacartasoftware.com Tue Sep 23 10:28:41 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Tue, 23 Sep 2003 14:28:41 GMT Subject: Executing a python script from an HTML link? Message-ID: <tMYbb.382$zy3.566196578@newssvr11.news.prodigy.com> Is this possible? In my CGI app. I display a web page with a link (anchor). When the link is clicked I want to exectute a python script rather than go to an HTML page. Many thanks. From jjl at pobox.com Thu Sep 11 07:07:43 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Sep 2003 12:07:43 +0100 Subject: Reportlab Image object opens filehandles References: <bjnc2k$2p1bh$1@hades.rz.uni-saarland.de> <3f5f36de$1@news.highway1.com.au> <bjnesm$2qbur$1@hades.rz.uni-saarland.de> Message-ID: <87u17jvb0g.fsf@pobox.com> Michael Schmitt <nomail at nomail.com> writes: > Tim Hoffman wrote: > > > Have a look at limit (or in csh ulimit) > > > > 256 open files is the default limit for a user/process. (all about > > conserving resources) you can make this bigger (much bigger ;-) assuming > > you have permissions. > > > > Rgds > > > Hello Tim. > unfortunately changing this limit is not an option for me. If you can't use a different machine, alter Image so it doesn't open a file until actually necessary. Should be easy. John From tzot at sil-tec.gr Mon Sep 29 18:41:31 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 01:41:31 +0300 Subject: 64-bit EPIC and some modules References: <nsd3nv40ifcur0clp7ful66qohveos0o9r@4ax.com> <m3vfrea6fu.fsf@mira.informatik.hu-berlin.de> Message-ID: <ipchnv4a995l1r55rvkfevk2r4ot8cm4bv@4ax.com> On 27 Sep 2003 12:09:41 +0200, rumours say that martin at v.loewis.de (Martin v. L?wis) might have written: >_tkinter built fine for me, with Python 2.3.1, on a Debian/ia64 >system. If it was not built for you, most likely, you forgot to >install the header files. The header files were there (/usr/lib/tcl), and that is why I managed to compile just by uncommenting the lines in Modules/Setup. I didn't install any -devel packages in the meanwhile. I'll give it a shot again remotely when the machine reaches our client (we must send it tomorrow). >audioop and imageop are not build because of this code in setup.py: > > # Multimedia modules > # These don't work for 64-bit platforms!!! > # These represent audio samples or images as strings: Ah, thank you. Given that they worked fine for me[1] on ia64, I will post a patch tomorrow afternoon which hopefully will be used when more success reports on 64-bit machines come in. [1] the tests ran, and I tried the following on a Windows python, a 32-bit Linux and the ia64 one side-by-side: print audioop.max("hello there!", 2) and I got 29285 in all three of them -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From mwh at python.net Sat Sep 27 09:46:08 2003 From: mwh at python.net (Michael Hudson) Date: Sat, 27 Sep 2003 13:46:08 GMT Subject: Now that rexec is gone... References: <XA8db.597231$o%2.276974@sccrnsc02> Message-ID: <7h33ceinyc8.fsf@pc150.maths.bris.ac.uk> "Rainer Deyke" <rainerd at eldwood.com> writes: > Now that rexec is gone, is there any code or information available on > executing Python in a restricted environment? There was a thread on python-dev about Zope's version of rexec (RestrictedPython?) which looked promising on casual inspection. Cheers, mwh -- > It might get my attention if you'd spin around in your chair, > spoke in tongues, and puked jets of green goblin goo. I can arrange for this. ;-) -- Barry Warsaw & Fred Drake From gh at ghaering.de Tue Sep 9 05:17:18 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 09 Sep 2003 11:17:18 +0200 Subject: set built-in func_code? In-Reply-To: <bjk4v2$6iv$07$1@news.t-online.com> References: <bjk4v2$6iv$07$1@news.t-online.com> Message-ID: <3F5D9A9E.1000305@ghaering.de> Birgit Rahm wrote: > Hello newsgroup, > > I want to set the built-in func_code in my function, how can I does this in > the correct way? I don't think that's possible for an existing function object. Dynamically creating new function objects, however, certainly /is/ possible. > My books dont tell me anything about this. There's almost certainly a better way of achieving what you want. Why don't you tell us what you really want to do, i. e. what is the purpose of this? -- Gerhard From stefnin at alussinan.org Fri Sep 12 07:59:27 2003 From: stefnin at alussinan.org (Stéphane Ninin) Date: 12 Sep 2003 11:59:27 GMT Subject: asyncore question Message-ID: <Xns93F48D6F052CAstefninalussinanorg@213.228.0.75> Hi. I am trying to understand the asyncore module. I read it and found something which seems strange (nb: I am still using Python 2.2.2). I will keep only what seems useful in this post: class dispatcher: # [...] def __init__ (self, sock=None, map=None): if sock: self.set_socket (sock, map) # I think it should inherit this anyway self.socket.setblocking (0) self.connected = 1 # XXX Does the constructor require that the socket passed # be connected? try: self.addr = sock.getpeername() except socket.error: # The addr isn't crucial pass else: self.socket = None def add_channel (self, map=None): #self.log_info ('adding channel %s' % self) if map is None: map=socket_map map [self._fileno] = self def create_socket (self, family, type): self.family_and_type = family, type self.socket = socket.socket (family, type) self.socket.setblocking(0) self._fileno = self.socket.fileno() self.add_channel() My problem is the following: what happens if dispatcher is created with non global map but with no socket, like: d=dispatcher(self,sock=None,map=some_map) then create_socket called: d.create_socket() This dispatcher will be added to the global map. But probably user will call asyncore.loop(map=some_map), as d was buillt with this map. Is there not something wrong here, or am I just missing something ? Regards, -- St?phane Ninin From tim.parkin at pollenationinternet.com Mon Sep 8 10:14:45 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Mon, 8 Sep 2003 15:14:45 +0100 Subject: More Comments on Python Redesign In-Reply-To: <000e01c37612$881089e0$0a00a8c0@JASPER> Message-ID: <000f01c37613$940afc70$0a00a8c0@JASPER> >Hi, >I'm replying off list as, to be honest, I've had enough. :-) Not as off list as I thought I'd replied. From duncan at NOSPAMrcp.co.uk Mon Sep 8 08:24:43 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 8 Sep 2003 12:24:43 +0000 (UTC) Subject: Modifying the {} and [] tokens References: <mtqdkv8sdrmgrn02vugnbpuhtjsgel3ohb@4ax.com> <QfC1b.3575$Ej6.427@newsread4.news.pas.earthlink.net> <pdvdkv8i0j2lfd041bqlgo0d84sv9kjoh4@4ax.com> <ckjekvcm6pf4hhq59ro08p20gk6lf9himp@4ax.com> <bi7rpt$sv9$1@naig.caltech.edu> <km4fkv8qbbge3mvckv5gsim9amq59qvohb@4ax.com> <UlGdnSPexu1eO9qiXTWJkQ@comcast.com> <e6bfkvsnro96db74j8en20tuqm0tml23lr@4ax.com> <oQhU/ks/KXNd089yn@the-wire.com> Message-ID: <Xns93F084E3691FDduncanrcpcouk@127.0.0.1> mwilson at the-wire.com (Mel Wilson) wrote in news:oQhU/ks/KXNd089yn at the- wire.com: > Personally, the applications I've written so far would > like dictionary addition d+u to work like > > for k in u.keys(): > d[k] = d.get (k, additive_identity) + u[k] > > where additive_identity is a magical value that's 0 working > with numbers, [] with lists, () with tuples and '' with > strings. In real life I'd catch the key errors instead. FWIW, Your 'magical value' isn't actually terribly magical, it is easily defined with a few lines of Python: >>> class AdditiveIdentityClass: def __coerce__(self, other): return type(other)(), other >>> additive_identity = AdditiveIdentityClass() >>> additive_identity + 42 42 >>> additive_identity + "urk!" 'urk!' >>> additive_identity + (1,2,3) (1, 2, 3) >>> additive_identity + { 1:0 } Traceback (most recent call last): File "<pyshell#34>", line 1, in ? additive_identity + { 1:0 } TypeError: unsupported operand types for +: 'dict' and 'dict' >>> [ 5 ] + additive_identity [5] >>> 3 - additive_identity 3 -- 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 riquito at riquito.matrix Tue Sep 23 17:09:37 2003 From: riquito at riquito.matrix (Riccardo Attilio Galli) Date: Tue, 23 Sep 2003 23:09:37 +0200 Subject: General Password questions References: <mailman.1064266830.20157.python-list@python.org> <pan.2003.09.23.13.26.53.712668@riquito.matrix> <3F704A91.FA7D31F7@engcorp.com> <pan.2003.09.23.16.02.35.675695@riquito.matrix> <bkpsng$knm$1@panix1.panix.com> Message-ID: <pan.2003.09.23.21.09.35.146080@riquito.matrix> On Tue, 23 Sep 2003 12:34:56 -0400, Aahz wrote: > This is extremely difficult to do in a secure way. What you need to do > is encrypt the e-mail password before storage; each time the user starts > the e-mail application, zie needs to enter the local password. There are > other less secure options, all of which (with some partial exceptions) > equate to "no security" from the perspective of a security professional. > (E.g. relying on the OS to keep the data secure.) > > Python does not make encryption available in its "batteries included" > philosophy because of the legal problems. M2Crypto is probably the > module most often used; see also > http://www.amk.ca/python/code/crypto.html ok, thank you all. curiosity: what is "zie" intended to mean? It is maybe slang for he/she ? Ciao, Riccardo -- -=Riccardo Galli=- _,e. s~ `` ~@. ideralis Programs . ol `**~ http://www.sideralis.net From tzot at sil-tec.gr Mon Sep 29 20:53:00 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 03:53:00 +0300 Subject: Wavelet package available? References: <2ceb70f8.0309290136.118a856d@posting.google.com> <z4adnU-lwpqa1eWiU-KYjA@comcast.com> <bla6kk$mps$1@reader10.wxs.nl> Message-ID: <bjkhnv0lns7j7hfl1jsj0tq2kgk9dpnq66@4ax.com> On Mon, 29 Sep 2003 23:03:44 +0200, rumours say that "gez" <gez_75 at hotmail.com> might have written: >Why this stupid answer? I tried to find python in combination with wavelets, >both in the normal Google search engine and the Google groups search. Also >jpython/jython, etc. but non of the results was what I wanted to use. So, >that is why I posted it here. Think this is exacly the place to be... If Terry's answer was stupid like you say, then you shouldn't continue your paragraph following precisely his suggestion (that is, providing info about your previous efforts to answer your question). Imagine sb telling me to jump off a bridge, me answering "this is stupid!" and then jumping off the bridge... how would you call that? [snip of more info about prior searches] >So, please, think before you write such an answer. Not everybody is as >stupid as you think. Please note that Terry didn't call you stupid, he just hinted how to get more helpful replies. What exactly in his post was so offensive? Note that when he used the phrase 'they should not waste time on' (a subsentence with high offensive-likeness), the object (syntactically speaking) wasn't <you> or <your post> but <possible paths to help answer your question>. [snip] >So please be more kind to the next poster that (in you eyes) posts a stupid >question. IMO Terry *wasn't* unkind towards your post, while IYO he *was*. If you thought he patronized you, you should say so; but he never called you or your post 'stupid'. Please try another approach. Thank you. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From mzupan at meso.com Tue Sep 2 11:40:00 2003 From: mzupan at meso.com (Mike Zupan) Date: 2 Sep 2003 08:40:00 -0700 Subject: python + mplayer Message-ID: <9d302332.0309020740.29ee6613@posting.google.com> I'm wondering if anyone has a link or made a script to control mplayer via python. I'm aware that freevo does it but I don't wanna debug their code to figure it all out. I'm looking for something very simple that can get me started in controlling mplayer in a python app. I'd like to get a movie into a pygame app i'm doing. From bogus at invalid.tld Thu Sep 11 21:14:05 2003 From: bogus at invalid.tld (Jules Dubois) Date: Thu, 11 Sep 2003 19:14:05 -0600 Subject: safari (was Re: Writing solid code book) References: <b15d2792.0309030339.3ac939e7@posting.google.com> <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <elC5b.11632$hE5.410636@news1.tin.it> Message-ID: <c19a00587rpb$.1dbigl3h85ufm$.dlg@40tude.net> On Thu, 04 Sep 2003 08:03:22 GMT, in article <elC5b.11632$hE5.410636 at news1.tin.it>, Alex Martelli wrote: > Jules Dubois wrote: > >> That's the only Python book you think worth having? Or buying? > > Speaking as both the co-editor of the Cookbook and the author of the > Nutshell, if I had to choose ONE Python book "worth having or buying" > I think I'd go for the Nutshell. Hard decision, though. I discovered the Engineering library had ordered _Nutshell_, but it hadn't been delivered from the main library. I requested it and got it the next day. However, seeing for the first time Python's syntax in _Nutshell_ was enough to scare me away. We had to commit today to development in Java or Python. I had made a firm decision to choose Java, even buying a book on the Eclipse IDE. Just before sign-ups, we discovered a sample Tkinter application on the class' internal BBS. After comparing the Tkinter code to the Swing code I've read, I signed up for the Python development team five minutes later. This afternoon, I bought _Cookbook_. When _Nutshell_ is due at the library, I'll buy it too. Thanks for your suggestions. From michaelmossey at yahoo.com Wed Sep 3 23:39:15 2003 From: michaelmossey at yahoo.com (Michael Mossey) Date: 3 Sep 2003 20:39:15 -0700 Subject: installing PyQt References: <9badaf0.0309031219.666fa852@posting.google.com> <ur82xh91k.fsf@fitlinxx.com> Message-ID: <9badaf0.0309031939.43db73ab@posting.google.com> David Bolen <db3l at fitlinxx.com> wrote in message news:<ur82xh91k.fsf at fitlinxx.com>... > michaelmossey at yahoo.com (Michael Mossey) writes: > > > Hi, I'm trying to install PyQt for windows together with > > non-commercial Qt version 2.3.0. When I try to run a sample Qt > > program I get this error: > > > > File "c:/DOCUME~1/mossey/LOCALS~1/Temp/python-1872fAk", line 1, in ? > > from main_qt import * > > File "main_qt.py", line 2, in ? > > from qt import * > > File "C:\PROGRA~1\Python22\lib\site-packages\qt.py", line 17, in ? > > import libsip > > ImportError: DLL load failed: The specified module could not be found. > > > > I'm assuming it can't find libsip.dll. This file is located in the > > directory C:\Program Files\Python22\Lib\site-packages\ and I added > > that directory to both the PYTHONPATH and the PATH. This is windows > > 2000 so I used the system dialog to do it, and then rebooted the > > computer (I don't know if rebooting is necessary). I keep getting the > > same error. I tried copying libsip.dll to the C:\winnt directory and > > it still didn't find it. Can someone familiar with Python on Windows > > 2000 give me a clue here? > > It's hard to believe that it won't find libsip.dll if it's in the > site-packages directory since that's part of your default Python > search path (even without a PYTHONPATH setting). And since libsip is > a direct "import" (and not a system DLL dependency), the search path > that governs things is Pythons (e.g., sys.path, including PYTHONPATH) > and not the Windows system search path (aka PATH). > > But it wouldn't hurt for you to verify sys.path after starting a copy > of Python just to ensure that it has all the directories you expect. > > So if we assume libsip itself is found, the problem could be in > loading it due to another dependency. Do you have the underlying Qt > DLL (I forget the exact name for the non-commercial version) also > somewhere in the system PATH? libsip.dll depends on the Qt DLL, and > if it fails to find it, libsip in turn will fail to load and can > produce precisely the traceback as above. > > Although if it is a failing dependent DLL, in such a case typically > you'll also get a system dialog complaining about not finding the > underlying dependent DLL, but maybe you've just answered that dialog > without reading it closely? (or maybe somehow those dialogs are being > suppressed in your setup) > > Another alternative would be some other dependency - it might be worth > checking if all the dependencies for libsip.dll can be resolved on > your system. A tool like depends (comes with various MS > toolkits/development environments), or cygcheck (if you have cygwin) > or others you can download can check this. > > -- David Hi, thanks very much. Your information was helpful in tracking down the problem, which turned out to be that PyQt was built against Python 2.3 and I was running Python 2.2.2. I'm running Python from Emacs, so I had to do a few more things to get Emacs to recognize a new version of python -- turns out I had to re-byte-compile the python-mode.el file. It all seems to work now. Although you didn't suggest this solution directly, your information allowed me to eliminate things and quickly move toward the right answer. Isn't it neat how that works? -Mike From mpeuser at web.de Fri Sep 5 15:37:20 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 21:37:20 +0200 Subject: OT: best book in years References: <opruzmelopdd8opo@news.vo.lu> <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <bj8el7$12m$07$1@news.t-online.com> <3F5868BA.85F506B4@engcorp.com> Message-ID: <bjaomi$ocq$06$1@news.t-online.com> "Peter Hansen" <peter at engcorp.com> > > ... but I would have been happier to see a bunch of > suggestions for Mr. Useldinger to read, without the negative > comments about others' suggestions. Just doesn't feel right > to me. Call me mildly ticked, is all. > I think you are right! In fact I enjoy all the other suggestions, 20% of which I did not know of before... So I should contribute another clasical book: Hofstadter: Goedel Escher Bach which probably everybody of our age has read but maybe not the younger generation ;-) And it is still entertaining, especially in a hospital... Kindly Michael P From ramen at lackingtalent.com Tue Sep 30 03:44:28 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 30 Sep 2003 07:44:28 -0000 Subject: Fun with fancy slicing Message-ID: <slrnbniddg.ldu.ramen@lackingtalent.com> Hey all, I just realized you can very easily implement a sequence grouping function using Python 2.3's fancy slicing support: def group(values, size): return map(None, *[values[i::size] for i in range(size)]) >>> group(range(20), 4) [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15), (16, 17, 18, 19)] >>> group(range(14), 3) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, None)] I had to use map(None, *...) instead of zip(*...) to transpose the result because zip throws away the "orphans" at the end. Anyway, this is a useful function to have in your toolkit if you need to do pagination or multi-column display, among other things... Anyone have any other interesting applications of the extended slice syntax? Peace, Dave -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From messageboardfan1 at yahoo.com Thu Sep 25 10:30:18 2003 From: messageboardfan1 at yahoo.com (ataraxia2500) Date: Thu, 25 Sep 2003 16:30:18 +0200 Subject: newbie script References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> <bks61f$3s3$1@newsfeed.eris.qinetiq.com> <3f719ed5$0$14824$79c14f64@nan-newsreader-03.noos.net> <bks7pp$4a8$1@newsfeed.eris.qinetiq.com> <3f72eb7c$0$29964$79c14f64@nan-newsreader-02.noos.net> <fBCcb.164855$R32.5292346@news2.tin.it> Message-ID: <3f72fc0d$0$8288$79c14f64@nan-newsreader-01.noos.net> <posted & mailed> Alex Martelli wrote: > ataraxia2500 wrote: > >> hey Ed, >> I get that weird error when I tried to run the little loop, this is what >> it says: >> >> sys:1: DeprecationWarning: Non-ASCII character '\xa0' in file myloop.py >> on line 3, but no encoding declared; see http://www.python.org/peps >> pep-0263.html for details >> File "myloop", line 3 >> os.system('/home/joe/src/myprog/myprog') >> ^ >> SyntaxError: invalid syntax >> >> does it mean anything to you? > > Sure! You have a weird character, of hex code A0, somewhere on your > line 3. How it got there, I dunno. Anyway, what you need to do is > remove it -- a good editor should be able to show you exactly where > it is, otherwise just use a small Python script to find that out. > > > Alex this is my line 3: os.system('/home/joe/src/myprog/myprog') I even tried os.system('ls /') as line 3 and I still sot the same ascii error; From google at elesi.org Wed Sep 10 20:51:17 2003 From: google at elesi.org (neeson) Date: 10 Sep 2003 17:51:17 -0700 Subject: Heisenberg strikes again! References: <a82d9823.0309101254.39f8f05@posting.google.com> <nRM7b.311656$Oz4.100417@rwcrnsc54> Message-ID: <a82d9823.0309101651.7fdbec7e@posting.google.com> Thank you! That answers my questions precisely. :) You can see my c/c++/java biases showing. Expecting global variables to carry into functions and not expecting silent exceptions to alter my execution paths. Valuable lessons! Heath "David C. Fox" <davidcfox at post.harvard.edu> wrote in message news:<nRM7b.311656$Oz4.100417 at rwcrnsc54>... > neeson wrote: > > > Alright, I'm fairly new to Python, and this one has got me stumped. > > I've just started to write a cli program that'll use readline, and > > I've attached the relevant bits. > > > > Here's the mystery: If I so much as /look/ at the list 'matches', > > readline stops working. Run the program, hit tab at the prompt, > > you'll get 'one', which is incorrect, as there are in fact four > > possible completions. Now comment out the line that I've marked > > (which, incidentally, does nothing). /Now/ it works. > > > > Is there some very strange side effect to accessing a list element > > that I'm unaware of? I've tried it in two different versions of > > Python. > > No, but there is a side effect of accessing the first element of an > empty list: namely, Python raises an IndexError exception (i.e. index > out of range). > > > Any elightenment would be appreciated... > > > > Heath > > > > > > import readline > > import sys > > > > commands = ["one", "two", "three", "four"] > > matches = [] > > > > def comp(text, state): > > if state == 0: > > matches = [] > > Because you haven't used > > global matches > > the next statement creates a new list called matches as a variable local > to comp. All your matching commands are added to this variable, which > disappears when comp returns. > > > > n = len(text) > > for cmd in commands: > > if cmd[:n] == text: > > matches.append(cmd) > > > > throwaway = matches[0] # <--- Comment out this line > > When comp is called with state == 0, matches is still referring to the > local list which is not empty (unless there were no matches to the > text), so this line does indeed do nothing. However, when comp is > called with state != 0, this line refers to the global matches list, > which is empty, so it raises an IndexError, and the following line is > not reached. > > Apparently, readline treats an exception in the completer as equivalent > to returning None. In fact, you seem to be relying on this behavior > implicitly in the line below, because you are not checking whether state > < len(commands) > > > return commands[state] > > > > readline.set_completer(comp) > > readline.parse_and_bind("tab: complete") > > David From 2002 at weholt.org Thu Sep 11 18:21:23 2003 From: 2002 at weholt.org (Thomas Weholt) Date: Fri, 12 Sep 2003 00:21:23 +0200 Subject: Web server with Python References: <tnr1mvgnt45urvu6n4q6dso3eto73hfr1m@4ax.com> Message-ID: <sx68b.29387$Hb.450091@news4.e.nsc.no> "Patrick Useldinger" <p.useldinger at myrealbox.com> wrote in message news:tnr1mvgnt45urvu6n4q6dso3eto73hfr1m at 4ax.com... > Hi all, > after my unsuccessful try to run Apache 2 with mod_python and Python > 2.3, I am looking for an alternative approach. > My aim is to write a small web-based application: > > Python > - the solution must be based / usable on Python 2.3 > > Portability > Targeted plaforms are > - Windows 2000 Server > - Windows XP Pro > - AIX 5.1 > > Webserver: > - supporting up to 50 concurrent client connections > - must be able to use Python 2.3 to create dynamic pages > I can think of 3 alternatives to Apache: > - Medusa > - Twisted > - Zope > Which one is the easiest to work with? Which one is known to work on an > AIX 5.1 platform, for instance? I've worked with Zope, Medusa and Twisted. If you can use anything found on www.zope.org under resource and like to do everything in a webpage, not doing much programming yourself, then Zope might be the thing. It covers the python-code a bit much for my taste ( a bit being a huge understatement ). Medusa is easy to work with but I had some problems with blocking and form-handling ( mainly posted files etc. ) but it might have been my lack of understanding back then. Twisted is very easy to get a grip on if you stay away from Woven and use the resource-class yourself. I can produce a very simple example if you like. I find Twisted to have a very steep learning curve in some areas and the project do have a feeling being "under construction", but the developers/mailing-list are very friendly and helpful and glad for input. I haven't done anything on AIX so I don't know anything about portability. I'd go for Twisted if you want control, Zope if you can use any existing "product" available at zope. > > Persistent storage > - Is ZODB easily usable from outside Python, i.e. to produce reports > without reverting to programming? > - Is MySQL with Python a good combination? MySQL is easy to work with using Python, so yes. My experience with ZODB has not been good. I had problems compiling earlier version of it ( probably my fault but still ) and I quickly found out that I needed SQL to be able to store and retrieve data the way I wanted. If MySQL is too much for you take a look at SQLite, it has a python-module and easy to install/distribute and it is a "real" sql-database, ie. it can understand SQL and feels like a SQL-database. Thomas W From martin at v.loewis.de Tue Sep 16 16:12:13 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 16 Sep 2003 22:12:13 +0200 Subject: None, False, True References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> <bk7lq1$qicfh$1@ID-70710.news.uni-berlin.de> <bk7mkg$4s$1@news.peterlink.ru> <FHJ9b.13226$x21.7557@twister.southeast.rr.com> Message-ID: <m3llso4hnm.fsf@mira.informatik.hu-berlin.de> "M-a-S" <NO-MAIL at hotmail.com> writes: > Will it be lower-case (together with false and true) like all other > keywords or is it just a start of mess? It is a start of mess. Actually, None will be the first in a new category of token, the "reserved identifiers". The exact lexical properties of such tokens still need to be determined, and it might be that None is only the second in its category, following "as". Martin From jjl at pobox.com Fri Sep 26 12:11:28 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Sep 2003 17:11:28 +0100 Subject: Python embedded in C & memory releasing References: <63701d2f.0309231819.31fdec85@posting.google.com> <87vfri14a3.fsf@pobox.com> <B9Vcb.171250$R32.5477166@news2.tin.it> Message-ID: <87y8wbbkcv.fsf@pobox.com> Alex Martelli <aleax at aleax.it> writes: > John J. Lee wrote: [...] > > On almost all OSes, processes hold on to all memory that has been > > allocated by the OS. Memory released by a process can only be reused > > *by that same process*. The OS only gets it back when the process > > exits. > > This is not true any more these days!!! Consider the following program: [...] > PID TTY STAT TIME MAJFL TRS DRS RSS %MEM COMMAND > 32606 pts/6 T 0:00 73 1 1330 276 0.0 ./a.out [...] > 32606 pts/6 T 0:00 82 1 2362 320 0.0 ./a.out [...] > 32606 pts/6 T 0:00 82 1 1334 316 0.0 ./a.out [...] Well, you live and learn. :-) John From skip at pobox.com Wed Sep 24 17:57:49 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Sep 2003 16:57:49 -0500 Subject: Python Glossary In-Reply-To: <20030924201127.GA5122@nl.linux.org> References: <16241.53538.40615.455582@montanaro.dyndns.org> <20030924201127.GA5122@nl.linux.org> Message-ID: <16242.4957.967892.67902@montanaro.dyndns.org> Gerrit> Skip Montanaro wrote: >> Thanks to people who submitted content for the Python Glossary: >> >> http://manatee.mojam.com/python-glossary Gerrit> I think it may also be useful to add some terms that are not Gerrit> related to programming, but do occur in the tutorial and may be Gerrit> difficult for some users. Agreed. Gerrit> When I first read the tutorial (years ago), I was really Gerrit> frightened by the section on complex numbers. Yes, complex numbers would be a good addition. There is a note on above Wiki which indicates how to submit a term for which you don't know a definition. Simply enter it as (for example) * complex number - ??? Someone else who comes along can fill in the definition. Gerrit> I would have been helped then by a note that I would not need Gerrit> them, and maybe even a short introduction of what they are Gerrit> (however, I was 14, so I would probably not be able to Gerrit> understand them). You kids... ;-) When I was 14 I don't think I knew what a computer was. We learned how to use slide rules in algebra class. They didn't get any computers at my high school until at least a couple years after I graduated. Skip From raims at dot.com Mon Sep 29 08:48:59 2003 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 29 Sep 2003 14:48:59 +0200 Subject: What's the best MP3 (ID3) access library to use? References: <182bcf76.0309290349.452a6643@posting.google.com> Message-ID: <87ekxzg3pg.fsf@voodoo.fake> paul.moore at atosorigin.com (Paul Moore) writes: > I'm looking for a Python library to access ID3 information in MP3 > files. A search of Parnassus picked up a number of possibilities, but > I can't work out which best suits what I'm trying to do. Some seem out > of date, others are Unix only, etc. There doesn't seem to be an > obvious "standard" module to use. Try this: id3-py.sf.net It should work on Windows but I haven't tested yet -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com rhymes at NOSPAMmyself.com From jjl at pobox.com Tue Sep 2 18:09:42 2003 From: jjl at pobox.com (John J. Lee) Date: 02 Sep 2003 23:09:42 +0100 Subject: Open Source leader? (was Re: Celebrity advice) References: <mailman.1061927168.7845.python-list@python.org> <yra3b.6546$Jh2.2048@newsread4.news.pas.earthlink.net> <23891c90.0308280317.ac68b38@posting.google.com> <Kv-cnVDMbb1qmdOiRTvUqg@speakeasy.net> <biqve2$qp0$1@panix1.panix.com> Message-ID: <87y8x6x2op.fsf@pobox.com> aahz at pythoncraft.com (Aahz) writes: > In article <Kv-cnVDMbb1qmdOiRTvUqg at speakeasy.net>, [...] > OTOH, Perens is also (like me ;-) a self-described asshole. When I saw > him at the Waterside Conference earlier this year, he basically claimed > that only assholes could make significant progress in the Open Source > community. [...] Why? John From losnations at comcast.net Wed Sep 3 22:08:17 2003 From: losnations at comcast.net (Marc) Date: Wed, 3 Sep 2003 21:08:17 -0500 Subject: Drag and drop in Tkinter. How difficult is it? Message-ID: <ApGdnUgAC6p1AMuiU-KYuA@comcast.com> Hi all, I was thinking about developing a drag and drop application and was curious how difficult it is to do. Basically I want to have a set of objects that I move around the screen and drop into place. Anyone else ever done it? Got any tips? Thanks, Marc From uwe.schmitt at procoders.net Tue Sep 16 05:56:45 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 16 Sep 2003 09:56:45 GMT Subject: stripping a string References: <mailman.1063486343.1777.python-list@python.org> Message-ID: <bk6mot$38uia$1@hades.rz.uni-saarland.de> Leeds, Mark <mleeds at mlp.com> wrote: hello : i am very much a python novice because > I only use it for preprocessing data that > i send into another language called Splus. > > I have the following problem that > I have spent a lot of time on but I > can't figure out. > > I have a string called tickerstring > that might be > > "ANL LN32" > > and i want to get rid of the digit piece. > so that i get "ANL LN" > > i can't just take off the last two charcters > because the string could also be > > "ANL LN3" for example. > > thanks to anyone who could explain > how to do this ? > If the numbers only occur at the end of the string: a = "ANL LN32" print a.rstrip("0123456789") Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt http://www.procoders.net schmitt at procoders.net "A service to open source is a service to mankind." From __peter__ at web.de Wed Sep 24 07:00:00 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 24 Sep 2003 13:00:00 +0200 Subject: Pre-PEP: reverse iteration methods References: <HA5cb.185$kD3.168@nwrdny03.gnilink.net> <f4b2nv8vs81v6egonckq7935jmh6a8gku6@4ax.com> <2Udcb.1997$541.708@nwrdny02.gnilink.net> Message-ID: <bkrthm$8db$03$1@news.t-online.com> Raymond Hettinger wrote: > If you want the indices to match their original position, then you > would need something like: > > >>> list(enumerate(mystr).iter_backwards()) > [(2, 'c'), (1, 'b'), (0, 'a')] > > The implementation would need to access both mystr.iterbackwards() > and mystr.__len__(). > > At first glance, this is a can of worms, a pandora's box, > a gordian knot, or some unnamed code smell unsuitable > for this mixed metaphor. You can count down starting at -1 for reverse enumeration and keep that can of pandora's knots closed :-) The only drawback I see would be that the following behaviour might not be what you expect: >>> [(i, c, "uvwxyz"[i]) for i, c in reverse_enumerate("abc")] [(-1, 'c', 'z'), (-2, 'b', 'y'), (-3, 'a', 'x')] >>> Peter From thanks200 at hotmail.com Tue Sep 30 21:16:29 2003 From: thanks200 at hotmail.com (Tom Hanks) Date: 30 Sep 2003 18:16:29 -0700 Subject: where are the "class variables"? References: <62e9c66e.0309301057.65f24a3b@posting.google.com> Message-ID: <6152d0a0.0309301716.38e8d67d@posting.google.com> Access class members... as members of the class! :) class Server(threading.Thread): running = 0 def run(self): Server.running = 1 # note added "Server." while Server.running: # ditto, added "Server." print "do something here..." def exit(self): Server.running = 0 # ditto, added "Server." TTFN, Tom. From fumanchu at amor.org Mon Sep 29 12:45:55 2003 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 29 Sep 2003 09:45:55 -0700 Subject: A startup puzzle Message-ID: <DE1CF2B4FEC4A342BF62B6B2B334601E02F6D8@opus.HQAMOR.amorhq.net> Consider placing initialization code in the __init__.py file for your package? Robert Brewer -----Original Message----- From: Edward K. Ream [mailto:edreamleo at charter.net] Sent: Mon 9/29/2003 9:31 AM To: python-list at python.org Cc: Subject: A startup puzzle I've just about convinced myself there is no good, clean solution to the following puzzle. I wonder if you agree. 1. My app has a module called leoGlobals that contains often-used global functions. All of Leo's source files start with: from leoGlobals import * I don't want to discuss whether this is good style: it is simple and it works well for me :-) 2. All code accesses the singleton application object using the app() method in leoGlobals. 3. To make the code cleaner looking, I would really like the code to be able to access an app global instead of the app() function. This has nothing to do with speed: it's simply that there are lots of references to app() in the code, and there is soon going to be a lot more references to app.gui.x() and app.gui.y() etc. As a workaround, many methods and functions assign a = app(), but I would like to avoid this step. 4. Alas, it does not seem possible to initialize an app global in leoGlobals. The reason is simple: from leoGlobals import * caches the value of app at the time the import is done. But the startup code that creates the app "global" (really an attribute of the leoGlobals module) must do _other_ imports. For example, doing the following at the top of leoGlobals doesn't work: import leoApp app = leoApp.leoApp() # construct the app instance. Indeed, the leoApp module will be imported before the assignment of app. Moreover, the leoApp module does other imports, and all the app variables in those modules will be uninitialized. It would be horrible style to place detailed constraints on the order in which modules get imported, and I'm not sure even that would work. Any ideas for a clean solution? Thanks. Edward P.S. The solution must work in 2.1, 2.2 and 2.3. EKR -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- -- http://mail.python.org/mailman/listinfo/python-list From jjl at pobox.com Tue Sep 16 15:11:56 2003 From: jjl at pobox.com (John J. Lee) Date: 16 Sep 2003 20:11:56 +0100 Subject: Pipe problem References: <9GH8b.2074$Cu3.689@edtnps84> <slrnbme3tq.err.hat@se-126.se.wtb.tue.nl> Message-ID: <87y8wownsz.fsf@pobox.com> Albert Hofkamp <hat at se-126.se.wtb.tue.nl> writes: > On Sat, 13 Sep 2003 16:34:13 GMT, Doug <no.email.you.must.phone.me at fu.bar.ws> wrote: > > This works with a small string, but not a large one (read returns an > > empty string if i pass a large html file to tidy): > > > > > > >>> iin , iiout = popen2("tidy.exe -asxml") > > >>> iin.write(str) > > >>> iin.close() > > >>> iiout.read() [...] Didn't see the OP, but (guessing tidy.exe is HTMLTidy): do you know about mxTidy and uTidylib? John From joonas.paalasmaa at iki.fi Fri Sep 5 17:16:16 2003 From: joonas.paalasmaa at iki.fi (Joonas Paalasmaa) Date: 5 Sep 2003 14:16:16 -0700 Subject: _imp__* linking errors when compiling extension using Mingw Message-ID: <1a50a43.0309051316.51f3fc72@posting.google.com> Hi, When compiling Sketch's streamfilter C extension the errors below are raised during linking. What could cause the errors? (Python 2.3, MinGw 1.1 with GCC 2.95.3-6, Windows 98) Here are the occurrences of FilterType that may be relevant: ------- C:\sketch\sketch-0.7.12\Filter\filterobj.c: 949: PyTypeObject FilterType = { C:\sketch\sketch-0.7.12\Filter\filterobj.h: 89: extern DL_IMPORT(PyTypeObject) FilterType; ------- setup.py contents: ------- from distutils.core import setup, Extension filter_dir = "Filter/" setup(name = "sketch", ext_modules=[ Extension("streamfilter", [filter_dir+filename for filename in ("streamfilter.c", "filterobj.c", "linefilter.c", "subfilefilter.c", "base64filter.c","nullfilter.c", "stringfilter.c", "binfile.c", "hexfilter.c")])]) ------- Linking errors: ------- running build running build_ext building 'streamfilter' extension creating build creating build\temp.win32-2.3 creating build\temp.win32-2.3\Release creating build\temp.win32-2.3\Release\filter C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/linefilter.c -o build\temp.win32-2.3\Release\filter\linefilter.o C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/filterobj.c -o build\temp.win32-2.3\Release\filter\filterobj.o C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/nullfilter.c -o build\temp.win32-2.3\Release\filter\nullfilter.o C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/hexfilter.c -o build\temp.win32-2.3\Release\filter\hexfilter.o C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/streamfilter.c -o build\temp.win32-2.3\Release\filter\streamfilter.o C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/binfile.c -o build\temp.win32-2.3\Release\filter\binfile.o C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/base64filter.c -o build\temp.win32-2.3\Release\filter\base64filter.o C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/stringfilter.c -o build\temp.win32-2.3\Release\filter\stringfilter.o C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\PYTHON\include -IC:\PYTHON\PC -c Filter/subfilefilter.c -o build\temp.win32-2.3\Release\filter\subfilefilter.o writing build\temp.win32-2.3\Release\filter\streamfilter.def creating build\lib.win32-2.3 C:\MINGW\BIN\gcc.exe -mno-cygwin -mdll -static -s build\temp.win32-2.3\Release\filter\streamfilter.o build\temp.win32-2.3\Release\filter\filterobj.o build\temp.win32-2.3\Release\filter\linefilter.o build\temp.win32-2.3\Release\filter\subfilefilter.o build\temp.win32-2.3\Release\filter\base64filter.o build\temp.win32-2.3\Release\filter\nullfilter.o build\temp.win32-2.3\Release\filter\stringfilter.o build\temp.win32-2.3\Release\filter\binfile.o build\temp.win32-2.3\Release\filter\hexfilter.o build\temp.win32-2.3\Release\filter\streamfilter.def -LC:\PYTHON\libs -LC:\PYTHON\PCBuild -lpython23 -o build\lib.win32-2.3\streamfilter.pyd build\temp.win32-2.3\Release\filter\streamfilter.o(.text+0xda):streamfilter.c: undefined reference to `_imp__FilterType' build\temp.win32-2.3\Release\filter\filterobj.o(.text+0xdf):filterobj.c: undefined reference to `_imp__FilterType' build\temp.win32-2.3\Release\filter\filterobj.o(.text+0x21e):filterobj.c: undefined reference to `_imp__FilterType' build\temp.win32-2.3\Release\filter\filterobj.o(.text+0x534):filterobj.c: undefined reference to `_imp__FilterType' build\temp.win32-2.3\Release\filter\filterobj.o(.text+0x604):filterobj.c: undefined reference to `_imp__FilterType' build\temp.win32-2.3\Release\filter\filterobj.o(.text+0x64e):filterobj.c: more undefined references to `_imp__FilterType' follow error: command 'gcc' failed with exit status 1 ------- From FBatista at uniFON.com.ar Thu Sep 18 10:15:12 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 18 Sep 2003 11:15:12 -0300 Subject: Money data type Message-ID: <A128D751272CD411BC9200508BC2194D03382F9A@escpl.tcp.com.ar> #- One should be very wary of using floating point arithmetic #- when dealing #- with money. Engaged in a discussion with Andy Jewell, I couldn't prove him why! Do you know why? Have an example? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20030918/a3c2d241/attachment.html> From anton at vredegoor.doge.nl Tue Sep 16 07:05:14 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Tue, 16 Sep 2003 13:05:14 +0200 Subject: safari References: <b15d2792.0309030339.3ac939e7@posting.google.com> <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <elC5b.11632$hE5.410636@news1.tin.it> <51809ae4.0309040634.7999e400@posting.google.com> <L%06b.18004$hE5.637245@news1.tin.it> <51809ae4.0309110734.1e5d28be@posting.google.com> <87y8wvfd6d.fsf@pobox.com> <RXLY/kKkXU4e092yn@gnosis.cx> <mailman.1063303282.4058.python-list@python.org> <bjt1eq$dui$0@216.39.172.122> Message-ID: <bk6qst$s0v$1@news.hccnet.nl> bokr at oz.net (Bengt Richter) wrote: <$87 bn> >Just trying to get a concept of what these numbers >mean. Or could have meant. See also: http://villagevoice.com/issues/0337/baard.php Anton From __peter__ at web.de Sat Sep 27 11:25:45 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 27 Sep 2003 17:25:45 +0200 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> <IKScnUNBOsX4MumiU-KYgA@comcast.com> <bqeanvgel9ra3va44j090bmn2l126t340g@4ax.com> <10c662fe.0309270545.1fd5d839@posting.google.com> Message-ID: <bl4a8b$7ud$01$1@news.t-online.com> Roberto A. F. De Almeida wrote: > The problem with b[:-1][:-1] is that it will return b[:-1], and then > slice the result again. It's ok if you're working with lists, but not > for what I'm doing. > > I'm working in a client to access OPeNDAP servers. It's basically data > served through http, with some metadata and the ability to specify the > variables and ranges you want. [...] > Data is only retrieved when you slice a variable like above, and only > the data sliced is requested from the OPeNDAP server, instead of the > whole range. If I use multiple slices, eg, > >>>> A = data.variables["A"][1:10][1:5][6] > > then first the client will have to download A[1:10][:][:], and slice > it later -- more data than needed will be retrieved. If instead I pass > a tuple of slices, I can construct the URL > > http://server/cgi-bin/opendap/dataset.nc.dods?A[1:10][1:5][6] > > and request from the server only the data that will be used, and > return it as a Numeric array. > > Roberto Have you thought about a proxy class on the client side? It can defer the actual server access until it has the slice/index information for all dimensions: <code> class Proxy: def __init__(self, dims, slices=None): if slices == None: self.slices = [] else: self.slices = slices[:] self.dims = dims def fetchData(self, index): return "fetching data: " + str(self.slices + [index]) def __len__(self): return self.dims[0] def __getitem__(self, index): if len(self.dims) == 1: return self.fetchData(index) return Proxy(self.dims[1:], self.slices + [index]) def __str__(self): return "data access deferred" p = Proxy([10, 42, 9]) print p[:4] print p[:-1][:-2][:-3] print p[1][-2][:-3] q = Proxy([0]*3) print q[:4] print q[:-1][:-2][:-3] print q[1][-2][:-3] </code> If I have understood you right, the above should be a workable solution. If you do not know the nested arrays' lengths beforehand, you could implement __len__() to always return 0, which saves you from an AttributeError for negative indices. Peter From achrist at easystreet.com Wed Sep 10 17:39:14 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Wed, 10 Sep 2003 14:39:14 -0700 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> <3F5F82A5.7DB9A717@alcyone.com> Message-ID: <3F5F9A02.D1A5ACAA@easystreet.com> Erik Max Francis wrote: > > > Yep: > > generator.next() > This style supports only output-driven processes. The generator, being on the input side, is always the server, and the output side is always the client. It doesn't fit the situation where the input is heterogeneous and input has to get spewed in several directions, depending on its content. Al From falseaddy at here.org Fri Sep 19 18:04:15 2003 From: falseaddy at here.org (Dfenestr8) Date: Sat, 20 Sep 2003 07:04:15 +0900 Subject: Mandrake Linux 9: Why isn't bsddb working? References: <bka45f$q6rg1$1@ID-119882.news.uni-berlin.de> <mailman.1063820907.15026.python-list@python.org> <bkb385$r8u2n$1@ID-119882.news.uni-berlin.de> <mailman.1063895247.17694.python-list@python.org> Message-ID: <bkfug2$1dovr$1@ID-119882.news.uni-berlin.de> On Thu, 18 Sep 2003 09:26:49 +0000, Skip Montanaro wrote: > > >> What might I have done wrong, and/or what should I do to fix it? > > Skip> You probably don't have the necessary -devel RPM installed. > > >> That might have been true while I was using the rpm package. > > >> But currently I'm using the source package Python-2.3.tgz. > > Doesn't matter. The _bsddb module can't be built if the relevant header > files and libraries are not in place. > > Skip The rpm -devel package just won't install unless it detects I have python itself installed as an rpm. And I kind of like the version of IDLE that comes with Python 2.3, so I'd rather keep it. (Also, I'm not completely sure how to uninstall it. "make uninstall" doesn't work). So is there no way I can get the correct header files from source? From sami.viitanen at pp6.inet.fi Mon Sep 29 12:10:06 2003 From: sami.viitanen at pp6.inet.fi (Sami Viitanen) Date: Mon, 29 Sep 2003 16:10:06 GMT Subject: Python os.popen in Linux Message-ID: <yPYdb.369$2r2.112@read3.inet.fi> Hello, I was using os.popen function to get CVS command output to string from script.. Same commands worked well with Windows, but Linux seems to have problem with those. Whole CVS commands seem to froze or given commands aren't executed right at all. I had to replace os.popen commands with os.system. os.system commands just print additional information to screen that is not necessary at all. Any ideas what may cause this ? Example of "os.popens" that were not executed correctly: # Freezes files one at the time def sfnFreezeFiles(sModFiles,sTagOld): lModFiles = string.split(sModFiles) # Makes list out of string x = 0 while x < len(lModFiles): # While files in list iFilePoint = string.rfind(lModFiles[x],'/',1) # Seeks last '/' -char from string sModFile = lModFiles[x] sDir = sModFile[:iFilePoint] # Directory = from start to last '/' sModFile = sModFile[iFilePoint+1:] # File = from last '/' to end of string ColorPrint.fnPrintExecute('Freezing: %s %s' % (sDir,sModFile)) sCurrentDir = os.getcwd() # Get current working directory os.chdir(sDir) # Change directory os.popen('cvs update -A %s' % sModFile) # Remove sticky-tag from file <----- OS.POPEN os.popen('cvs ci '+sModFile) # Checkin file <----- OS.POPEN os.chdir(sCurrentDir) # Change directory back x = x+1 return len(lModFiles) Thanks in advance. --SV From sholden at holdenweb.com Tue Sep 16 08:07:49 2003 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 16 Sep 2003 12:07:49 GMT Subject: wanted($): mac and linux python gui coders for porting References: <EHr9b.36540$n94.18214@fed1read04> Message-ID: <p2D9b.11602$3Y2.8940@news2.central.cox.net> Oops, you said "shareware". Guess the SourceForge route wouldn't be for you, then. Sorry! regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ "Mark Hahn" <mark at hahnca.com> wrote in message news:EHr9b.36540$n94.18214 at fed1read04... > (I apologize in advance if this is not an appropriate posting) > > I have written a simple windows shareware app, EzPicMailer, in Python 2.3, > wxPython 2.4.1, and PIL 1.1.4 that lets computer novices find photo files, > edit them, and mail them, all in one simple app. Everyone is encouraged to > check out my beta version at http://EzPicMailer.com. > > I wrote it to be cross-platform except for a small amout of windows code to > do the system beep and to find the desktop and home folders. > > Now I need a Mac programmer and a Linux programmer to port to these > environments for me. I'm new to shareware but I'm guessing that paying 10% > of gross license receipts would be fair. I put in close to 200 hours into > the app and I'm assuming that 20 hours to do a decent looking port would be > about right, which gives 10% of the effort. Let me know if I'm off-base > here. > > You will also be responsible for a second line of support for your platform. > In other words you will need to fix problems particular to your platform to > keep your royalty flow. You will not have to talk to customers though. > That is what I mean by second-line. > > If you are interested, please tell me about yourself and point me to some of > your existing work with GUI's. > > > From duncan at NOSPAMrcp.co.uk Fri Sep 12 05:24:48 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 12 Sep 2003 09:24:48 +0000 (UTC) Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <mailman.1063300996.11325.python-list@python.org> Message-ID: <Xns93F4693C38142duncanrcpcouk@127.0.0.1> Michael Chermside <mcherm at mcherm.com> wrote in news:mailman.1063300996.11325.python-list at python.org: > I started by looking for use cases... where would this proposed > pass-by-reference actually prove useful? Stephen basically found > one good use case: > > I wish to "transfer ownership" of an object that gets passed > into a method call, and protect against the caller accidently > continuing to use the object. [So, we'll use a "ref" parameter and > set the caller's variable to None.] That only works if the caller hasn't assigned that object to any other variables. If they have, they can still accidentally continue to use the object. Since you have to trust the caller anyway, why not trust them to stop using the object? -- 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 jjl at pobox.com Sun Sep 7 18:45:38 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Sep 2003 23:45:38 +0100 Subject: Comments on Python Redesign References: <mailman.1062934990.9290.python-list@python.org> <3F5B362F.B5CCC6F2@engcorp.com> Message-ID: <87wucki5f1.fsf@pobox.com> Peter Hansen <peter at engcorp.com> writes: > Tim Parkin wrote: > > > > As a side note, I haven't been to any school of 'control the user > > experience'. Furthermore I think making comments such as accusing me of > > having a 'childish ego' and being 'arrogant' are IMO extremely > > disrespectful and I would appreciate an apology. I am quite hurt and > > dissapointed to see such coments on what I had considered a respectable > > forum for discussion although I'm sure they are not representative. > > On behalf of those with the nasty fingers today, I apologize. Tim, > they must have missed the relatively clear warnings that these > are *mockups*, and posted for discussion purposes. I agree also > that harsh public criticism without constructive comments is > wholly unwarranted, and out of order around here, not to mention > (thankfully) rather atypical. [...] Me too. Haven't followed the discussion closely or looked at the mockup, but some of the responses looked way over the top. I hope this doesn't stop you continuing with your efforts, Tim. Some people here do appreciate the work you're putting in. John From zzuvz at aon.at Tue Sep 9 05:38:13 2003 From: zzuvz at aon.at (daniel) Date: Tue, 09 Sep 2003 11:38:13 +0200 Subject: GUI Message-ID: <3f5d9fad$0$31720$91cee783@newsreader01.highway.telekom.at> hello, I'm new to python but I known other languages like ruby or php... I've found a tiny script in the net with throws an error, that the modules 'GUI' is not known - in this line 'import GUI, struct' In the net I haven't found a GUI module - where I can get it? daniel From brucedickey at micron.com Mon Sep 29 13:17:55 2003 From: brucedickey at micron.com (Bruce Dickey) Date: Mon, 29 Sep 2003 11:17:55 -0600 Subject: Meta programming question References: <vnce64dgqj047c@corp.supernews.com> <znzdb.132998$hE5.4530954@news1.tin.it> Message-ID: <bl9pg2$5f7$1@admin-svc.micron.com> "Alex Martelli" <aleax at aleax.it> wrote in message news:znzdb.132998$hE5.4530954 at news1.tin.it... > Bruce Dickey wrote: > > > I've read a number of the meta progamming articles. I have not found > > what I am looking for. I want to override assignments to variables which > > are in the module namespace (not object members -- no classes involved). > > Can this be done? > > No (not without, as somebody already suggested, rewriting substantial > portions of Python's C-level implementation). A module-level statement > > <name> = <expression> > > evaluates the expression, and sets the name to refer to its value -- no > ifs, no buts, no overriding, and nothing to do with metaprogramming. > > > Alex > I think the path of least resistance is to preprocess a (non-Python) grammar language. My OP was a shot in the dark. Thanks, Bruce From ken at perfect-image.com Wed Sep 17 23:37:34 2003 From: ken at perfect-image.com (Ken Godee) Date: Wed, 17 Sep 2003 20:37:34 -0700 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) In-Reply-To: <6ee58e07.0309171548.314a046c@posting.google.com> References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <mailman.1063810287.4212.python-list@python.org> <6ee58e07.0309171548.314a046c@posting.google.com> Message-ID: <3F69287E.7080306@perfect-image.com> Lothar Scholz wrote: > Ken Godee <ken at perfect-image.com> wrote in message news:<mailman.1063810287.4212.python-list at python.org>... > > >>I downloaded the demo and as far as I can tell it's fully fuctional >>Here's a quote from the opening screen...... > > > and heres a quote from the web site. > > ------------ > A demonstration version of BlackAdder can be downloaded at no charge. > The demonstration version has the following limitations. > You cannot save any changes to Python or Ruby scripts or GUI form > designs. > > There is no HTML documentation. > > There is no Python Qt extension module. You can download this for > yourself from the PyQt/PyKDE homepage. > > There is no ODBC connectivity. You can download this for yourself from > http://www.lemburg.com/files/python/eGenix-mx-Extensions.html. > ---- > > i hope that there support for the program is better then the support > for their website. Everything in the last weeks doesn't look very > promising. I downloaded it all right from there site, Qt<->python converted html docs as well (except ODBC, on win32 I use pyscopg). Know matter how you look at it, This is a GREAT DEAL, just for the Qt/pyqt license issue's alone! The kompany has put together a good deal with Trolltech and riverbank for python users. $79 personal and $399 commercial with rights to distribute the run-time elements. I guess one could stick with straight c++ and pay trolltech $2,000 plus per developer instead if you wanted to :) (opps, for win32 platform development might want to spend another grand+ to compile with MS VC++ compiler) From ajsiegel at optonline.net Wed Sep 3 08:42:27 2003 From: ajsiegel at optonline.net (Arthur) Date: Wed, 03 Sep 2003 08:42:27 -0400 Subject: artifical intelligence Message-ID: <000501c37218$d59b9270$0c02a8c0@Arts> Alex writes - >The single line of text following this one is >one of the longest I've >ever seen posted to Usenet - my compliments. Yeah. That seems to happen when I send from my on-line mailbaox, rahter than from my desktop. Annoying. No idea why. >Actually, I stick with our line from back in >the '80s, when I was doing >speech recognition with IBM Research on a >strictly probabilistic basis: >what we had on our T-shirts was >P(A|B) = P(B|A)P(A)/P(B) >and you know, there IS really nothing more to >it than this formula from >1764... almost;-). And, it IS easy to program, >if programmers were in >fact humble enough to study and apply >statistics and probability rather >than looking for "artificial intelligence" >silver bullets!-) I guess what I am obliquely addressing - as a dilletante, of course - is the ultimate claims of the potential of AI. AI is ultimately artificial not in that it artificially mimics intelligence - but that it does so within the confines of an artifically defined reality. Though it can certainly be useful, as such. I don't believe, though, that AI can ever deal adequately with the reality of reality - the universe of *all* possibilities. On the question of risk assessment, specifically. Its not a matter of processing power, or programming intelligance. Ultimately, there is an unavoidable Nan that can't be overcome. Risk assessment in respect to the universe of all possiblities *is* the survival instinct. It's truly Frankensteinish to believe it can be mimiced. IMO. Art From peter at engcorp.com Fri Sep 26 10:59:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 26 Sep 2003 10:59:59 -0400 Subject: PEPs link gone from the Python homepage? References: <un0crhase.fsf@boost-consulting.com> Message-ID: <3F74546F.AF665B35@engcorp.com> David Abrahams wrote: > > Since a significant part of Python is only documented in PEPs, I am > disappointed to see that they can't be easily found. Where are they? Why on the the Documentation page, of course. ;-) -Peter From sross at connectmail.carleton.ca Fri Sep 26 11:03:12 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 26 Sep 2003 11:03:12 -0400 Subject: PEPs link gone from the Python homepage? References: <un0crhase.fsf@boost-consulting.com> Message-ID: <wxYcb.12372$yD1.1504223@news20.bellglobal.com> "David Abrahams" <dave at boost-consulting.com> wrote in message news:un0crhase.fsf at boost-consulting.com... > > Since a significant part of Python is only documented in PEPs, I am > disappointed to see that they can't be easily found. Where are they? > > -- > Dave Abrahams > Boost Consulting > www.boost-consulting.com Hi. They're at http://www.python.org/peps/. They are found by following the "Documentation" link (top right of main page), and then clicking the PEPs link at the bottom of that page. (Having a link to http://www.python.org/doc/, the general Python documentation page, in the Documentation section on the left of the main page would be repetitive, but I think it would be useful. I don't really notice the links at the top of the page. The only reason I found them is because I was trying to figure out how someone is meant to navigate to the PEPs page, so I looked over the entire page carefully. Normally, I just look at the sections on the left side of the main page for navigation purposes.) HTH Sean From peter at engcorp.com Mon Sep 22 19:11:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Sep 2003 19:11:14 -0400 Subject: Memory allocation References: <mailman.1064263836.31956.python-list@python.org> Message-ID: <3F6F8192.450A9D6C@engcorp.com> "Batista, Facundo" wrote: > > #- Knowing how much memory the object consumes will not help you with > #- that, at least in general. The object could easily be changed in a > #- dozen ways yet still consume the same amount of memory. > > No, sorry. Knowing how much memory consumes, gives me if it's a viable > solution. Hmm... you mean the memory consumption had nothing to do with detecting the change? You just want to know if holding the pickled object in memory is viable? If that's what you mean, I must be missing something... a pickle is just a serialized (i.e. flat) representation of the data as a series of bytes, right? In other words, a string? So call len() on it... (as I said, that sounds too easy so I must be missing something). > But, there is a way to know the memory consumption? Not really, although I suspect there have been past postings to the newsgroup (maybe check the archives) in which people have experimented with partial solutions to this problem. It's not generally something that seems to come up very often. -Peter From alisonken1 at juno.com Tue Sep 16 16:46:49 2003 From: alisonken1 at juno.com (Ken Roberts) Date: 16 Sep 2003 13:46:49 -0700 Subject: from clipper move to python References: <mailman.1063605800.2328.python-list@python.org> Message-ID: <c26362ae.0309161246.30596c72@posting.google.com> ads <ads at chead.org> wrote in message news:<mailman.1063605800.2328.python-list at python.org>... > Hi Everyone, > > I'm starting learning python about 2 weeks, and still have > difficulties to create GUI based application because I never learn > about classes and other OOP things. Does anyone knows how to > create text console application like clipper using python. > > Thanks, For those who ask - clipper is a programming language that is a compiled version of dBase relational database scripting language. From anton at vredegoor.doge.nl Sat Sep 20 10:15:45 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 20 Sep 2003 16:15:45 +0200 Subject: Problems with string and lists (searching and replaceing) References: <pan.2003.09.20.10.51.37.875000@hotmail.com> Message-ID: <bkhnpn$hgc$1@news.hccnet.nl> jblazi <jblazi at hotmail.com> wrote: >I should like to search certain characters in a string and when they are >found, I want to replace other characters in other strings that are at >the same position (for a very simply mastermind game) for my pupils. > >This very simple thing does not seem simple at all. > >If I use strings, I cannot replace their parts (though I can use >string.find for the searching). I think it is a bad idea that strings are >not mutable, but I suspect that this has been discussed here for ages. > >I can use sequences instead, but then first I have to 'split' and 'join'. >Additionally, there is no 'find' for sequences (who knows why not) and so >I can choose between using 'index' that raises an exception (and we have >not covered exceptions yet) or I can ask whether the character is in the >string before using 'index' which is a bit artificial from the point of >view of my pupils. (It is all right with me.) > >Do I oversee something? Yes, UserString. The documentation is a bit sparse, but reading the module itself provides additional information. Below is a quick test script. HTH, Anton from UserString import MutableString def test(): s = MutableString("helo world") print s x = 'helo' y = 'hello' i = s.find(x) s[i:i+len(x)] = y print s if __name__=='__main__': test() #output: #helo world #hello world From andy47 at halfcooked.com Fri Sep 5 11:09:27 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Fri, 05 Sep 2003 16:09:27 +0100 Subject: in Ram database? In-Reply-To: <vlh7sqn1t375ff@news.supernews.com> References: <mailman.1062728122.8678.python-list@python.org> <vlh7sqn1t375ff@news.supernews.com> Message-ID: <bja94e$fr6$1@sea.gmane.org> John Roth wrote: > "John D." <lists at webcrunchers.com> wrote in message > news:mailman.1062728122.8678.python-list at python.org... > >>Does anyone know if there is an "in-ram" dictionary based database >>for Python. >> >>I can see some applications where this can really be powerful in >>applications requiring 10,000 records or less. >> >>Is such a database available? If so, who is working on it, >>or where is it? >> >>I've heard that Python supports a stand-alone database. I looked >>for it in the Docs, and see the "dbm" module. I haven't found >>any examples of code, so don't know how to use them. I'm one >>of those guys that learn through examples, and have very little >>luck in figuring out how to use anything unless I can see examples >>of their use. >> >>My idea is that ALL datums would be Python Dictionary objects, so >>not only can you store data, but python objects as well. >> >>Storage to disk would be through pickled files, or through CSV >>format, allowing easy import and export from other databases. >> >>I'm sure something like this exists, I just haven't found it yet, >>and if not, then I'm well on my way of implementing one myself. >> >>I kinda like the idea of being able to define smaller tables as >>"in-memory" types, and the really large massive ones in other forms >>managed by mySQL, PostGres, or bsddb3 databases. >> >>Any leads you guys??? > > > Look at Prevalyar. While it's a Java project, it might give > you some ideas about what's possible if you forget "data base" > and simply think "persistance." > > John Roth > >>JD >> Or you could look at the Python port of Prevayler (well, thats how it started out); http://www.orbtech.com/wiki/PyPerSyst Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From newsgroups at jhrothjr.com Tue Sep 16 16:40:03 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 16 Sep 2003 16:40:03 -0400 Subject: None, False, True References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> <3f675ecd$0$97184$edfadb0f@dread12.news.tele.dk> <5MJ9b.13244$x21.9088@twister.southeast.rr.com> Message-ID: <vmet8r7on91u72@news.supernews.com> "M-a-S" <NO-MAIL at hotmail.com> wrote in message news:5MJ9b.13244$x21.9088 at twister.southeast.rr.com... > > "Max M" <maxm at mxm.dk> wrote in message news:3f675ecd$0$97184$edfadb0f at dread12.news.tele.dk... > > > > Yes. You assign new values to the objects None, False and True. You then > > print out those values in a tuple. > > > > What's not to understand? > > > > But for others reading your programme you might be better of to keep > > them their normal values. > > Which are ...? > > I mean what are None, False and True? Are they just identifiers? Are they > variables defined in __builtins__? Are they literals? Are they language "bricks" > like "for" and "1"? As of 2.3, they are unique objects in the builtins name space. As such, they can be shadowed, which is what causes the confusion. John Roth > > From jjl at pobox.com Thu Sep 11 18:44:11 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Sep 2003 23:44:11 +0100 Subject: safari References: <b15d2792.0309030339.3ac939e7@posting.google.com> <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <elC5b.11632$hE5.410636@news1.tin.it> <51809ae4.0309040634.7999e400@posting.google.com> <L%06b.18004$hE5.637245@news1.tin.it> <51809ae4.0309110734.1e5d28be@posting.google.com> <87y8wvfd6d.fsf@pobox.com> <RXLY/kKkXU4e092yn@gnosis.cx> <mailman.1063303282.4058.python-list@python.org> Message-ID: <871xun6j44.fsf@pobox.com> mertz at gnosis.cx (David Mertz) writes: > jjl at pobox.com (John J. Lee) wrote previously: > |Pearson and O'Reilly owned by a single company, or something? I have > |a vague recollection that Pearson owns some other companies... > > There's been a huge amount of consolidation in publishing. Pearson is > not the parent of Addison-Wesley, Longman, Benjamin Cumming, New Riders, > Peachpit, Cisco Press, Prentice Hall, SAMS, Que, and several more > imprints. It's really a rather bad thing, (That should have been "now the parent...", I assume.) Wow. :-( Actually, doesn't Pearson own some stuff outside of publishing too? That's what ISTR hearing about recently... > although they do not seem to > use the degree of ideological acid-test that, say, MediaCorp > acquisitions do. What are you referring to there? Is Mediacorp Rupert's company? What's this about ideological acid-tests? > That said, I'm pretty sure that O'Reilly remains one of the few > independent publishers of technical books. I think Manning is also. By technical books, do you mean computing books? I've no idea what goes on with other fields, but I don't doubt they've been 'consolidating' too (and, of course, AW, Longman, Prentice Hall themselves publish(ed) a broad range). So, *is* Pearson's 'Safari' the same as O'Reilly's? I thought Alex had mentioned Pearson in that connection. Too lazy to check. John From tim.parkin at pollenationinternet.com Sun Sep 7 17:07:31 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 22:07:31 +0100 Subject: Comments on Python Redesign In-Reply-To: <bjg2ea$cvp$1@panix3.panix.com> Message-ID: <003001c37584$13c36050$0a00a8c0@JASPER> Aahz: > Don't worry -- some people think that's redundant, but Guido has > Prounounced that it will stay. Perhaps Guido or yourself could inform us of any other requirements. As far as I am aware this was never mentioned to anyone working on the design effort. Tim From daniel at dittmar.net Tue Sep 30 15:01:59 2003 From: daniel at dittmar.net (Daniel Dittmar) Date: Tue, 30 Sep 2003 21:01:59 +0200 Subject: Python Windows Source? In-Reply-To: <924a9f9c.0309300954.29b155d@posting.google.com> References: <924a9f9c.0309300954.29b155d@posting.google.com> Message-ID: <blcjvb$dio$1@news.eusc.inter.net> Paradox wrote: > This seems like a simple question but I keep looking and can't seem to > find it anywhere. Do I have to check it out directly from CVS. Is > there anywhere I can download the source already compiled. All I > really want is to be able to compile PIL. If you want to compile an extension like PIL on Windows, then everything needed is part of the normal installer. Assuming you installed Python to c:\Python23, then you'll need the include files at c:\Python23\include and the import library at c:\Python23\libs\python23.lib. Daniel From xnews at fredp.lautre.net Sun Sep 21 16:41:15 2003 From: xnews at fredp.lautre.net (Fred Pacquier) Date: 21 Sep 2003 20:41:15 GMT Subject: Anyone has "pyuploader.zip" from Parnassus ? References: <mailman.1064159370.7298.python-list@python.org> Message-ID: <Xns93FDE737AF5E8PaCmAnRDLM@213.228.0.75> eltronic at juno.com said : > yeh wayback! they don't always archive archives, > maybe only if they are small enough. its the first > place to look if you need to look at some page that > no longer exists, or to see what an earlier version > of the page looks like. > when persistence is futile use the wayback machine. Great tip ! I knew of the WM as a curiosity or a sort of museum, but hadn't thought of using it like this. It got me the file, though... Nice stuff, thanks ! -- YAFAP : http://www.multimania.com/fredp/ From gez_75 at hotmail.com Mon Sep 29 17:03:44 2003 From: gez_75 at hotmail.com (gez) Date: Mon, 29 Sep 2003 23:03:44 +0200 Subject: Wavelet package available? References: <2ceb70f8.0309290136.118a856d@posting.google.com> <z4adnU-lwpqa1eWiU-KYjA@comcast.com> Message-ID: <bla6kk$mps$1@reader10.wxs.nl> Why this stupid answer? I tried to find python in combination with wavelets, both in the normal Google search engine and the Google groups search. Also jpython/jython, etc. but non of the results was what I wanted to use. So, that is why I posted it here. Think this is exacly the place to be... Looked at wavelets.org, looked for Java implementations,etc.etc. Btw, I once wrote a wavelets (de)composition in Delphi and C++Builder. And fyi, I looked up the faq. So, I am not a novice at all in this field, but I just need a version in Python which I couldn't find. So, please, think before you write such an answer. Not everybody is as stupid as you think. And even then. If someone doesn't know the correct search keywords for use in Google, this place is still the place to be. So please be more kind to the next poster that (in you eyes) posts a stupid question. "Terry Reedy" <tjreedy at udel.edu> wrote in message news:z4adnU-lwpqa1eWiU-KYjA at comcast.com... > > "Gez" <gez_75 at hotmail.com> wrote in message > news:2ceb70f8.0309290136.118a856d at posting.google.com... > > Does anyone know if there is a wavelet package available for Python? > > This package should at least have the Daubechy wavelet. > > Before posting a question like this and waiting hours for a reply, one > should try a search engine like Google. In this case, "Python > wavelets" > > If this fails, then post question and note what you tried without > success. This tells responders both that you made an effort and also > what they should not waste time on in trying to help you. > > Teaching-you-to-fish-ly yours, > > Terry J. Reedy > > From Juha.Autero at iki.fi Sat Sep 6 04:53:14 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Sat, 06 Sep 2003 11:53:14 +0300 Subject: OT: best book in years References: <opruzmelopdd8opo@news.vo.lu> <mailman.1062788891.30224.python-list@python.org> <bjaqpk$mnh$02$1@news.t-online.com> Message-ID: <877k4mgux1.fsf@jautero.no-ip.org> "Michael Peuser" <mpeuser at web.de> writes: > "Juha Autero" <Juha.Autero at iki.fi> >> >> G?del, Escher, Bach: an Eternal Golden Braid. It may not be the best >> book I read and not very useful, but I'd recomend reading it anyway. >> > > I made the same recommendation some minutes ago, but without your > reservation. In fact I might even come to the conclusion it *is* the best > book I have read ;-) It is just too hard to say what is the best book I've ever read. Or even best book on subject of IT or Python. That's why I didn' dare to suggest that GEB was the best book. > Why do you think it is not very useful? What do you think of Shakespeare by > the way? Poor choise of words. I was just trying to say that it's not as practical as other books suggested here like Python Cookbook or Mythical Man-Month. -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From JoeyTaj at netzero.com Thu Sep 18 16:24:31 2003 From: JoeyTaj at netzero.com (Paradox) Date: 18 Sep 2003 13:24:31 -0700 Subject: Python ISPs Message-ID: <924a9f9c.0309181224.374a5bef@posting.google.com> Does anyone know of some ISPs that have Mod_Python installed. Most seem to allow Python CGI but not things like Mod_Python or Spyce. Is this a viable solution or should I just learn PHP. I would prefer to leverage my Python knowledge but I also would like a fast robust solution. Thanks Joey. From tim at remove_if_not_spam.digitig.co.uk Fri Sep 19 19:54:09 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Sat, 20 Sep 2003 00:54:09 +0100 Subject: Passing data out of a Sax parser Message-ID: <fe5nmv0mno1ib23ifekntp3v3u2er5bstt@4ax.com> Is there a preferred way of passing data out of a Sax parser? My Sax content handler constructa an object for the rest of the program to use, but I'm not sure how to pass it to the rest of the program. Ways I can see: a. Put it in a global (blech!) b. Add a parameter to the handler's __init__ method, that takes some sort of mutable object, and put the answer into that object. Is it one of these that I should do? I suppose I could pass in the owning parser, and put the result into a new member of the parser, but I wonder if I'm missing something. TIA. From aleax at aleax.it Fri Sep 5 09:23:52 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 13:23:52 GMT Subject: basic language question References: <bj7ots$48j$06$1@news.t-online.com> <VUidncLV5oQd88qiU-KYvw@comcast.com> Message-ID: <I706b.17723$hE5.626547@news1.tin.it> Terry Reedy wrote: ... > 'Returners' could wrap no-return mutators with functions or > derived-class methods that do return the object, but I have never seen > anyone post a complete module that does so for, say, all list > mutators. What about...: def wrapReturning(func): def returningWrapper(*args, **kwds): func(*args, **kwds) return args[0] return returningWrapper class metaReturner(type): ''' simplified metaReturner: deal with single inheritance only ''' def __new__(mcl, className, classBases, classDict): # get the "real" base class, then wrap its mutators for base in classBases: if not isinstance(base, metaReturner): for mutator in classDict['__mutators__']: classDict[mutator] = wrapReturning(getattr(base, mutator)) break # delegate the rest to built-in 'type' return type.__new__(mcl, className, classBases, classDict) class Returner: __metaclass__ = metaReturner # example usage class returnerlist(Returner, list): __mutators__ = 'sort reverse append extend insert'.split() print returnerlist('hello').extend('ciao').sort().reverse() Alex From ggg at zzz.it Fri Sep 12 09:16:05 2003 From: ggg at zzz.it (deelan) Date: Fri, 12 Sep 2003 15:16:05 +0200 Subject: Is there a web templating system like ruby's amrita ? In-Reply-To: <6ee58e07.0309120421.622cb55@posting.google.com> References: <6ee58e07.0309120421.622cb55@posting.google.com> Message-ID: <2bksjb.6rp.ln@news1.interplanet.it> Lothar Scholz wrote: > I there anything that completely avoid the use of python code inside > a template. I like the Amrita system because it allows me to design > the templates with WYSIWYG editors and blind text. never used amrita before, but i took a brief look at the quick start: http://www.brain-tokyo.jp/research/amrita/rdocs/files/docs/QuickStart.html an this remembered my of PyMeld: http://www.entrian.com/PyMeld/ you may like it. bye -- email: goldicus1970 AT yahoo.it web: http://www.deelan.com From barry at python.org Mon Sep 29 09:24:31 2003 From: barry at python.org (Barry A. Warsaw) Date: Mon, 29 Sep 2003 09:24:31 -0400 Subject: RELEASED Mailman 2.1.3 Message-ID: <16248.12943.161685.438279@gargle.gargle.HOWL> I've released version 2.1.3 of Mailman, the GNU Mailing List Manager. Mailman is released under the GNU General Public License (GPL). Version 2.1.3 is a bug fix release which also contains support for four new languages: Ukrainian, Serbian, Euskara (Basque), and Danish. This release also contains a fix for a cross-site scripting vulnerability, as well as improved queue runner performancey. See the links below for a detailed list of changes. I recommend all sites running versions of the 2.1.x line upgrade to the new version. Mailman is free software that enables users to manage email mailing lists and e-newsletters. Its integrated web interface provides easy-to-use access for list members and list administrators. Mailman supports built-in archiving, automatic bounce processing, content filtering, digest delivery, spam filters, and more. Mailman is compatible with most web servers, web browsers, and mail servers. It runs on any Unix-like operating system. Mailman 2.1.3 requires Python 2.1.3 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 (not yet updated) 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 From imcmeans at telus.net Tue Sep 16 17:38:16 2003 From: imcmeans at telus.net (Ian McMeans) Date: 16 Sep 2003 14:38:16 -0700 Subject: scoping with lambda in loops Message-ID: <7f9e1817.0309161338.20fbdcbc@posting.google.com> I was bitten by a bug today that depended on how lambda works. It took me quite a while to realize what was going on. First, I made multiple lambda functions inside a loop, each of which depended on the current loop variable. >>> a = [] >>> for index in range(5): a.append(lambda: index) Now, see if you can guess what the output was for each of the functions in the list a: >>> a[0](), a[1](), a[2](), a[3](), a[4]() I had expected it to be (0, 1, 2, 3, 4), but actually, it's: (4, 4, 4, 4, 4) This really surprised me. I guess what is happening is that each lambda knows what the context of execution is where it was defined, and doesn't actually evaluate until the function is called, and when it does evaluate, it uses the current value of the variable. Is this related to static scoping? A similar thing would happen if you defined a nested function that used a variable declared in the outer function, then changed that variable, and called the nested function. Can someone recommend a way to code around this gotcha? I'm having trouble. I want the functions created inside the loop to execute with the value of the loop index at the moment when the function is made. From gh at ghaering.de Fri Sep 5 04:51:15 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 05 Sep 2003 10:51:15 +0200 Subject: Database over 2gb In-Reply-To: <71FAC84C4125D611B91F00B0D0D1D1C60FEE49@AFSNUMAIL> References: <71FAC84C4125D611B91F00B0D0D1D1C60FEE49@AFSNUMAIL> Message-ID: <3F584E83.3060801@ghaering.de> AFSOUTH Internet Administration wrote: > All, > > Our python database has accidentally grown over 2Gb [...] Which 'Python database'? ZODB? -- Gerhard From Ian.Sparks at etrials.com Mon Sep 29 15:26:35 2003 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Mon, 29 Sep 2003 15:26:35 -0400 Subject: Package question. Message-ID: <41A1CBC76FDECC42B67946519C6677A9A20C56@pippin.int.etrials.com> I'm sure its been thrashed through a hundred times but googling for an answer left me more confused than before and yes, I did read the Tutorial (maybe not well enough, but I read it). On Windows, I want to set up a package structure like : Fred Bob test.py So I can say : from Fred.Bob import * To do this I need to put the package on the python path. So I drop this into my python root in a file called Fred.pth : C:\Fred\ Now I need to make sure that Fred and Bob both look like packages with empty __init__.py files like so : C:\Fred __init__.py C:\Fred\Bob __init__.py test.py so : C:\python.exe -c from Fred.Bob import * OK! But if I do : C:\>cd Fred C:\Fred>python.exe -c "from Fred.Bob import *" Traceback (most recent call last): File "<string>", line 1, in ? ImportError: No module named Fred.Bob Now lets say I change my Fred.pth contents to C:\MyTest and put my whole directory structure under c:\MyTest : C:\MyTest\Fred __init__.py C:\MyTest\Fred\Bob __init__.py test.py C:\>cd MyTest\Fred C:\MyTest\Fred>python.exe -c "from Fred.Bob import *" Works fine. Is this quirk expected? If yes, I would like to expand my python knowledge with the why. Thanks for your attention on this long post. From max at ucmg.com.ua.remove.it Thu Sep 4 03:29:57 2003 From: max at ucmg.com.ua.remove.it (Max Ischenko) Date: Thu, 04 Sep 2003 10:29:57 +0300 Subject: Interoperability between VB and Python under ASP In-Reply-To: <ckx5b.1735$9P5.77107@twister.austin.rr.com> References: <bj46f2$kk2$1@voodoo.volia.net> <bb536467.0309031055.2fe6a661@posting.google.com> <ckx5b.1735$9P5.77107@twister.austin.rr.com> Message-ID: <bj6piu$f3f$1@voodoo.volia.net> Paul Paterson wrote: >> I don't know if this will help, but it might be worth a shot. >> http://vb2py.sourceforge.net/ I've never used it myself, I only point >> it out as a curiosity I've heard of > > > Although it isn't (currently) targetted at VBScript, the CVS version of > vb2py might help if you have reasonably sized blocks of VBScript code to > convert. It hasn't been tested on VBScipt specifically but the parser > should work for most things and I'd certainly be interested to hear of > any specific problems with ASP scripts. That's seems like an interesting idea! While I doubt that the conversion could (or, more appopriately, should) be done automatically, I'll check out your project, thanks. > If you do decide to try this route, I'd be very interested to hear of > any specific issues that come up with translating ASP/VBScript to Python. OK. -- Regards, Max. From mcherm at mcherm.com Tue Sep 9 12:59:15 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 9 Sep 2003 09:59:15 -0700 Subject: A couple of OOPython questions Message-ID: <1063126755.3f5e06e37ad07@mcherm.com> Alexy Khrabrov writes: > Reading python books feels a bit like reading Perl books -- although > OO is there, some fundamental questions are not illuminated, and then > OO comes after scripting or text, as in the Cookbook! Good point. Many Python tutorials start with simple scripts because they're shorter, and save OO for later. It's a bit misleading because short scripts may be easier to learn on, but most coding is done on larger systems, where OO is very useful. > E.g., a = b is a deep copy. No, that's not true. The line "a = b" binds the name 'a' to the object that the name 'b' is currently bound to. Nothing is copied. Well, depending on implementation, perhaps some pointer somplace is copied, but no PYTHON object is copied -- a and b will refer to the same object. > What are the equivalent of copy constructors? Python has no equivalent, because all objects live "on the heap" and are referenced via name binding. > Here's another OO question for some real-life application, not that > puny regex fun (or was that perl? :)... I've developed a CORBA server > for structural protein data, [...] > OK, now I go to my python prompt and I want to inspect my objects as > returned by the CORBA server. One of them represents an atom site. I > merrily type just its name to see the great unknown unwrap before my > eyes. Here: > > >>> a > <MMS.StructConf instance at 0x8cb1b44> Aha... sounds like you want a way of printing out the full structure of some object. Simply calling repr() on it (that's what gets printed after each line of input) won't do that, at least not in the general case (simple lists and dicts DO dump their full contents to repr(), but many objects don't). Actually, the general problem is quite hard. What about objects which contain OS-specific data (eg: file pointers). What about objects that contain references to themselves (which is more common than you might think)? One thing which I strongly recommend you to try is to get Python 2.3 and try out the version of Idle that comes with it. Start it up and then try "Stack Viewer" from the Debug menu. It's exactly the kind of thing you are thinking of here, except that instead of printing it all out it provides a tree you can drill down into. [...] > Printing out gazillion fields by hand for each class is silly, they > only wrap strings and numbers and other objects of that nature. I am > ready to dive in a recursive descent. No such luck -- whoever created > CORBA bindings for python didn't make those objects dictionary-like! [...] > Is there an easy way to write something _once_, general enough, to > print out a hierarchy of nested objects which just don't have > __getitem__, although every field is either a string or a number or > another object? Well, I'm sure there is SOME way to obtain them, but since I'm not familiar with the omniORBpy objects, I'm not quite sure how. And without knowing how to access them, I can't provide you with sample code. But check out the trick I decribe above for Idle... I think it may help you out. -- Michael Chermside From nobody at nowhere.near.here Fri Sep 26 13:21:50 2003 From: nobody at nowhere.near.here (nobody) Date: Fri, 26 Sep 2003 18:21:50 +0100 Subject: A bold new adventure in pain References: <mailman.1064590475.20931.python-list@python.org> Message-ID: <3f7475b5$0$254$cc9e4d1f@news.dial.pipex.com> Are you using PythonWin? IF yes than use tools->com makepy utility from the menu. I think it does what you want. <jwsacksteder at ramprecision.com> wrote in message news:mailman.1064590475.20931.python-list at python.org... > I am attempting to do something that has apparently never yet been done > before- implement a Crystal Reports User Function Library in Python. I > suppose I should preface this by saying "I just barely understand what I am > doing". > > CR has a standard for creating plug-ins that implement functions too > complicated to be done in CR's own internal grammar. When CR starts up, it > looks for COM automation servers starting with CRUFL and makes their methods > available as additional formulas inside CR. > > I have implemented a COM automation object that is registered and can be > called with Dispatch. It does, in fact, accept an input string and return > properly-formatted output. > > HOWEVER- My object does not appear the the 'COM Browser' of Activestate's > Pythonwin, and fails to be included in CR. This leads me to believe my > little endeavour has gone off the rails somehow. > > My class definition(sans methods) looks something like this: > > class code128tools: > _public_methods_ = [ 'code128B' ] > _reg_progid_ = "CRUFLfoo.code128" > _reg_desc_ = "Crystal Reports UFL Code128 toolkit" > _reg_clsid_ = "{733D454C-43C1-436F-A0E2-E12AE05E4F07}" > > I think I have failed to define the 'type library'. I welcome any assistance > gratefully. > From scribe at linuxht.com Mon Sep 8 21:25:53 2003 From: scribe at linuxht.com (Scribe) Date: Tue, 09 Sep 2003 01:25:53 GMT Subject: wxPython.grid Message-ID: <B_97b.90006$bo1.71105@news-server.bigpond.net.au> Hi The megagrid expaple in the docs is great but, I can make it all work with the grid appearing in its own window but how do I make it show on my frame. Thanks in advance. From martin.schneider at illusion-factory.de Tue Sep 9 09:54:41 2003 From: martin.schneider at illusion-factory.de (Martin Schneider) Date: Tue, 9 Sep 2003 15:54:41 +0200 Subject: Python / C: small runtime difference? References: <bjk3mi$jorjb$1@ID-119488.news.uni-berlin.de><bjka05$jlrt2$1@ID-119488.news.uni-berlin.de> <mailman.1063106894.20701.python-list@python.org> Message-ID: <bjkkjp$jvkvt$1@ID-119488.news.uni-berlin.de> Hi, Gerhard, thanks for your answer :-) Here's my python code: for i in range(len(fileList)-1): for j in range(len(fileList)-i-1): if fileList[j+1] < fileList[j]: tmp = fileList[j] fileList[j] = fileList[j+1] fileList[j+1] = tmp Of course I don't know what Python does here internally. > It's best to have an array of pointers to structs. Then in > your bubble-sort algorithm, only exchange the pointers, don't copy the > structs themselves. Okay - I'll try that :-) > So if you make your C code as > smart as Python automatically is <wink>, your C code should be a hell of > a lot faster than your Python code :-) Maybe :-) I'll let you know. Thanks! Martin From bogus at invalid.tld Thu Sep 25 23:50:41 2003 From: bogus at invalid.tld (Jules Dubois) Date: Thu, 25 Sep 2003 21:50:41 -0600 Subject: When did Windows start accepting forward slash as a path separator? References: <b16e4ef7.0309251550.724a57f@posting.google.com> Message-ID: <qwkk08g01cnk.1cg40v1qdfe2l.dlg@40tude.net> On 25 Sep 2003 16:50:49 -0700, in article <b16e4ef7.0309251550.724a57f at posting.google.com>, Stephen Ferg wrote: > When did Windows start accepting the forward slash as a path separator > character? Even MS-DOS 3.3 would accept '/'; the command-line utilities were programmed to use only '\' without some start-up parameter (PATHSEP?). Microsoft removed that feature in v4.0 or 5.0. The "kernel" didn't care. The Windows kernels are the same. The internals of the operating system accept either. From aleax at aleax.it Sat Sep 27 11:22:37 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Sep 2003 15:22:37 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <wCGcb.3064$yU5.2141@nwrdny01.gnilink.net> <8RScb.169633$R32.5449258@news2.tin.it> <uk77vhagj.fsf@boost-consulting.com> <JH_cb.174346$R32.5548036@news2.tin.it> <u7k3ve63q.fsf@boost-consulting.com> <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> <ur8239i6z.fsf@boost-consulting.com> <0acdb.128801$hE5.4391247@news1.tin.it> <u4qyy8mfk.fsf@boost-consulting.com> Message-ID: <1Xhdb.130593$hE5.4445587@news1.tin.it> David Abrahams wrote: ... > Well, (understanding that you don't nececessarily agree with the > above) you can in fact iterate on std::pair<T,T> with the usual C++ > iterator protocol, You mean there's an std::pair::begin etc?! OK, I guess I'm even rustier on standard C++ than I thought I was -- I could have SWORN there wasn't. (Std chapter & verse pls? I plan to win bets based on this tidbit...!-). So I guess the lack of those in gcc is a breach of the Standard on gcc's part...? > and with a new mixed compile-time/runtime tuple > iterator protocol developed by Doug Gregor, iteration over > heterogeneous tuples is possible too. It certainly is desirable to be > able to do that; it's a real need that has come up in practice. So, given an arbitrary struct, with fields (generally) of different types, you can iterate field by field? That's basically what the "heterogeneous tuple" is supposed to be equivalent to, in the "party line" I was relating (although the names to go with the fields are only present in a FEW such tuples, such as those returned by modules time and stat, as of now; more general tuples still haven't grown the ability to access fields by name, in Python). My partial dissent comes from feeling the need for "frozen/immutable lists" and the fact that tuples are often used as such (including goofy immutable representations of dicts, e.g. via tuple(thedict.iteritems()), and the like). If tuples cannot be thought of as immutable lists, then (I think) we need "immutable/hashable/frozen" lists by other means. (I need to say "I think" because, as I quoted, Ruby experts claim that the "anyobject.freeze" feature they do have isn't actually as useful as it SEEMS it should be -- though I'm not sure I understand why, yet). Alex From andy at wild-flower.co.uk Mon Sep 15 17:32:21 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Mon, 15 Sep 2003 22:32:21 +0100 Subject: unreferenced (???) variable; prob. simple In-Reply-To: <JESUSBTQYIcVqeavxhg00000401@webmail.campusnet.dtu.dk> References: <JESUSBTQYIcVqeavxhg00000401@webmail.campusnet.dtu.dk> Message-ID: <200309152232.21692.andy@wild-flower.co.uk> On Monday 15 Sep 2003 8:31 pm, Halfdan Holger Knudsen wrote: > goodday all - here's a snippet of code that just doesn't seem to work...at > all! But I haven't got the faintest idea why I keep getting an unref. > local var. error. Take a look - I know I can get good help here. And PS: > Thanks beforehand. > > If you're wondering - it's an attempt at a (crude) reproduction of the > string.split() functionality for learning purposes. > > ---------------------- > > #! /usr/bin/env python > > import string > begind = 0 > endind = 0 > > def stripfunc(): > inpstr = raw_input('String to strip: ') > length = len(inpstr) > spacelst = list(string.whitespace) > print spacelst > for a in range(length): > if inpstr[a] not in spacelst: > begind = a > break > break > for b in range(1, length+1): > if inpstr[-b] not in spacelst: > endind = length-b > break > break > stripstring = inpstr[begind:(endind+1)] > print stripstring > print begind > print endind > > if __name__ == '__main__': > stripfunc() Halfdan, I reckon it's due to your 'excessive use' ;-) of 'break'. Basically, neither of your for loops ever go more than one iteration, and if the first or last character of your string is not whitespace, your *local* variables begind and endind never get assigned anything (that's what Python said, right? ;-)). Try this for size: -----8<----- >>> def strp(strg): from string import whitespace b=0 while b<len(strg) and strg[b] in whitespace: b+=1 e=len(strg)-1 while e>b and strg[e] in whitespace: e-=1 return strg[b:e+1] >>> strp("\t\n this is a test \r\t") 'this is a test' >>> -----8<----- btw, string.split does this: >>> "\t\n this is a test \r\t".split() ['this', 'is', 'a', 'test'] but I guessed you meant string.split() ;-)) !bing! idea: def strp2(strg): return strg.split().join(" ") _However_ this will also remove duplicate spaces and any other whitespace in strg... maybe even useful! hth -andyj From danbmil99 at yahoo.com Tue Sep 30 00:49:05 2003 From: danbmil99 at yahoo.com (dan) Date: 29 Sep 2003 21:49:05 -0700 Subject: overriding built-ins References: <fbf8d8f2.0309281120.564ec9d5@posting.google.com> Message-ID: <fbf8d8f2.0309292049.eea47e6@posting.google.com> Thanks for the responses, and my apologies for getting the terminology confused. What I really should have asked is this: * Is there any way to create your own statements? and, * if so, can they override the names of built-in statements such as 'print'? To which the answers seem to be, no, and definitely not (with a strong hint of "why would you ever want to do that"?) danbmil99 at yahoo.com (dan) wrote in message news:<fbf8d8f2.0309281120.564ec9d5 at posting.google.com>... > I really have two related questions. > > 1) Is it possible (without recompiling and changing the core Python > behavior) to write functions that utilize the same syntax as built-in > functions? IE, can I create a function that does this: > > >>>printCaps "hello" #note no parentheses > HELLO > > > 2) Is it possible to do this with the built-in keywords themselves, ie > override functions such as print? > > thanks in advance - From gh at ghaering.de Tue Sep 30 20:04:14 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 01 Oct 2003 02:04:14 +0200 Subject: Registering Python 2.1.3 In-Reply-To: <6.0.0.22.0.20030930122535.027a6b08@66.28.54.253> References: <6.0.0.22.0.20030930122535.027a6b08@66.28.54.253> Message-ID: <3F7A19FE.2040206@ghaering.de> Bob Gailer wrote: > I need to register Python 2.1.3 so I can, in turn, install > sqlite-python-0.3.1.win32-py2.1.exe, so I can in turn use pysqlite with > ZOPE. [...] The simplest way to achieve your goal is to download the .exe PySQLite installer, then unzip (yes, *unzip*) it with a tool like WinZip, PowerArchiver, unzip.exe or whatever and move the files into their places. The trick is that a Windows installer creatd with distutils is basically a zip file with a little bootstrap routine in front of it :) -- Gerhard From jjl at pobox.com Wed Sep 24 13:22:30 2003 From: jjl at pobox.com (John J. Lee) Date: 24 Sep 2003 18:22:30 +0100 Subject: Fastest way to get thousands of db records to client in 3 tier? References: <Zr7cb.30579$uJ2.4877@fe3.columbus.rr.com> <3f71361f$0$97182$edfadb0f@dread12.news.tele.dk> <bZecb.14514$KJ5.11624@fe2.columbus.rr.com> Message-ID: <874qz22jah.fsf@pobox.com> amonroejj at yahoo.com (R. Alan Monroe) writes: > In article <3f71361f$0$97182$edfadb0f at dread12.news.tele.dk>, Max M <maxm at mxm.dk> wrote: > > >> I intend to write both client and server in Python, and my main goal > >> in the first cut is speed. Suggestions? > > >Why do you need thousand of rows at the client? Normally you would get > >the results in batches, so that you only transfer at most a few hundred > >at a time to the client. > > Those types of tests will be done in my second cut. At this stage you should be worrying more about this than about the details of the protocol and implementation thereof. > >Why not let the client ask directly if it is faster? > > I thought that defeats the purpose of having 3 tiers. You'd have to > update the client if/every time business rules changed. Unless I'm [...] Why? The client asks the client in terms of "business logic", the server asks the database in SQL. If server and DB can communicate quickly, no problem. John From domma at procoders.net Thu Sep 25 08:40:16 2003 From: domma at procoders.net (Achim Domma) Date: Thu, 25 Sep 2003 14:40:16 +0200 Subject: adodbapi / string encoding problem References: <bkuku2$qm5$04$1@news.t-online.com> <0ZAcb.118994$hE5.4097227@news1.tin.it> Message-ID: <bkunn8$pgs$03$1@news.t-online.com> "Alex Martelli" <aleax at aleax.it> wrote in message news:0ZAcb.118994$hE5.4097227 at news1.tin.it... > You have to *EN*-code Unicode into string, with the same way the string > had been *DE*-coded to Unicode originally, in order to be sure to get > the same string back; specifically, you have to use the same *codec* [...] Thanks Alex, I understand that, but looking at the adodbapi code I could not find any call to encode/decode. The conversion seems to happen somewhere in win32com. Don't know if you will ever get your data back, once it's converted to Variant. ;-) Achim From claird at lairds.com Mon Sep 1 12:29:42 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 01 Sep 2003 16:29:42 -0000 Subject: learning to program References: <mailman.1062052883.23262.python-list@python.org> <3f4e6a44.1219503072@news.blueyonder.co.uk> <vl6qm09a7drv2f@corp.supernews.com> Message-ID: <vl6svmmrt9c56@corp.supernews.com> In article <vl6qm09a7drv2f at corp.supernews.com>, I misled readers with: > . > . > . >But not *much* invalid. While I don't recommend it to >the original poster, as he's a beginner, it might amuse >those with a little Python background to play with > import Tkinter > Tcl_script = "some Tcl script here" > Tkinter.tk.eval(Tcl_script) . . . Incorrect. I had a little editing problem in posting that; I apologize to all the readers the missing "Tk()" has puzzled. Here's a more useful example: import Tkinter Tcl_script = 'puts "This is an example."' Tkinter.Tk().tk.eval(Tcl_script) -- Cameron Laird <Cameron at Lairds.com> Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From FBatista at uniFON.com.ar Wed Sep 17 13:47:59 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 17 Sep 2003 14:47:59 -0300 Subject: [newbie] Manipulating Dates Message-ID: <A128D751272CD411BC9200508BC2194D03382F8C@escpl.tcp.com.ar> #- newDate = oldDate + 3 months You can't (AFIK) #- What would that be in Python code? The problem is, what that be in Human code? Example: July 31 + 3 months: ?November 31? . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20030917/7c7984f8/attachment.html> From mwh at python.net Mon Sep 22 10:07:45 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 22 Sep 2003 14:07:45 GMT Subject: was: Re: looking for MOP documentation References: <oprvdsg7tl5j9jb9@news.tiscali.dk> <3F62123C.F671D058@engcorp.com> <oprvfiy8i15j9jb9@news.tiscali.dk> <3F6319E9.4C7BAA0F@engcorp.com> <bk6jav$p0k$1@mawar.singnet.com.sg> <3F66F516.3D06D946@engcorp.com> <m2he3bexzj.fsf@mycroft.actrix.gen.nz> <3F69AD0F.53D51719@engcorp.com> <3F69D215.5649AF66@hotmail.com> <3F69DFEB.5B05CED8@engcorp.com> <7h37k45j895.fsf@pc150.maths.bris.ac.uk> <3F6B2AB1.2D839EF5@engcorp.com> <7h3he359eda.fsf@pc150.maths.bris.ac.uk> <zQCbb.100778$hE5.3550142@news1.tin.it> Message-ID: <7h3zngw9azx.fsf@pc150.maths.bris.ac.uk> Alex Martelli <aleax at aleax.it> writes: > Michael Hudson wrote: > ... > > Fair enough. I can see your point of view, I just don't (completely) > > agree with it :-) You could have something with similar syntax, > > keywords, etc to Python but semantics like C, and it would still be > > horrible (IMHO). > > Tried pyrex? It comes reasonably close to the "something" you > describe, and it ain't all that horrible (IMHO). I'm not sure pyrex is all that close to what I meant. I meant something like this: include "stdio.h" def main(int argc, char** argv): char* s = "world" if argc == 2: s = argv[1] printf("Hello %s", s) OK, so maybe it's a little nicer than regular punctuation-soup C but I really do think it's the object model of Python plus having high-level types *right there* in the language that makes Python so useful (as opposed to the syntax which just makes it *pleasant*). Cheers, mwh -- I hate leaving Windows95 boxes publically accessible, so shifting even to NT is a blessing in some ways. At least I can reboot them remotely in a sane manner, rather than having to send them malformed packets. -- http://bofhcam.org/journal/journal.html, 20/06/2000 From mcherm at mcherm.com Fri Sep 26 17:47:59 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 26 Sep 2003 14:47:59 -0700 Subject: Reduce need of backslash Message-ID: <1064612879.3f74b40f24dcd@mcherm.com> John Roth writes: > And you can parenthesize a surprisingly large number of places. One > that I learned just recently was that the entire operand string of the > print statement can be put into parenthesis. Basically, you can parenthesize anywhere that an expression is expected. The only place that you can't which still bugs me frequently is this: from myModule import function_one, function_two, function_three \ function_four, function_five, Class_six, Class_seven which I use when typing "myModule." in front of the items would be burdensome. Of course, "from myModule import *" is concise, but evil and should be avoided. -- Michael Chermside From FBatista at uniFON.com.ar Thu Sep 18 12:27:03 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 18 Sep 2003 13:27:03 -0300 Subject: file object: seek and close? Message-ID: <A128D751272CD411BC9200508BC2194D03382FA4@escpl.tcp.com.ar> #- f = open('somefile', 'r') #- for lines in f: #- some operations #- f.seek(0) I think will be very useful if you detail what those "some operations" are. . Facundo From cnetzer at sonic.net Mon Sep 8 13:52:46 2003 From: cnetzer at sonic.net (Chad Netzer) Date: Mon, 08 Sep 2003 10:52:46 -0700 Subject: negative indices for sequence types In-Reply-To: <fbf8d8f2.0309080911.1cf73016@posting.google.com> References: <fbf8d8f2.0309071026.4c44b985@posting.google.com> <bjh94c$j9p$1@peabody.colorado.edu> <fbf8d8f2.0309080911.1cf73016@posting.google.com> Message-ID: <1063043565.1871.4.camel@adsl-209.204.179.133.sonic.net> On Mon, 2003-09-08 at 10:11, dan wrote: > My explanation of the behavior is correct however. list[a] always > equals list[a % len(list)]. Many people pointed out to you that this is NOT true. In particular, your version gives you NO bounds checking at all; every 'a' is a valid index (for len(list) > 0). The Python behavior DOES give IndexError for an out of bound a, and that difference is very significant, IMO. -- Chad Netzer From ads at chead.org Wed Sep 17 00:38:38 2003 From: ads at chead.org (ads) Date: Wed, 17 Sep 2003 11:38:38 +0700 Subject: GTK help Message-ID: <1386838535.20030917113838@chead.org> Hi All, I need some help, whe trying to run some gtk examples, show below messages: Traceback (most recent call last): File "D:\Downloads\python\test\pygtk\examples\pygtk-demo\demos\stock_browser.py", line 216, in -toplevel- main() File "D:\Downloads\python\test\pygtk\examples\pygtk-demo\demos\stock_browser.py", line 160, in main model = create_model() File "D:\Downloads\python\test\pygtk\examples\pygtk-demo\demos\stock_browser.py", line 33, in create_model store = gtk.ListStore(StockItemInfo) TypeError: could not get typecode from object >>> It show up when I run pygtk\examples\pygtk-demo\demos\stock_browser.py Could someone help me, what is wrong with my system? Thank you very much, *sorry my language is Indonesia, so I haven't good English From bgailer at alum.rpi.edu Wed Sep 10 15:56:46 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 10 Sep 2003 13:56:46 -0600 Subject: Opposite of yield? In-Reply-To: <3F5F7E35.B5DA4669@easystreet.com> References: <3F5F7E35.B5DA4669@easystreet.com> Message-ID: <6.0.0.22.0.20030910135508.03b69d28@66.28.54.253> At 01:40 PM 9/10/2003, achrist at easystreet.com wrote: >The yield statement looks to be a big step toward some kind of >lightweight concurrency-oriented programming in python. Is there >any similarly nice way to do the opposite of yield, just sit around >(perhaps in the middle of a loop) and wait until some other routine >(unknown to the waiting module) hurls a value in? Sounds like a task for a thread that sleeps a while then checks for the data. Also reminiscent (a long time ago) someone proposed a COME FROM statement for FORTRAN to be the inverse of GO TO. Perhaps a new Python statement "suck"? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From zanesdad at bellsouth.net Thu Sep 11 15:45:50 2003 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 11 Sep 2003 15:45:50 -0400 Subject: ftplib question: how to upload files? In-Reply-To: <40669.199.169.240.132.1063305332.squirrel@svr1.turboweb.net>; from python@sarcastic-horse.com on Thu, Sep 11, 2003 at 02:35:32PM -0400 References: <40669.199.169.240.132.1063305332.squirrel@svr1.turboweb.net> Message-ID: <20030911154550.C32566@cerberus.liberty> * python at sarcastic-horse.com (python at sarcastic-horse.com) wrote: > Hi: > > I want to write a procedure to automatically upload some files for me, but > I'm getting stuck. Before I write my own gruesome put() function, I > wanted to check if there is an easier way. > > Here's what I can do so far: > >>>import ftplib > >>>conn = ftplib.FTP('ftp.example.com') > >>>conn.login(user='userid', passwd='passwd') > >>>conn.cwd('/var/www/html/incoming') > > What do I do to send files? > > I have three files I want to upload, but I'm not sure what to do. I hoped > to find a ftplib.put() method, but it looks like ftplib is a low-level > interface. It is definitely a lower level interface. You need to do something like: conn.storbinary('STOR %s' % (file_name),file_object) to put in binary mode or: conn.storbinary('STOR %s' % (file_name),file_object) to put in ascii mode. HTH. Jeremy Jones > > All help is welcome. > > > -- > http://mail.python.org/mailman/listinfo/python-list From mpeuser at web.de Sun Sep 21 03:29:00 2003 From: mpeuser at web.de (Michael Peuser) Date: Sun, 21 Sep 2003 09:29:00 +0200 Subject: What is the meaning of the astarisk in Python References: <3f6ce54f$0$10962$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <bkjjth$lat$02$1@news.t-online.com> "John Dean" <john at rygannon.com> schrieb im Newsbeitrag news:3f6ce54f$0$10962$fa0fcedb at lovejoy.zen.co.uk... > Hi > Below is a line taken from Andy Dustman's MySQLdb module: > def Connect(*args, **kwargs): > > I would be grateful if somebody explain the meaning of the astarisks, since > I was under the impression that pointers are not used in Python and the > above look very must like pointers to me In addition to the other answers: It also works the other way: You can use tuples ore dicts for positional or keyword parameters. This generally comes handy for co-ordinates in graphic routines. def p(a,b,c,d, x=None,y=None): print a,b,c,d,x,y abcd=(1,2,3,4) xy={'x':100, 'y':200} p(*abcd) p(0,0,0,0,**xy) Kindly MichaelP From logistix at cathoderaymission.net Tue Sep 30 17:32:02 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 30 Sep 2003 14:32:02 -0700 Subject: can i implement virtual functions in python ? References: <e73c30c6.0309300653.24456567@posting.google.com> Message-ID: <3c91a864.0309301332.3483a61@posting.google.com> prabua at hotmail.com (Prabu) wrote in message news:<e73c30c6.0309300653.24456567 at posting.google.com>... > Hi, > > I'm new to python, so excuse me if i'm asking something dumb. > Does python provide a mechanism to implement virtual functions? > Can you please give a code snippet also...:) > Thanx in advance > -Prabu. As others have mentioned, all methods are overridable in python. But if you want to create a genuine Abstract Base Class, raise NotImplementedErrors for the virual methods. People will tell you that this is not 'pythonic' (you should be using hasattr() to test for interfaces) but I still find it useful from time to time. PythonWin 2.3.2c1 (#48, Sep 30 2003, 09:28:31) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> class virtualClass: ... def __init__(self): ... pass ... def virtualMethod1(self): ... raise NotImplementedError("virtualMethod1 is virutal and must be overridden.") ... def concreteMethod1(self): ... print "The concrete method is implemented" ... >>> x = virtualClass() >>> x.concreteMethod1() The concrete method is implemented >>> x.virtualMethod1() Traceback (most recent call last): File "<interactive input>", line 1, in ? File "<interactive input>", line 5, in virtualMethod1 NotImplementedError: virtualMethod1 is virutal and must be overridden. >>> class subClass(virtualClass): ... def virtualMethod1(self): ... print "sub class implemented virtualMethod1" ... >>> y = subClass() >>> y.concreteMethod1() The concrete method is implemented >>> y.virtualMethod1() sub class implemented virtualMethod1 >>> From max at fr.fm Wed Sep 17 06:01:46 2003 From: max at fr.fm (Maxime Biais) Date: Wed, 17 Sep 2003 12:01:46 +0200 Subject: Graphic python debugger Message-ID: <20030917120146.3c5202e2.max@fr.fm> Hello, I'm looking for a graphic debugger for python on linux like DDD or GVD. I tried pdb and pdb-mode for emacs, but I would use a more gvd-like debugger. -- Maxime Biais From skip at pobox.com Wed Sep 24 15:28:38 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Sep 2003 14:28:38 -0500 Subject: __init__ return value In-Reply-To: <6.0.0.22.0.20030924124805.0346ed20@66.28.54.253> References: <A128D751272CD411BC9200508BC2194D03382FFE@escpl.tcp.com.ar> <16241.58373.833630.615370@montanaro.dyndns.org> <6.0.0.22.0.20030924124805.0346ed20@66.28.54.253> Message-ID: <16241.61542.584624.536623@montanaro.dyndns.org> >> No, __init__ method return values are always ignored. Bob> Oh? >>>> class A: Bob> ... def __init__(self): Bob> ... return 'asdf' Bob> ... >>>> A() Bob> Traceback (most recent call last): Bob> File "<interactive input>", line 1, in ? Bob> TypeError: __init__() should return None My apologies. It is checked and an exception raised if it's not None. That's an implementation detail, not a property of the language. Skip From vincent_delft at yahoo.com Mon Sep 1 12:01:22 2003 From: vincent_delft at yahoo.com (vincent delft) Date: 1 Sep 2003 09:01:22 -0700 Subject: HELP : class and variables Message-ID: <5c184570.0309010801.2353a3cc@posting.google.com> Sorry if my question is stupid. I've missed something with classes. Can you explain the following ? class test: var1=1 var2=2 res=var1+var2 t=test() print t.res >> 3 t.var1=6 print t.res >> 3 ?????????????????? I though that everithing is memory zones. Why it's not 8 ? Thanks From mertz at gnosis.cx Mon Sep 8 14:59:22 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 08 Sep 2003 14:59:22 -0400 Subject: What is marketing? References: <mailman.1062969251.5905.python-list@python.org> <qU9W/kKkXURB092yn@gnosis.cx> <mailman.1062983352.15417.python-list@python.org> <qnY6b.42704$R32.1360114@news2.tin.it> <eIMX/kKkXswV092yn@gnosis.cx> <mailman.1063044013.17856.python-list@python.org> <Uc47b.46580$R32.1483053@news2.tin.it> Message-ID: <KGNX/kKkX4cC092yn@gnosis.cx> |> The neutral word that Alex is looking for is 'promotion', which has a |> subtle but important difference from the dirty word. Alex Martelli <aleax at aleax.it> wrote previously: |Nope -- it's "marketing" as defined in textbooks of economics Ahh... that begs the question[*]. I do not believe that Economics is the relevant field to consult as to the purpose of the python.org website. Economists give only economic answers to questions, and that's not the particular song-and-dance that interests me (FWIW, I've published in an Economics journal, and taken graduate economics courses--albeit suspiciously lefty ones--so my eschewal comes from something other than simple ignorance). If we decide our textbook should be one about Sociology, or Psychology, or Anthropology, or Communications, the false generality for the term 'marketing' evaporates. IOW, I'm more interested in what Thorstein Veblen would say than in what Ludwig von Mises would say :-). Or for that matter, I'd rather consult Erving Goffman. Yours, Lulu... [*] Has anyone else noticed how horribly misused this phrase has become... including in a televised ad series by Adobe for Acrobat. -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From mensanator at aol.com Tue Sep 23 21:04:33 2003 From: mensanator at aol.com (mensanator) Date: 23 Sep 2003 18:04:33 -0700 Subject: why the inconsistency? Message-ID: <fbf22ff1.0309231704.3f324abf@posting.google.com> I just installed Python 2.3 (upgrading from 2.1). Version 2.3 is noticably faster and the automatic conversion to long integers is very handy: >>> print 2**64 18446744073709551616 But if I want to know how many digits 2**64 has, I can't just do >>> print len(2**64) Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: len() of unsized object So instead, I did this >>> print len(`2**64`) 21 But the correct answer is 20, not 21. The reason the answer is wrong >>> print `2**64` 18446744073709551616L Why is the "L" there? I thought "L" isn't used anymore? From FBatista at uniFON.com.ar Tue Sep 23 12:47:37 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 23 Sep 2003 13:47:37 -0300 Subject: idle import problem Message-ID: <A128D751272CD411BC9200508BC2194D03382FEB@escpl.tcp.com.ar> #- Traceback (most recent call last): #- File "<pyshell#15>", line 1, in -toplevel- #- import countylist #- ImportError: No module named countylist #- >>> Where do you have located this file? This directory is in your path? . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20030923/64d77382/attachment.html> From mwilson at sarcastic-horse.com Tue Sep 23 09:22:05 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Tue, 23 Sep 2003 09:22:05 -0400 (EDT) Subject: a little OT: how to handle this email list? Message-ID: <51397.199.169.240.132.1064323325.squirrel@svr1.turboweb.net> Hi- I subscribe to the python mailing list with an IMAP mailbox. I use squirrelmail to check my mail. This is a great list, but it is definitely high volume. My python folder fills up with several hundred emails every day. How do the rest of you handle all the traffic on this list? Do you delete everything at the end of every day? All insights are welcomed. From carl at hotmail.lala.com Mon Sep 29 22:27:15 2003 From: carl at hotmail.lala.com (Carlo v. Dango) Date: Tue, 30 Sep 2003 04:27:15 +0200 Subject: meta classes Message-ID: <oprwajrpt3g9zfwx@news.tiscali.dk> hello there I'd like to take control over the method dispatching of every subclass of a given python class. Currently I've redefined __getattribute__() so i can find the right instance/method to dispatch to. This works fine, albeit it may seem a bit hackish. Further I want to control the actual dispatching, so that I can execute methods before, after or instead of the actual method. I would prefer to do this with the least modification of the source due to debug'ing issues. My best idea so far is to rename every method who subclass the magic class X and then create new methods in place of the renamed ones, which looks up in a list to execute "before-methods", then execute the renamed method etc.. Only I don't know how to do this. I've found some MOP code which was designed for python old-style objects... but this is not what I want. Can anyone kindly give me some pointers for help or some actual code? many thanks in advance.. --- From sheila at spamcop.net Tue Sep 2 16:30:26 2003 From: sheila at spamcop.net (Sheila King) Date: Tue, 02 Sep 2003 20:30:26 GMT Subject: MySQLdb -- any way to get "rows matched"? References: <fg54lvg2uhicjvl0i9a1vq5h925frjr4gq@4ax.com> <mailman.1062518530.3141.python-list@python.org> <bj202l.1nc.1@kserver.org> <mailman.1062529509.26494.python-list@python.org> Message-ID: <bj260h.1bk.1@kserver.org> On Tue, 2 Sep 2003 14:04:20 -0500, Skip Montanaro <skip at pobox.com> wrote in comp.lang.python in article <mailman.1062529509.26494.python-list at python.org>: > mysql> UPDATE example SET AGE=30 WHERE AGE=30; > Sheila> Query OK, 0 rows affected (0.00 sec) > Sheila> ws matched: 2 Changed: 0 Warnings: 0 > > Sheila> MySQLdb in Python: > > >>>> c = conn.cursor() > >>>> c.execute("""UPDATE example SET AGE=30 WHERE AGE=30;""") > Sheila> 0L > >>>> c.messages > Sheila> [] > >>>> c.info() > Sheila> '' > > Sheila> Being a MySQL and MySQLdb newbie, I'm not sure if there is any > Sheila> way to find out how many matched, via Python's MySQLdb module. I > Sheila> thought, from the source code, that .messages or .info() for the > Sheila> cursor attributes/methods might do it, but apparently not??? > > I'm not sure what the return value means when executing an update. My guess > is that it returns the number of rows changed. If you want to know the > number of rows matched, execute a SELECT which matches your WHERE clause: > > >>> db = MySQLdb.Connection(...) > >>> c = db.cursor() > >>> c.execute("select * from cities where city='San Jose'") > 4L > >>> c.execute("update cities set city='San Jose' where city='San Jose'") > 0L > > Skip Right. That is what I was saying, except that the OP wants to get the number of matches from an UPDATE statement, even if they entries are not updated. IOW, he doesn't want to have to do both SELECT and UPDATE but is hoping to get the information from only an UPDATE statement. I was correcting what I believe was incorrect information in an earlier post. i.e. you wrote: On Tue, 2 Sep 2003 11:00:58 -0500, Skip Montanaro <skip at pobox.com> wrote in comp.lang.python in article <mailman.1062518530.3141.python-list at python.org>: > Chris> When issuing updates in mysql (in the console window), mysql will > Chris> tell you if any rows matched and how many rows were updated (see > Chris> below). I know how to get number of rows udpated using MySQLdb, > Chris> but is there any way to get the number of rows matched? > > I believe the return value of the cursor's execute() method gives you the > number of rows which matched. > > Skip which is not correct. Roberto Gomez from Argentina contacted me in private email in response to my last post (apparently having trouble posting to the mailing list today for some reason) and pointed out that the MySQLdb exceeds the required DB-API for Python, as the result of "execute" for a cursor is undefined according to the DB-API. True enough. His point was, that if there is a concern that the program be compatible with possible other databases in the future, besides MySQLdb, that this feature of the MySQLdb cursor.execute method should not be assumed. In summary the "gee I'm a newbie" remark was meant to indicate that I do not know the answer to the OP's question, not that I didn't know how to get the result from a SELECT statement. Sorry for being unclear. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From panbru at comcast.net Fri Sep 12 12:14:56 2003 From: panbru at comcast.net (T. Panbru) Date: Fri, 12 Sep 2003 10:14:56 -0600 Subject: Canvas - Rectangle. Is there an easy way to detect if you're inside? In-Reply-To: <4378fa6f.0309120811.394c494b@posting.google.com> References: <4378fa6f.0309111159.7a9bb539@posting.google.com> <ekCdneV55u9Ij_yiXTWJhA@comcast.com> <0KScnYKghrLc1fyiXTWJjQ@comcast.com> <bjrtmh$bts$03$1@news.t-online.com> <4378fa6f.0309120811.394c494b@posting.google.com> Message-ID: <kuCdnapfh9SDbPyiU-KYvQ@comcast.com> Type "point in polygon algorithm" into Google and follow the links. Tim Marc wrote: > Yeah, I've had to use the 'tags' parameter fairly heavily to bind > different groups of canvas objects to different mouse actions. So I'm > all over that. > > But I think the key thing you said was "has to be filled." Basically > I'm using the rectangle as a border within which other things are > placed. The border itself is simply an overlay where I need the > background to show through. Therefore I can't fill it with anything. > > So if it has to be filled, apparently there is no easier way than the > way I'm doing now. From fawcett at teksavvy.com Wed Sep 10 01:16:49 2003 From: fawcett at teksavvy.com (Graham Fawcett) Date: Wed, 10 Sep 2003 01:16:49 -0400 Subject: Redesign of Python site In-Reply-To: <16222.9390.817242.32280@montanaro.dyndns.org> References: <Xns93EEDC144D362whiteywidowyahoocom@216.77.188.17> <mailman.1063040841.27825.python-list@python.org> <VUOdnRS_xeZOYcCiRTvUqA@speakeasy.net> <3F5E0171.B68BDE2F@engcorp.com> <_WydnXPHCO6oksOiRTvUqA@speakeasy.net> <16222.9390.817242.32280@montanaro.dyndns.org> Message-ID: <3F5EB3C1.6020107@teksavvy.com> Skip Montanaro wrote: > amk> I envision people wanting information on a specific version first, > amk> only later going to the more generic items under "documentation". > amk> Do other people think this would be a good idea? > >I think docs are more important than specific versions. Sure, the first >time they come to the site they'll be looking for "Python 2.3". But most >times after that they'll want documentation. The most frequent page I visit >on the site is > > http://www.python.org/dev/doc/devel/modindex.html > >That far outpaces any other page on the site, even the home page, so I >bookmarked so it's one click away. > > Interesting point. It might prove useful to those redesigning the site, or discussing its redesign, to examine either -- python.org's Web logs, if available, or -- a Google of "python site:python.org" to determine frequencies of visits to various parts of the site. (I am assuming, based on minimal knowledge of Google's ranking algorithms, that the most "relevant" pages will be close to the top of the Google list.) Here's a fun exercise for someone with some time on their hands: Mirror the larger part of the Python site. Then apply extra formatting to each page, and to links on each page, indicating how "hot" they are, based on frequencies determined from the logs or Google. For example, my Google search (above) would suggest that the home page and the tutorial page are both "hot", so both these pages and any links to these pages would appear in a warm colour; links to "Python Patch Submission Guidelines" appears on Google's Page 10 (today, anyway), so it would get a cool-colour treatment. At a glance, this should show which parts of the site, and which links, are "used" and which are "not used" (relatively, by the past and present audiences of the site, of course). If you are colour-blind (I mean, chromato-visually impaired), perhaps you could use various font sizes instead of colours. I leave the implementation as an exercise for the student. ;-) Of course, the colour map describes past behaviour, and conclusions drawn from examining such a "coloured" site might reinforce past usage patterns, which may or may not be favourable, depending on your point of view. Best, -- Graham P.S. If someone implemented this, I would get my boss to buy a boxed set. And I'll trade the rights for a canoe. ;-) From bokr at oz.net Thu Sep 11 10:55:36 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Sep 2003 14:55:36 GMT Subject: Why the 'self' argument? References: <slrnblh5ru.nd5.gstaniak@inka.zagiel.pl> <vlh7otscuo8gb1@news.supernews.com> <slrnbm0nci.d9.gstaniak@inka.zagiel.pl> Message-ID: <bjq2d8$ttd$0@216.39.172.122> On Thu, 11 Sep 2003 11:33:38 +0000 (UTC), Grzegorz Staniak <gstaniak at inka.zagiel.pl> wrote: [...] >To sum up what I've learnt here and from the FAQ: 'self' could actually be >any string (it is 'self' by convention), as its role is only to serve as >the first argument of methods in order to facilitate the process of >associating method calls with their context. It would be possible (even if >not obviously desirable) to implement method definitions in such a way >as to avoid the first argument completely, i.e. > > def something(): > ... > >so actually it's just a question of implementation. Having little >experience with object-oriented programming, I won't try to relate to >pro and contra arguments that have been given in the discussion, I just >have one more question: isn't it a little superfulous to have to use the >'classmethod()' builtin to declare class methods? I'd think giving a >class object name as the first argument should suffice? > I think you may have misunderstood classmethod. Rebinding a class attribute with the result of classmethod makes a method that works differently from an ordinary method. It means that the class itself will be bound to the first argument, even if the method is called as an attribute of an instance of the class. E.g., >>> class A(object): ... def cm(*args): return args ... cm = classmethod(cm) ... def m(*args): return args ... >>> class B(A): pass ... >>> a= A() >>> b= B() >>> a.cm() (<class '__main__.A'>,) >>> a.m() (<__main__.A object at 0x00902350>,) >>> b.cm() (<class '__main__.B'>,) >>> b.m() (<__main__.B object at 0x008F9690>,) and note: >>> A.cm() (<class '__main__.A'>,) >>> B.cm() (<class '__main__.B'>,) but: >>> A.m() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unbound method m() must be called with A instance as first argument (got nothing instead) >>> B.m() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unbound method m() must be called with B instance as first argument (got nothing instead) also, you don't have to do it inside the class definition, and it's not about a specific attribute name -- i.e. you don't have to write xxx = classmethod(xxx) as is conventional, unless the following is fooling me. >>> def bar(*args): return 'bar %r'%args ... >>> class C(B): pass ... >>> C.cmbar = classmethod(bar) >>> c=C() >>> c.cmbar() "bar <class '__main__.C'>" >>> C.cmbar() "bar <class '__main__.C'>" >>> c.cm() (<class '__main__.C'>,) >>> c.m() (<__main__.C object at 0x00902170>,) Of course the result is not *identical*, since you can see the original function name (note that you get a *bound* method either way with a classmethod, vs the ordinary C.m/c.m) >>> C.cmbar <bound method type.bar of <class '__main__.C'>> >>> c.cmbar <bound method type.bar of <class '__main__.C'>> >>> C.cm <bound method type.cm of <class '__main__.C'>> >>> c.cm <bound method type.cm of <class '__main__.C'>> >>> C.m <unbound method C.m> >>> c.m <bound method C.m of <__main__.C object at 0x00902170>> Regards, Bengt Richter From M.Waack at gmx.de Thu Sep 25 11:00:37 2003 From: M.Waack at gmx.de (Mathias Waack) Date: Thu, 25 Sep 2003 17:00:37 +0200 Subject: squeeze and package imports Message-ID: <lhcb41-6t3.ln1@valpo.de> Hi, I've got a problem with Fredrik's squeeze tool. I've got a script which accesses a Oracle DB with the help of DCOracle. This script works very well, but after squeezing it the "import DCOracle" fails. The DCOracle package consists of several python files and some shared libs. The import of one shared lib from within the package fails. It looks like a problem with the code responsible for searching the appropriate module file. Let me try to illustrate the situation. DCOracle ist installed under /tmp for example: /tmp +--- DCOracle +----- odb.py +----- Buffer.sl +----- __init__.py ... __init__.py imports odb.py which imports Buffer.sl, that means in odb.py you can find statements like from Buffer import Buffer If I import it from my script: sys.path.append("/tmp") import DCOracle it works without squeezing and fails with squeezing. In the latter case, the Buffer import statement named above fails. The traceback shows, which import in which file is executed, but instead of the directory names of each file it prints only question marks "?". Thus I thought, if the import code doesn't know about the current directory, it can't import the Buffer module, because it can't look into the "same" directory. And so my second try: sys.path.append("/tmp") sys.path.append("/tmp/DCOracle") import DCOracle And everything works fine. But I'm still curious - there seems to be something wrong with the import hooks in the squeeze module. BTW, I'm using python 2.2.2. Any ideas? Mathias From peter at engcorp.com Mon Sep 15 16:32:03 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Sep 2003 16:32:03 -0400 Subject: irritating problem References: <20030915150042.22749.00001062@mb-m23.aol.com> Message-ID: <3F6621C3.56525D6B@engcorp.com> Park997 wrote: > > I have a script that runs correctly in IDLE, runs correctly when invoked in the > Command Prompt (Win XP), runs correctly from Komodo, but flashes a black box > too fast to see when the icon is double clicked and produces no output. There > are no error meassages from any of the methods that produce output. All of the > other modules in the same directory (these are imported to the problem module) > work correctly in any start mode. Can you select Properties for that icon and change it so it doesn't close the window automatically when the program terminates? Or is this just using the default settings after you've installed Python, in which case it's being run using the assocation for the .py file extension? In that case, you should go to Explorer, under View->Folder Options. Then click the File Types tab, scroll down until you find the entry for the Python files (make sure you use .py or .pyw as appropriate), then click on Edit, then on Run in the Actions area, then on Edit. You should then see, in about the 19th dialog that has popped up (isn't Windows wonderful?! Truly those at Microsoft are masters of good user interface design!), the actual command that is being executed when you click on the icon. I suspect it uses the directory that the .py file is in as the current directory, and it should show an absolute path to where it thinks Python should be, then something like "%1" %* which roughly means execute the file using the exact command plus the filename in quotation marks. I suspect the %* does nothing in most cases. If you can then go to the DOS prompt in the same directory, and type the same command, and everything works.... well then you've got a problem on your hands, don't you? ;-) (But let us know more, then, as there are doubtless other steps to take.) -Peter From jjl at pobox.com Tue Sep 2 17:46:50 2003 From: jjl at pobox.com (John J. Lee) Date: 02 Sep 2003 22:46:50 +0100 Subject: Bayesian kids content filtering in Python? References: <20030828161409.V40715@onyx.ispol.com> <AVA3b.9197$Pn6.1974@twister.austin.rr.com> <7e7439f1.0309020641.28ace8fc@posting.google.com> Message-ID: <877k4qyib9.fsf@pobox.com> ed at digitallumber.net (Ed Stoner) writes: > I've been looking at this sort of thing for a while now. I initially > tried what you did about a year and a half ago and ran into some > problems. I ended up writing my own http proxy, html parser, and > bayes filtering code. It is being used now by Woodland Hills School > District in Pittsburgh, PA. The school has 2300 computers, 6000 > students, and 3 T1 lines to the Internet. Most of the problems I ran [...] Interesting. How closely has the success of Willow at the school been monitored? Has somebody taken a statistical sample of unlucky kids and watched their surfing closely, for instance? How does it fail, if so? I think the ways that it fails are probably more interesting than the frequency of failure at a particular site. I suppose one problem is that the frequency of abuse is likely to be low once you start cracking down! What have been your experiences with attempting to subvert your own system? Of course, the fundamental problem with testing these things is that a successful block doesn't tell you anything about all the cases where blocking would fail... John From maney at pobox.com Thu Sep 18 01:00:10 2003 From: maney at pobox.com (Martin Maney) Date: Thu, 18 Sep 2003 05:00:10 +0000 (UTC) Subject: No "side effect" assignment! References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> <bk2okk$nrhg9$1@ID-139865.news.uni-berlin.de> <38ec68a6.0309142310.30c09f9f@posting.google.com> Message-ID: <bkbe4q$8il$2@wheel2.two14.net> Asun Friere <afriere at yahoo.co.uk> wrote: > In terms of pandering to newbies, I think the requirement that loop > conditions be expressions is much more squarely aimed at experienced > programmers, who would otherwise be tempted to write unintelligible > code by placing too much of the programs logic withing the loop > condition. Uhm, no. *Experienced* programmers know better than to take usch things to excess, unless the code is being written for a obfuscated code contest. As is so often the case, it's those difficult in-betweeners, no longer innocent by virtue of ignorance, not yet grown wise enough to eschew the merely clever, who bollix it all up for the rest of us. -- Threaten not the comic with your lawyers' bluster, all toothless to supress parody and satire; for you will not amuse him, but you may inspire him. (me, inspired by http://www.netfunny.com/rhf/jokes/01/Apr/mcrhf.html) From anna at aleax.it Tue Sep 23 11:22:24 2003 From: anna at aleax.it (Anna Ravenscroft) Date: Tue, 23 Sep 2003 15:22:24 GMT Subject: Computer Programming for Everybody, a Newbie Project References: <mailman.1063781063.16709.python-list@python.org> <tAV9b.181$qK1.218658@news2.news.adelphia.net> <8e6e8e5d.0309171647.65d5ea1f@posting.google.com> Message-ID: <pan.2003.09.23.15.22.20.630726@aleax.it> On Wed, 17 Sep 2003 17:47:22 -0700, Ron Stephens wrote: >> > Three years of sustained effort. >> > >> > But we seemed to have taken away different lessons. >> > >> > My expereince led me to look upon the CP4E slogan quite askance. >> > Yours, apparently, allowed you to embrace it. > > Agreed, and I respect your point of view on this. Also, I noticed that > some one on the marketing-python list a few weeks ago made a similar > comment; that he was not too happy about people making too much of > Python's alleged ease of learning, because it devalued the skills of > those professional programmers who need to be fairly paid and make a > living at programming with Python. This seems to me to be a reasonable > position to take, but still, since Guido coined CP4E, I feel justified > in exploring that aspect of Python's nature, and I do find I that the > hypotesis that ease of learning and ease of use might ultimately win out > in the programming field, this resonates with me. > > But we certainly still need expert Python programmes, to do the real > work, create the serious business systems, and also to create the tools > that I and others like me use ;-))) > > >> > It seems to me "everybody" who's imagination is ignited by something >> > to >> the >> > extent that it carries them through 3 years of sustained effort can >> > expect to be doing "computer programming" somewhere along that line. >> > >> > Not very surprising, really. > > Good point. And the same aforementioned marketing-python poster pointed > out that brain surgery is not for everybody, and that programming is > also not for everybody. And I agree. But the CP4E slogan is using > hyperbole to make a memorable point...that programming can be usefully > extended to a far greater audience. And that learning as much as one is > interested in about the brain, nervous system, and artificial > intelligence does not create a danger that such people will take > scalpels to their loved ones' heads. It's horses for courses, you know? > >> > No slogans helped me along - that I do know. >> > >> > It was three years of sustained effort. >> > >> > For everybody? >> > >> > Are we *required* to embrace that notion? > > LOL. Of course we are not required to embrace any notion. Even if you > advocate curly braces, your welcome in my discussions, but I wont agree > with you ;-))) > > >> > Yes everybody - let's say - has that potential. But that was true >> > before Python came along. >> > >> > For some - like myself - Python was a real factor in helping realize >> > that potential. I am a raving fan, in fact. >> > >> > But I do not discount my 3 years of sustained effort as anything less >> > than >> 3 >> > years of sustained effort, and seem to think that that was a bit of >> factor, >> > as well. > > Hey, I did put in a lot of effort, sustained effort, as you say, and > I do not de-value that. Perhaps one of my primary resaons for admiring > Python so much is that it helped to sustain in me that 3 year effort, > which is no mean feat. > > >> > And would love to see the CP4E slogan go away now, peacefully and >> > happily. >> > >> > Art > > Well, I like the CP4E sloagan; but I'm not married to it. One of my > first exposures to Python was a mention of CP4E in some good book about > hackers, primarily Linus Torvalds, but I forget the title. The author in > a later chapter of that book mentioned Guido's CP4E slogan and it > piqued my interest. But I don't mind some others being turned off to it. > > Look, the main thing is this. My program is trivial, I could have done > more than half of it by simply using an Excel spreadsheet way back 3 > years ago. But I wouldn't have , and the Python program, trivially > simple as it is at its roots, raises interesting ideas for extension and > expansion that could just possibly lead to quite interesting uses. It > will still be trivial in most ways, it wont ever earn a buck, but it > could be interesting and useful; and I don't think I would have been > motivated to follow up on any of those ideas in a lesser language in > which the barrier to such exploration was higher than I would want to > pay. Python seems to encourage and reward incremental effort, and it > leads one to explore extentions and improvements to programs because the > language makes it relatively easy to see how to do the extensions. <snip> Greetings from one longish-term newbie to another. Python is the reason I'm doing programming. I learned a bit of Pascal and Basic mumbletymumble years ago (let's just say that I started learning on punchcards and leave it at that shall we?). But, it was never something that I felt enough comfort with to *use* in my day-to-day life. It was always so much effort for the slightest return... Python, otoh, *IS* comfortable and easy to use - which means I use it more. I've been able to use it regularly in little ways both at work and at home. As I feel more comfortable with it, I find more ways I can use it. Which is kewl! And, afaic, if *I* can use it, just about *everybody* could... well, okay - you have actually have more imagination and intelligence than a turnip... Anna -- Bottom line: ignore your body, it's most likely doing you harm. Lyle McDonald, mfw From dyoo at hkn.eecs.berkeley.edu Mon Sep 8 01:05:19 2003 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 8 Sep 2003 05:05:19 +0000 (UTC) Subject: ANN: Baypiggies User Group Meeting, September 11, 2003 Message-ID: <bjh2mf$n95$1@agate.berkeley.edu> BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: September 11, 2003 @ 7:30pm Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: Wavlets for SciPy Speaker: Chad Netzer Abstract: This talk will demonstrate an implementation of a wavelets package for SciPy, and present some applications with signal processing and image classification. There will be discussion of the benefits of doing scientific computation with Python, unit testing with statistical methods, and using SciPy with PythonCard as a learning tool. (Knowledge of wavelets is not a requirement, and the math will be kept to a minimum) We hope to see you there! From roy at panix.com Tue Sep 2 20:17:55 2003 From: roy at panix.com (Roy Smith) Date: Tue, 02 Sep 2003 20:17:55 -0400 Subject: python short conditional? References: <pan.2003.09.03.00.16.45.270773@countersnipe.com> Message-ID: <roy-9BB785.20175502092003@reader2.panix.com> Pieter Claassen <pieter at countersnipe.com> wrote: > I am looking to find a short conditional for python equivalent > to the perl question mark operator > > statement? if true:else false There is no such ternary operator in Python. There was a HUGE debate earlier this year about possibly adding it. To make a very long story short, it's not going to happen. Look up PEP-308 for more details. From jjl at pobox.com Sat Sep 6 19:00:39 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Sep 2003 00:00:39 +0100 Subject: Why python??? References: <mailman.1062790509.19411.python-list@python.org> <bjarq6$j45$00$1@news.t-online.com> <NO66b.30883$R32.926812@news2.tin.it> <bjb4hk$ohm$01$1@news.t-online.com> <87fzjalogu.fsf@pobox.com> <bjccn3$eb$07$1@news.t-online.com> <87vfs6unsx.fsf@pobox.com> <bjcstg$plc$04$1@news.t-online.com> Message-ID: <87iso5plns.fsf@pobox.com> "Michael Peuser" <mpeuser at web.de> writes: > "John J. Lee" <jjl at pobox.com> schrieb im Newsbeitrag > news:87vfs6unsx.fsf at pobox.com... [...] > > > I know this argument well and have repeated it myself in the days of Pascal > > > and Algol68. Few have listened..... > > > Well, they'd be right not to listen if you argued it about Pascal. > > There's a real difference in productivity between Pascal and Python. > > Pascal doesn't even have built-in garbage collection, for heaven's > > sake, which places it much closer to C than to Python in this respect. > > I said "in the time of Pascal and Algol 68". If you kindly would consult a > calender you will find out that had been 35 years ago. Pascal had been [...] Oh, sorry, I thought the comparison you were making was between C and (Algol or Pascal). I guess C hadn't quite happened then... John From manuelbastioni at tin.it Tue Sep 9 04:01:56 2003 From: manuelbastioni at tin.it (Manuel Bastioni) Date: Tue, 09 Sep 2003 08:01:56 GMT Subject: Get the date of last modification of a file References: <rE27b.45940$R32.1458201@news2.tin.it> <3F5CBAB8.F8888E3@engcorp.com> Message-ID: <UNf7b.48792$R32.1584881@news2.tin.it> > > It's possible using only a built-in module? > > os.path.getmtime() ... >>> import os, stat >>> s = os.stat("c:/tmp") os isn't built-in :-( Thx, Manuel From robin at jessikat.fsnet.co.uk Sat Sep 20 16:14:55 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 20 Sep 2003 21:14:55 +0100 Subject: spam killing with poplib References: <pan.2003.09.20.06.52.21.266409@webone.com.au> <S02bb.43098$NM1.7449@newsread2.news.atl.earthlink.net> Message-ID: <BPpREWA$ULb$Ewt$@jessikat.fsnet.co.uk> In article <S02bb.43098$NM1.7449 at newsread2.news.atl.earthlink.net>, Phil Weldon <pweldon at mindspring.com> writes >At best that will identify less than a third of the messages produced by >this worm. A permutating and mutating bogus 'Undeliverable e-mail' message >carrying the infection package is more common than the HTML message. Either >type is over 100 KBytes, and will quickly clog a mailbox. > >Expect the HTML message body, FROM and SUBJECT to mutate also. > >Phil Weldon, pweldon at mindspring.com > >"Simon Burton" <simonb at webone.com.au> wrote in message >news:pan.2003.09.20.06.52.21.266409 at webone.com.au... >> >> This was so easy :) >> >> Simon Burton. .... you're right, I had to use patterns like re.compile('^subject:\s*((Microsoft|MS|Upgrade|Net|Network|New|Newest| Latest|Last|Critical|Patch|Pack|internet|security|current|update)\s*)+$' ,re.IGNORECASE) and check the from value as well. Even so I'm not getting all of them and as you say mutation is happening. -- Robin Becker From john at rygannon.com Thu Sep 11 05:17:14 2003 From: john at rygannon.com (John Dean) Date: Thu, 11 Sep 2003 09:17:14 GMT Subject: Problems with setting up mod_python and Apache References: <3f5f6b41$0$239$fa0fcedb@lovejoy.zen.co.uk> <4zK7b.11532$NW3.6643@news1.central.cox.net> <jXO7b.14165$NW3.10353@news1.central.cox.net> Message-ID: <3f603db5$0$199$fa0fcedb@lovejoy.zen.co.uk> Hi Dave Thank you very much for your reply I only have one copy of httpd.conf, since I am working on a development machine and I only have the one directory. Once I have things working this will obviously change. Now that I have enabled debugging I am getting something meaningful. Below is the output from the error handler Mod_python error: "PythonHandler test" Traceback (most recent call last): File "/usr/lib/python2.2/site-packages/mod_python/apache.py" line 185, in Dispatch object = resolve_object(req, module, object_str, silent) File "/usr/lib/python2.2/site-packages/mod_python/apache.py" line 394, in resolve_object raise AttributeError s AttributeError: module 'srv/www/htdocs.test.py' contains no handler It is obvious from the above that I need to read the mod_python docs again and this time more thoroughly Apologies for not sending my last reply to the list. I must have hit the wrong button -- Best Regards John From my at mail.ru Wed Sep 17 04:39:48 2003 From: my at mail.ru (Kerim) Date: Wed, 17 Sep 2003 12:39:48 +0400 Subject: Can Python Module Locate Itself? References: <VYR9b.1109$c17.866@newssvr24.news.prodigy.com> <mailman.1063781182.18892.python-list@python.org> Message-ID: <3f681dd6@shknews01> Try this: print 'usage:', __file__ Kerim From aahz at pythoncraft.com Tue Sep 23 12:34:56 2003 From: aahz at pythoncraft.com (Aahz) Date: 23 Sep 2003 12:34:56 -0400 Subject: General Password questions References: <mailman.1064266830.20157.python-list@python.org> <pan.2003.09.23.13.26.53.712668@riquito.matrix> <3F704A91.FA7D31F7@engcorp.com> <pan.2003.09.23.16.02.35.675695@riquito.matrix> Message-ID: <bkpsng$knm$1@panix1.panix.com> In article <pan.2003.09.23.16.02.35.675695 at riquito.matrix>, Riccardo Attilio Galli <riquito at riquito.matrix> wrote: > >I think you have misunderstood me(mmm, I hope it sound polite enough in >english). An user should never enter the password again. I know how hashes >work, and they're useful when I can compare an entered password with an >hash value, but here I need that the user don't enter a password anymore >(after the first time). > >The natural use of the program would be: >run the e-mail client for the first time >user enter his e-mail password >the client check for new mails >user close the client. > >while 1: > user run the e-mail client > the client check for new mails WITHOUT ask for a password > user close the client This is extremely difficult to do in a secure way. What you need to do is encrypt the e-mail password before storage; each time the user starts the e-mail application, zie needs to enter the local password. There are other less secure options, all of which (with some partial exceptions) equate to "no security" from the perspective of a security professional. (E.g. relying on the OS to keep the data secure.) Python does not make encryption available in its "batteries included" philosophy because of the legal problems. M2Crypto is probably the module most often used; see also http://www.amk.ca/python/code/crypto.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From merman at snafu.de Mon Sep 29 10:59:18 2003 From: merman at snafu.de (T. Kaufmann) Date: Mon, 29 Sep 2003 16:59:18 +0200 Subject: Question: Inheritance from a buil-in type Message-ID: <3F7848C6.8070306@snafu.de> Hi there, A simple but important question: How can I initialize a super class (like dict) correctly in my subclass constructor? A sample: class MyClass(dict): def __init__(self): dict.__init__(self) ... Is there a general rule to do this for all buil-in types? Thanks for help. Thomas From tim.parkin at pollenationinternet.com Sun Sep 7 12:09:45 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 17:09:45 +0100 Subject: Comments on Python Redesign In-Reply-To: <v4lmlvkav0fui6trcj39khbevvm9u1u8eh@4ax.com> Message-ID: <001c01c3755a$7a7fd410$0a00a8c0@JASPER> John W Hall > When I view _this_ site in IE6, it has low-contrast text in a small > size, which "view|text size" cannot change. Did I mention it was an image? Tim From geoff at gerrietts.net Thu Sep 11 15:13:34 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 11 Sep 2003 12:13:34 -0700 Subject: OT: Americans love their guns In-Reply-To: <Wx38b.8278$PE6.2683@newsread3.news.pas.earthlink.net> References: <000d01c37870$181e6020$0c02a8c0@Arts> <mailman.1063297012.18608.python-list@python.org> <Wx38b.8278$PE6.2683@newsread3.news.pas.earthlink.net> Message-ID: <20030911191334.GD2085@thoth.homegain.com> Quoting Greg Krohn (ask at me.com): > > "Geoff Gerrietts" <geoff at gerrietts.net> wrote in message > news:mailman.1063297012.18608.python-list at python.org... > > I think that /your freedom/ ends where /my freedom/ begins. Until > > you can guarantee that your weapon will not be used against me by > > your family members or the conqueror thereof, your freedoms to > > shoot what you want as a hobbyist and to exercise catastrophically > > lethal force in home defense are not compelling arguments. > > What freedom of yours does me owning a gun infringe on? Your right > not to worry? > > (I've rewritten that 100 times and it still sounds funny > gramatically. I appologise.) It's funny when you phrase it that way, which I think is a consequence of my poor choice of words. Your /owning/ a gun infringes no /rights/. Its /use/ or /accidental discharge/ in my direction infringes my rights, equal to yours, to life, liberty, and the pursuit of happiness. You simply can't guarantee that your weapon will never accidentally kill me, nor can you guarantee that it will not be stolen or borrowed from you and deployed against me. Let's ignore for a moment that driving a car has utility beyond its potential to be deployed as lethal force, and its entertainment value. To be allowed to do this, you must be licensed. You must carry insurance that protects others against your catastrophically bad decisions. Few argue that this requirement is reasonable. If you purchase a gun, your neighbors are in jeapordy of an accidental mishandling, or a home invasion gone wrong, resulting in destruction of their property or possibly their loved ones. You are undoubtedly not insured against this: hope for their sake the expenses do not exceed your ability to pay. To my mind, gun control does not mean /nobody can have a gun/. Gun control means /gun ownership should be controlled/. I understand that a good many people do not want the society at large, as reflected by the government, to be deciding whether they are fit to carry a .45 in a shoulder rig. Those tend to be the people I don't want to see carrying a .45 in a shoulder rig, because their ideas about 'freedom' and 'responsibility' are clearly skewed. --G. -- Geoff Gerrietts "There is no fate that cannot be <geoff at gerrietts net> surmounted by scorn." --Albert Camus From ofnap at nus.edu.sg Fri Sep 12 10:16:38 2003 From: ofnap at nus.edu.sg (Ajith Prasad) Date: 12 Sep 2003 07:16:38 -0700 Subject: Open MS Excel Spreadsheet with Python References: <mailman.1058229111.12248.python-list@python.org> <221d8dbe.0307160619.2c2943c3@posting.google.com> <221d8dbe.0308150959.b18167c@posting.google.com> Message-ID: <37ee60c8.0309120616.794e2bf1@posting.google.com> Would appreciate any advice on how to get started with the script. Created an empty spreadsheet "test.xls" on drive F. Then at the PythonWin prompt tried and obtained: >>> xlapp=UseExcel("f:\test.xls") Traceback (most recent call last): File "<interactive input>", line 1, in ? File "UseExcel.py", line 16, in __init__ File "<COMObject <unknown>>", line 2, in Open com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "'f:\test.xls' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files on the File menu, make sure that the file has not been renamed, moved, or deleted.", 'C:\\Program Files\\Microsoft Office\\Office10\\1033\\xlmain10.chm', 0, -2146827284), None) Thanks in advance. srijit at yahoo.com wrote in message news:<221d8dbe.0308150959.b18167c at posting.google.com>... > Hello Members, > I would like to share the Python-Excel Interface code. > This is based on sample code from Mark Hammond and Andy Robinson's > "Python Programming on Win32" > I use Python 2.3 and Win32all-157 on a Win 98 machine. > I look forward to feedback on how to improve this code. If I get good > response I may think of putting up this code as a Python recipe in > Activestate. > Once again hats off to Mark Hammond for his excellent Win32all > library. > > Regards, > Srijit > > --------------------------------------------------------------------------- > > import win32com.client.dynamic > > class UseExcel(object): > """Python Excel Interface. It provides methods for accessing the > basic functionality of MS Excel 97/2000 from Python. > > This interface uses dynamic dispatch objects. All necessary constants > are embedded in the code. There is no need to run makepy.py. > """ > __slots__ = ("xlapp", "xlbook") > def __init__(self, fileName=None): > """e.g. xlFile = > useExcel("e:\\python23\myfiles\\testExcel1.xls") > """ > self.xlapp = > win32com.client.dynamic.Dispatch("Excel.Application") > if fileName: > self.xlbook = self.xlapp.Workbooks.Open(fileName) > else: > self.xlbook = self.xlapp.Workbooks.Add() > > def save(self, newfileName=None): > if newfilename: > self.xlbook.SaveAs(newfileName) > else: > self.xlbook.Save() > > def close(self): > self.xlbook.Close(SaveChanges=False) > del self.xlapp > > def show(self): > self.xlapp.Visible = True > > def hide(self): > self.xlapp.Visible = False > > def getcell(self, sheet, cellAddress): > """Get value of one cell. > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > cellAddress - tuple of integers (row, cloumn) or string "ColumnRow" > e.g. (3,4) or "D3" > """ > sht = self.xlbook.Worksheets(sheet) > if (isinstance(cellAddress,str)): > return sht.Range(cellAddress).Value > elif (isinstance(cellAddress,tuple)): > row = cellAddress[0] > col = cellAddress[1] > return sht.Cells(row, col).Value > > def setcell(self, sheet, value, cellAddress, > fontStyle=("Regular",), fontName="Arial", > fontSize=12, fontColor=1): > """Set value of one cell. > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > value - The cell value. it can be a number, string etc. > cellAddress - tuple of integers (row, cloumn) or string "ColumnRow" > e.g. (3,4) or "D3" > fontStyle - tuple. Combination of Regular, Bold, Italic, Underline > e.g. ("Regular", "Bold", "Italic") > fontColor - ColorIndex. Refer ColorIndex property in Microsoft > Excel Visual Basic Reference > """ > sht = self.xlbook.Worksheets(sheet) > if (isinstance(cellAddress,str)): > sht.Range(cellAddress).Value = value > sht.Range(cellAddress).Font.Size = fontSize > sht.Range(cellAddress).Font.ColorIndex = fontColor > for i, item in enumerate(fontStyle): > if (item.lower() == "bold"): > sht.Range(cellAddress).Font.Bold = True > elif (item.lower() == "italic"): > sht.Range(cellAddress).Font.Italic = True > elif (item.lower() == "underline"): > sht.Range(cellAddress).Font.Underline = True > elif (item.lower() == "regular"): > sht.Range(cellAddress).Font.FontStyle = "Regular" > sht.Range(cellAddress).Font.Name = fontName > elif (isinstance(cellAddress,tuple)): > row = cellAddress[0] > col = cellAddress[1] > sht.Cells(row, col).Value = value > sht.Cells(row, col).Font.FontSize = fontSize > sht.Cells(row, col).Font.ColorIndex = fontColor > for i, item in enumerate(fontStyle): > if (item.lower() == "bold"): > sht.Range(cellAddress).Font.Bold = True > elif (item.lower() == "italic"): > sht.Range(cellAddress).Font.Italic = True > elif (item.lower() == "underline"): > sht.Range(cellAddress).Font.Underline = True > elif (item.lower() == "regular"): > sht.Range(cellAddress).Font.FontStyle = "Regular" > sht.Cells(row, col).Font.Name = fontName > > def getrange(self, sheet, rangeAddress): > """Returns a tuple of tuples from a range of cells. Each tuple > corresponds to a row in excel sheet. > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > rangeAddress - tuple of integers (row1,col1,row2,col2) or > "cell1Address:cell2Address" > row1,col1 refers to first cell > row2,col2 refers to second cell > e.g. (1,2,5,7) or "B1:G5" > """ > sht = self.xlbook.Worksheets(sheet) > if (isinstance(rangeAddress,str)): > return sht.Range(rangeAddress).Value > elif (isinstance(rangeAddress,tuple)): > row1 = rangeAddress[0] > col1 = rangeAddress[1] > row2 = rangeAddress[2] > col2 = rangeAddress[3] > return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, > col2)).Value > > def setrange(self, sheet, topRow, leftCol, data): > """Sets range of cells with values from data. data is a tuple > of tuples. > Each tuple corresponds to a row in excel sheet. > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > topRow - row number (integer data type) > leftCol - column number (integer data type) > """ > bottomRow = topRow + len(data) - 1 > rightCol = leftCol + len(data[0]) - 1 > sht = self.xlbook.Worksheets(sheet) > sht.Range(sht.Cells(topRow, leftCol), sht.Cells(bottomRow, > rightCol)).Value = data > return (bottomRow, rightCol) > > def setcellalign(self, sheet, cellAddress, alignment): > """Aligns the contents of the cell. > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > cellAddress - tuple of integers (row, cloumn) or string "ColumnRow" > e.g. (3,4) or "D3" > alignment - "Left", "Right" or "center" > """ > if (alignment.lower() == "left"): > alignmentValue = 2 > elif ((alignment.lower() == "center") or (alignment.lower() == > "centre")): > alignmentValue = 3 > elif (alignment.lower() == "right"): > alignmentValue = 4 > sht = self.xlbook.Worksheets(sheet) > if (isinstance(cellAddress,str)): > sht.Range(cellAddress).HorizontalAlignment = > alignmentValue > elif (isinstance(cellAddress,tuple)): > row = cellAddress[0] > col = cellAddress[1] > sht.Cells(row, col).HorizontalAlignment = alignmentValue > > def addnewworksheetbefore(self, oldSheet, newSheetName): > """Adds a new excel sheet before the given excel sheet. > > Description of parameters (self explanatory parameters are not > described): > oldSheet - Name of the sheet before which a new sheet should > be inserted > newSheetName - Name of the new sheet > """ > sht = self.xlbook.Worksheets(oldSheet) > self.xlbook.Worksheets.Add(sht).Name = newSheetName > > def addnewworksheetafter(self, oldSheet, newSheetName): > """Adds a new excel sheet after the given excel sheet. > > Description of parameters (self explanatory parameters are not > described): > oldSheet - Name of the sheet after which a new sheet should > be inserted > newSheetName - Name of the new sheet > """ > sht = self.xlbook.Worksheets(oldSheet) > self.xlbook.Worksheets.Add(None,sht).Name = newSheetName > > def insertchart(self, sheet, left, top, width, height): > """Creates a new embedded chart. Returns a ChartObject object. > Refer Add Method(ChartObjects Collection) in Microsoft Excel Visual > Basic Reference. > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > left, top - The initial coordinates of the new object (in > points), relative to the upper-left corner of cell A1 on a worksheet > or to the upper-left corner of a chart. > width, height - The initial size of the new object, in points. > point - A unit of measurement equal to 1/72 > inch. > """ > sht = self.xlbook.Worksheets(sheet) > return sht.ChartObjects().Add(left, top, width, height) > > def plotdata(self, sheet, dataRanges, chartObject, chartType, > plotBy=None, > categoryLabels=1, seriesLabels=0, > hasLegend=None, title=None, > categoryTitle=None, valueTitle=None, > extraTitle=None): > """Plots data using ChartWizard. For details refer ChartWizard > method in Microsoft Excel Visual Basic Reference. > Before using PlotData method InsertChart method should be used. > > Description of parameters: > sheet - name of the excel worksheet. This name should be same > as that in InsertChart method > dataRanges - tuple of tuples ((topRow, leftCol, bottomRow, > rightCol),). Range of data in excel worksheet to be plotted. > chartObject - Embedded chart object returned by InsertChart method. > chartType - Refer plotType variable for available options. > For remaining parameters refer ChartWizard method in Microsoft Excel > Visual Basic Reference. > """ > sht = self.xlbook.Worksheets(sheet) > if (len(dataRanges) == 1): > topRow, leftCol, bottomRow, rightCol = dataRanges[0] > source = sht.Range(sht.Cells(topRow, leftCol), > sht.Cells(bottomRow, rightCol)) > elif (len(dataRanges) > 1): > topRow, leftCol, bottomRow, rightCol = dataRanges[0] > source = sht.Range(sht.Cells(topRow, leftCol), > sht.Cells(bottomRow, rightCol)) > for count in range(len(dataRanges[1:])): > topRow, leftCol, bottomRow, rightCol = > dataRanges[count+1] > tempSource = sht.Range(sht.Cells(topRow, leftCol), > sht.Cells(bottomRow, rightCol)) > source = self.xlapp.Union(source, tempSource) > plotType = { > "Area" : 1, > "Bar" : 2, > "Column" : 3, > "Line" : 4, > "Pie" : 5, > "Radar" : -4151, > "Scatter" : -4169, > "Combination" : -4111, > "3DArea" : -4098, > "3DBar" : -4099, > "3DColumn" : -4100, > "3DPie" : -4101, > "3DSurface" : -4103, > "Doughnut" : -4120, > "Radar" : -4151, > "Bubble" : 15, > "Surface" : 83, > "Cone" : 3, > "3DAreaStacked" : 78, > "3DColumnStacked" : 55 > } > gallery = plotType[chartType] > format = None > chartObject.Chart.ChartWizard(source, gallery, format, plotBy, > categoryLabels, seriesLabels, hasLegend, title, categoryTitle, > valueTitle, extraTitle) > > def copyrange(self,source, destination): > """Copy range of data from source range in a sheet to > destination range in same sheet or different sheet > > Description of parameters (self explanatory parameters are not > described): > source - tuple (sheet, rangeAddress) > sheet - name of the excel sheet > rangeAddress - "cell1Address:cell2Address" > destination - tuple (sheet, destinationCellAddress) > destinationCellAddress - string "ColumnRow" > """ > sourceSht = self.xlbook.Worksheets(source[0]) > destinationSht = self.xlbook.Worksheets(destination[0]) > sourceSht.Range(source[1]).Copy(destinationSht.Range(destination[1])) > > def copychart(self, sourceChartObject, destination,delete="N"): > """Copy chart from source range in a sheet to destination > range in same sheet or different sheet > > Description of parameters (self explanatory parameters are not > described): > sourceChartObject - Chart object returned by InsertChart method. > destination - tuple (sheet, destinationCellAddress) > sheet - name of the excel > worksheet. > destinationCellAddress - string "ColumnRow" > if sheet is omitted and only > destinationCellAddress is available as string data then same sheet is > assumed. > delete - "Y" or "N". If "Y" the source chart object is > deleted after copy. > So if "Y" copy chart is equivalent to move > chart. > """ > if (isinstance(destination,tuple)): > sourceChartObject.Copy() > sht = self.xlbook.Worksheets(destination[0]) > sht.Paste(sht.Range(destination[1])) > else: > sourceChartObject.Chart.ChartArea.Copy() > destination.Chart.Paste() > if (delete.upper() =="Y"): > sourceChartObject.Delete() > > def hidecolumn(self, sheet, col): > """Hide a column. > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet. > col - column number (integer data) > """ > sht = self.xlbook.Worksheets(sheet) > sht.Columns(col).Hidden = True > > def hiderow(self, sheet, row): > """ Hide a row. > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet. > row - row number (integer data) > """ > sht = self.xlbook.Worksheets(sheet) > sht.Rows(row).Hidden = True > > def excelfunction(self, sheet, range, function): > """Access Microsoft Excel worksheet functions. Refer > WorksheetFunction Object in Microsoft Excel Visual Basic Reference > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > range - tuple of integers (row1,col1,row2,col2) or > "cell1Address:cell2Address" > row1,col1 refers to first cell > row2,col2 refers to second cell > e.g. (1,2,5,7) or "B1:G5" > For list of functions refer List of Worksheet Functions > Available to Visual Basic in Microsoft Excel Visual Basic Reference > """ > sht = self.xlbook.Worksheets(sheet) > if isinstance(range,str): > xlRange = "(sht.Range(" + "'" + range + "'" + "))" > elif isinstance(range,tuple): > topRow = range[0] > leftColumn = range[1] > bottomRow = range[2] > rightColumn = range[3] > xlRange = "(sht.Range(sht.Cells(topRow, leftColumn), > sht.Cells(bottomRow, rightColumn)))" > xlFunction = "self.xlapp.WorksheetFunction." + function + > xlRange > return eval(xlFunction, globals(), locals()) > > def clearrange(self, sheet, rangeAddress, contents="Y", > format="Y"): > """Clear the contents of a range of cells. > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > rangeAddress - tuple of integers (row1,col1,row2,col2) or > "cell1Address:cell2Address" > row1,col1 refers to first cell > row2,col2 refers to second cell > e.g. (1,2,5,7) or "B1:G5" > contents - "Y" or "N". If "Y" clears the formulas from the > range > format - "Y" or "N". If "Y" clears the formatting of the > object > """ > sht = self.xlbook.Worksheets(sheet) > if (isinstance(rangeAddress,str)): > if (format.upper() == "Y"): > sht.Range(rangeAddress).ClearFormats() > if (contents.upper() == "Y"): > sht.Range(rangeAddress).ClearContents() > elif (isinstance(rangeAddress,tuple)): > row1 = rangeAddress[0] > col1 = rangeAddress[1] > row2 = rangeAddress[2] > col2 = rangeAddress[3] > if (format.upper() == "Y"): > sht.Range(sht.Cells(row1, col1), sht.Cells(row2, > col2)).ClearFormats() > if (contents.upper() == "Y"): > sht.Range(sht.Cells(row1, col1), sht.Cells(row2, > col2)).ClearContents() > > def addcomment(self, sheet, cellAddress, comment=""): > """Add or delete comment to a cell. If parameter comment is > None, delete the comments > > Description of parameters (self explanatory parameters are not > described): > sheet - name of the excel worksheet > cellAddress - tuple of integers (row, cloumn) or string "ColumnRow" > e.g. (3,4) or "D3" > comment - String data. Comment to be added. If None, delete > comments > """ > sht = self.xlbook.Worksheets(sheet) > if (isinstance(cellAddress,str)): > if (comment != None): > sht.Range(cellAddress).AddComment(comment) > else: > sht.Range(cellAddress).ClearComments() > elif (isinstance(cellAddress,tuple)): > row1 = cellAddress[0] > col1 = cellAddress[1] > if (comment != None): > sht.Cells(row1, col1).AddComment(comment) > else: > sht.Cells(row1, col1).ClearComments() > > def excelapp(): > xlFile = UseExcel("e:\\python23\myfiles\\StudentTabulation.xls") > xlFile.show() > xlFile.setcell(sheet="Sheet1", value="Class X Annual > Examination",fontName="Arial", > cellAddress="D1",fontColor=1, > fontStyle=("Bold",), fontSize=16) > xlFile.setcell(sheet="Sheet1", value="Subject : History", > fontName="Arial", > cellAddress="D3",fontColor=1) > data = ( > ("Sl. No." ,"Name of Students", "Roll No.", > "Marks(out of 100)"), > (1 ,"John" ,1020, 52), > (2 ,"Nikhil" ,1021, 75), > (3 ,"Stefen" ,1025, 85), > (4 ,"Thomas" ,1026, 54), > (5 ,"Ali" ,1027, 87), > (6 ,"Sanjay" ,1028, 0) > ) > (bottomRow, rightCol) = xlFile.setrange("Sheet1", 5,2,data) > xlFile.addcomment("sheet1", "C11", "Absent") > chrt1 = xlFile.insertchart("sheet2", 100, 100, 400, 200) > xlFile.plotdata(sheet="sheet1",dataRanges=((6,3,bottomRow,5),), > chartObject=chrt1, > title="Annual Examination : History", plotBy=2, > categoryLabels=1, > seriesLabels=0, chartType="Bar") > #~ xlFile.clearrange("sheet1",(3,2,3,5),"y") > #~ xlFile.addcomment("sheet1", "B4", "Test Comment") > #~ chrt1 = xlFile.insertchart("sheet1", 100, 100, 400, 250) > #~ xlFile.plotdata(sheet="sheet1",dataRange=(4,2,bottomRow, > rightCol), chartObject=chrt1, > #~ title="Test Chart", chartType="Column") > #~ xlFile.copyrange(("sheet1","C3:E3"), ("sheet2", "C3")) > #~ chrt2 = xlFile.insertchart("sheet2", 100, 100, 400, 250) > #~ xlFile.movechart(chrt1,chrt2) > #~ xlFile.copychart(chrt1,("sheet3","D22"), "y") > #~ xlFile.hiderow("sheet1",7) > #~ print xlFile.excelfunction("sheet1", (3,2,3,5), "Min") > #~ print xlFile.getrange("sheet1","A2","C3") > #~ xlFile.setcellfont("sheet1","Regular", "A1") > #~ cellVal1 = xlFile.getcell("sheet1","A1") > #~ xlFile.setcell("sheet1", cellVal1,1,3) > #~ xlFile.setcellfont("sheet1","bold","C1") > #~ xlFile.setcellfont("sheet1","italic",1,3) > #~ xlFile.setcellfont("sheet1","underline",1,3) > #~ xlFile.setcellalign("sheet1","left",1,3) > #~ print xlFile.getrange("sheet1", "D5", "F6") > #~ xlFile.setrange("sheet1", 10,10, > ((45,67),(67,"342"),(88,66.8),(32,77),(3,3))) > #~ xlFile.addnewworksheetafter("sheet1", "Srijit1") > > if (__name__ == "__main__"): > excelapp() > > > --------------------------------------------------------------------------- > > srijit at yahoo.com wrote in message news:<221d8dbe.0307160619.2c2943c3 at posting.google.com>... > > Hi, > > I am working on Python-Excel interface based on the excellent library > > win32com. > > I was planning to put it up as a Python recipe in Activestate. > > Anyway before that I shall personally send you the code after some > > cleanup. It will be good to get an early feedback before I upload it > > in Activestate. > > > > Regards, > > Srijit > > > > "Allison Bailey" <allisonb at terralogicgis.com> wrote in message news:<mailman.1058229111.12248.python-list at python.org>... > > > Hi Folks, > > > > > > I'm a brand new Python programmer, so please point me in the right > > > direction if this is not the best forum for this question.... > > > > > > I would like to open an existing MS Excel spreadsheet and extract > > > information from specific worksheets and cells. > > > > > > I'm not really sure how to get started with this process. > > > I ran the COM Makepy utility from my PythonWin (IDE from ActiveSTate), > > > using Microsoft Excel 10.0 Object Library, then > > > import win32com.client > > > xl = win32com.client.Dispatch("Excel.Application") > > > wb = xl.Workbooks.Open ("c:\\data\\myspreadsheet.xls") > > > > > > Then, I get errors when I try the following: > > > sh = wb.worksheets(1) > > > > > > > > > I think I'm missing something fairly fundamental, but I've googled all > > > over the place and can't seem to find anything very introductory about > > > opening and using data from MS Excel using Python. Any suggestions, > > > including places to get more information are welcome. > > > > > > Also, do I need to run the makepy utility every time I run my script? > > > If so, how would I do it from within my Python program, rather than with > > > the GUI in the IDE? > > > > > > Thanks for your help, > > > > > > Allison > > > > > > > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > Allison Bailey > > > TerraLogic GIS, Inc. > > > allisonb at terralogicgis.com > > > 425-673-4495 > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From __peter__ at web.de Thu Sep 25 10:28:44 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2003 16:28:44 +0200 Subject: adodbapi / string encoding problem References: <bkuku2$qm5$04$1@news.t-online.com> <bkumfg$ifj$01$1@news.t-online.com> <bkuoeb$kbt$01$1@news.t-online.com> Message-ID: <bkuu57$pc6$01$1@news.t-online.com> Achim Domma wrote: >> You have to know the encoding of the original file. > > Why? It's of type 'str' and I would expect that I could write it to DB and > get the same 'str' back. That's all I want. Why is it required do know the > encoding? str is essentially a sequence of bytes that can store the same content in different ways: >>> utf8 = u"?".encode("utf8") >>> latin = u"?".encode("latin1") >>> latin '\xe4' >>> utf8 '\xc3\xa4' >>> Now imagine you store the latter byte sequence in your database and want to display it in your windows editor >>> print utf8 ?? (you should see two strange characters) I had this problem occasionally when I edited python scripts with idle and, oddly enough, my old c++ builder 3 ide. To avoid such ambiguities, unicode is introduced. Now I guess that the first conversion, when your string data is fed to the db api, is performed automatically using the default encoding of your environment, which may differ from the encoding of the downloaded file, thus probably messing up some characters. Of course you could store the file in binary form (not in a memo field) in your db and thus bypass all encoding mechanisms, but if you still think that a string is a string is a string, you should reread the above or go for more detailed information on the matter. Peter From andy47 at halfcooked.com Fri Sep 19 06:10:41 2003 From: andy47 at halfcooked.com (Andy Todd) Date: Fri, 19 Sep 2003 11:10:41 +0100 Subject: Python ISPs In-Reply-To: <924a9f9c.0309181224.374a5bef@posting.google.com> References: <924a9f9c.0309181224.374a5bef@posting.google.com> Message-ID: <bkeknn$70f$1@sea.gmane.org> Paradox wrote: > Does anyone know of some ISPs that have Mod_Python installed. Most > seem to allow Python CGI but not things like Mod_Python or Spyce. Is > this a viable solution or should I just learn PHP. I would prefer to > leverage my Python knowledge but I also would like a fast robust > solution. > > Thanks Joey. http://www.python.org/cgi-bin/moinmoin/PythonHosting Regards, Andy -- -------------------------------------------------------------------------------- From the desk of Andrew J Todd esq - http://www.halfcooked.com/ From hungjunglu at yahoo.com Fri Sep 26 13:57:42 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 26 Sep 2003 10:57:42 -0700 Subject: COM Dispatch() and multiple instances Message-ID: <8ef9bea6.0309260957.7d8755da@posting.google.com> Hi, I try win32com.client.Dispatch('InternetExplorer.Application'), and it returns an instance of the running IE object. If there are multiple instances of IE running, how can I make sure I get the one I want? thanks, Hung Jung From tim at remove_if_not_spam.digitig.co.uk Thu Sep 18 13:49:00 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Thu, 18 Sep 2003 18:49:00 +0100 Subject: Money data type References: <mailman.1063901790.24630.python-list@python.org> Message-ID: <iorjmv4dqhbabfepraf3i3ugsg59ot2gaa@4ax.com> On Thu, 18 Sep 2003 13:15:26 -0300, "Batista, Facundo" <FBatista at uniFON.com.ar> wrote: >Anyway, all roads leads to FixedPoint (all roads leads to Trantor, :)) Well, one road leads to BCD, but I don't know of any support for BCD in Python (all I can find from a net search is that it was on the agenda at a Python conference in 2001!) Fancy writing a BCD module? From gh at ghaering.de Mon Sep 15 07:40:38 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 15 Sep 2003 13:40:38 +0200 Subject: I: caching the sql queries In-Reply-To: <003501c37b7c$486781d0$410100a4@utente65> References: <003501c37b7c$486781d0$410100a4@utente65> Message-ID: <3F65A536.3040708@ghaering.de> Luca Calderano wrote: > I MEAN YOU CAN ACCESS ADO TROUGHT COM > AS EXPLAINED HERE: [...] No need to shout. This is all fine and dandy, but perhaps you should look at the link the OP posted ;-) Considering you have database experience as well, I'd be interested in hearing your opinion about something like this. I personally find it awful :-D -- Gerhard From yorklee70 at yahoo.com Thu Sep 11 07:41:48 2003 From: yorklee70 at yahoo.com (York) Date: Thu, 11 Sep 2003 12:41:48 +0100 Subject: Debug python programs Message-ID: <bjpn2s$8bh$1@pegasus.csx.cam.ac.uk> Hi, anybody, Would you please recommend some good softwares/methods for tracking/debugging python codes. Thanks, York From peter at engcorp.com Fri Sep 26 08:46:34 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 26 Sep 2003 08:46:34 -0400 Subject: When did Windows start accepting forward slash as a path separator? References: <b16e4ef7.0309251550.724a57f@posting.google.com> <mailman.1064540736.16016.python-list@python.org> <2aNcb.3620$RW4.1866@newsread4.news.pas.earthlink.net> Message-ID: <3F74352A.5E50B2B5@engcorp.com> Andrew Dalke wrote: > > Bob Gailer: > > Good question. Certainly later than: > > > > Microsoft Windows 2000 [Version 5.00.2195] > > (C) Copyright 1985-2000 Microsoft Corp. > > > > C:\>cd /samis > > The syntax of the command is incorrect. > > The shell is parsing the line and interprets the "/" as a > command-line flag, Try a relative path, like > > cd ./samis And of course, there's always: C:\>ver Windows 98 [Version 4.10.2222] C:\>cd ./temp Too many parameters - /TEMP C:\>cd ./temp" Too many parameters - /TEMP" C:\>cd "./temp" C:\> But I digress... *you* guys were talking about operating systems. ;-) -Peter From medved at fcc.net Thu Sep 4 14:50:51 2003 From: medved at fcc.net (ted holden) Date: Thu, 04 Sep 2003 14:50:51 -0400 Subject: Zope locking Message-ID: <ZqednXzZPebV8MqiXTWJhg@fcc.net> Dumb question here. Every once in a while, while playing around with or experimenting with Zope, I either get clumsy with my hands and don't click something thoroughly enough or I do some combination of things which Zope can't deal with (this is on the manage screen), and the thing locks up. All I've been able to do so far when that happens is to break out of zope, kill any zope processes lying around, and delete the lock file which gets created in the var subdirectory. I assume there's got to be some better way, i.e. some step I could take from the manage screen which would unhang or unlock the system. I'd appreciate hearing from anybody who knows what that might be. Ted Holden medved at fcc.net From nomail at nomail.com Tue Sep 9 13:14:29 2003 From: nomail at nomail.com (Michael Schmitt) Date: Tue, 09 Sep 2003 19:14:29 +0200 Subject: Errors while compiling SWIG wrappers on Solaris Message-ID: <bjl1pm$2oi99$1@hades.rz.uni-saarland.de> Hello. I am trying to compile SWIG wrappers for the Python interface of libsvm on SunOS 5.9, using g++ 3.2.1. I constantly get "relocations remain" error from the linker. I tried some hints I found on the web: "-shared" for compiling and linking. "-fPIC". "-Wl,-G". But none of these (also in combinations) worked. Any ideas? Thanks for any help. Michael -------------------- Text relocation remains referenced against symbol offset in file <unknown> 0x2610 ../svm.o <unknown> 0x2614 ../svm.o . . . ld: fatal: relocations remain against allocatable but non-writable sections collect2: ld returned 1 exit status *** Error code 1 make: Fatal error: Command failed for target `svmc.so' From __peter__ at web.de Wed Sep 17 10:51:58 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Sep 2003 16:51:58 +0200 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <bk80n3$rsb$03$1@news.t-online.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> Message-ID: <bk9sfo$55q$06$1@news.t-online.com> Hilde Roth wrote: > Thanks for the suggestion but zip is not nice for large lists > and as for array/numpy, although I chose a numeric example in > the posting, I don't see why only numeric arrays should enjoy > the benefit of such a notation. > > l[;0] is illegal right now but does anyone of any other bit > of syntax it might conflict with if proposed as an extension? I think that in alist[from:to:step] the step argument is already overkill. If there is sufficient demand for column extraction, I would rather make it a method of list, as alist[:columnIndex] can easily be confused with alist[;toIndex] (or was it the other way round :-). Would you allow slicing, too, or make slicing and column extraction mutually exclusive? Here's how to extract rows 2,4,6 and then columns 4 to 5: m = n[2:7:2;4:6] # not valid python Also, ";" is already used (though seldom found in real code) as an alternate way to delimit statements. So your suggestion might further complicate the compiler without compelling benefits over the method approach. Peter From tjreedy at udel.edu Sun Sep 7 14:29:09 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 7 Sep 2003 14:29:09 -0400 Subject: Comments on Python Redesign References: <mailman.1062934990.9290.python-list@python.org> Message-ID: <p3idnVDIPrJm5caiU-KYgg@comcast.com> To the extent that my comments were misdirected and/or unwarrented, I retract and/or apologize. I did not notice that the demo fromt page is merely a dead image. I was mislead by the word 'mock-up'. To me, a mock-up page would have real html, even if filled with dummy text and stub links. While a mock-up airplane does not fly , it is a real 3-d object, not an image. In any case, the page looks enough like many live pages I have visited (usually corporation front pages) that I was fooled. The comments page *is* live, not an image. It was also unusually painful and difficult for me to read. I usually don't care too much what people do with their pages. If I can't read it, I move on to one of the millions of others vying for my attention. However, python.org is one I visit a lot (top 5, surely) and I really care about being able to continue reading it. Perhaps Python needs two front pages or even two sites. One for the IT manager types that you seem to be aiming at, who would be impressed by the corporate look that tends to depress me, and one for programmers just looking for info. The current site, perhaps with more tweeks, is pretty good for the latter but not, I would agree, for the former. Terry J. Reedy From __peter__ at web.de Mon Sep 22 10:29:53 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Sep 2003 16:29:53 +0200 Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale related?)) References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> <bkk4h1$9ke$06$1@news.t-online.com> <mailman.1064154389.29357.python-list@python.org> <bkmd4q$t13$05$1@news.t-online.com> <DUCbb.100826$hE5.3550910@news1.tin.it> Message-ID: <bkn12v$tns$06$1@news.t-online.com> Alex Martelli wrote: >> Everytime that someone posts a naive list.sort(compare), the DSU pattern >> is proposed to improve execution speed. >> >> So maybe it's about time to change the sort() method to support a second >> argument >> >> list.sort(compare=None, mapping=None) >> >> that, if provided, would perform the DSU magic. Or was that already >> proposed and rejected? > > I have not seen this proposed before, and I'm not very clear on what > the "compare" and "mapping" arguments are supposed to be in order to > let you specify any DSU. Basically it seems you would need two > callables, "decorate" to be called with each item in the list (to > return for each item the decorated tuple) and "undecorate" to be > called with each decorated tuple after the sort (to return the item > for the result). How do you turn that into "compare" and "mapping"? My first idea was to add a .dsu(mapping) where the tuples in the decoration phase would be generated as (mapping(item), item). But I would rather enhance the already-existing sort() to provide for both the traditional and the dsu sorting. Then you have to detect if the function passed to sort(fun) takes one or two arguments, which is not reliable when default values come into play. So I resorted to named arguments. Didn't make it any clearer? So here is a pure python prototype to shed some light on the matter: class dsu(list): def sort(self, compare=None, mapping=None): if mapping: decorated = [(mapping(i), i) for i in self] decorated.sort() self[:] = [i[1] for i in decorated] else: list.sort(self, compare) sample = dsu("ab Aa AC d e f".split()) # "traditional" sort sample.sort(lambda s, t: -cmp(s, t)) print sample # decorate-sort-undecorate sample.sort(mapping=lambda s: s.lower()) print sample Peter From peter at engcorp.com Sat Sep 20 15:47:34 2003 From: peter at engcorp.com (Peter Hansen) Date: Sat, 20 Sep 2003 15:47:34 -0400 Subject: bizarre behavior using .lstrip References: <681f9321.0309191607.4e8b858a@posting.google.com> <3F6B9B44.9EAD3CF9@engcorp.com> <j8mdnRu0dsXxR_aiU-KYjQ@comcast.com> Message-ID: <3F6CAED6.8B2A4ED@engcorp.com> Terry Reedy wrote: > > "Peter Hansen" <peter at engcorp.com> wrote in message > news:3F6B9B44.9EAD3CF9 at engcorp.com... > > > Does this make any sense at all? where did the lead c in conn_fee > go? > > > > Based on the behaviour you describe, I would assume lstrip() > > removes, starting at the beginning of the string, all characters > > which are *anywhere* in the argument string you give it, until > > it encounters a character not in that string, at which point it > > stops. > > Good call: from Lib Ref 2.2.6.1 String Methods > > lstrip( [chars]) > > Return a copy of the string with leading characters removed. If chars > is omitted or None, whitespace characters are removed. If given and > not None, chars must be a string; the characters in the string will be > stripped from the beginning of the string this method is called on. I think that last phrase might be responsible for the OP's confusion. Even now my brain interprets it as meaning the *string* formed by those characters will be removed from the beginning of the string, not that each occurrence of any character in that arg string will be removed from the target. -Peter From mleeds at mlp.com Sat Sep 13 16:51:16 2003 From: mleeds at mlp.com (Leeds, Mark) Date: Sat, 13 Sep 2003 16:51:16 -0400 Subject: stripping a string Message-ID: <C497480353EF904FBF7A8B0851E5422C9F7BB1@MAIL002.AD.MLP.COM> hello : i am very much a python novice because I only use it for preprocessing data that i send into another language called Splus. I have the following problem that I have spent a lot of time on but I can't figure out. I have a string called tickerstring that might be "ANL LN32" and i want to get rid of the digit piece. so that i get "ANL LN" i can't just take off the last two charcters because the string could also be "ANL LN3" for example. thanks to anyone who could explain how to do this ? mark -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20030913/106dde16/attachment.html> From tjreedy at udel.edu Wed Sep 24 17:41:45 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2003 17:41:45 -0400 Subject: RELEASED Python 2.3.1 References: <mailman.1064390741.20344.python-list@python.org> <bksmrs$1u0$1@news2.tilbu1.nb.home.nl> Message-ID: <wuWcnZEWT_4Eku-iXTWJhQ@comcast.com> "vincent wehren" <vincent at visualtrans.de> wrote in message news:bksmrs$1u0$1 at news2.tilbu1.nb.home.nl... > Than why does the documentation (at least the Windows CHM-one) repeat the > claim: > "Release 2.4a0, documentation updated on 23 September 2003." on each page! > ;) Because of a glitch in the release process that wasn't noticed until just after the release, and because it was not seen as serious enough to withdraw until redone. The main development line for Python *is* the future 2.4a0 release. Some or most bug-fix only patches (including doc patches) were backported to the 2.3 maintainance branch (of CVS repository) to make this release. Somehow, one thing too many got backported ;-). Terry J. Reedy From avera at coes.org.pe Wed Sep 24 21:45:28 2003 From: avera at coes.org.pe (Alberto Vera) Date: Wed, 24 Sep 2003 20:45:28 -0500 Subject: getting a value from a web-page Message-ID: <000d01c38306$b2888640$1603a8c0@pc22> Hello: Is it possible to get a row from a text-file? This text-file is located in a web page. And a value from an excel located in a web-server? (Sheet1!cell A1) Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20030924/29b26cc0/attachment.html> From newsgroups at jhrothjr.com Thu Sep 25 12:40:10 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 25 Sep 2003 12:40:10 -0400 Subject: pythonwin from dos References: <3f731176.33482654@powernews.libero.it> Message-ID: <vn66jje743n725@news.supernews.com> "Alberto Mantovani" <alberto.mantovaniNOSPAM at bologna.marelli.it> wrote in message news:3f731176.33482654 at powernews.libero.it... > hi, > how is it possible to run a python script in the pythonwin > environment from dos command line? > If I use the command "/run scriptname.py" and the pythonwin is already > opened I get error, so someone can help me? Why do you want to run it in Pythonwin? To run a script from one of the command lines, the correct command is: python scriptname.py parameters.... Of course, python.exe has to be on the path. John Roth > > thanks > Alberto From anton at vredegoor.doge.nl Sun Sep 7 14:09:16 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 07 Sep 2003 20:09:16 +0200 Subject: Comments on Python Redesign References: <mailman.1062951732.14553.python-list@python.org> Message-ID: <bjfsji$3in$1@news.hccnet.nl> "Tim Parkin" <tim.parkin at pollenationinternet.com> wrote: >>John W Hall >>> When I view _this_ site in IE6, it has low-contrast text in a small >>> size, which "view|text size" cannot change. >> >>Did I mention it was an image? > >Sorry, gotcha now... www.zeldman.com If you're planning to score any success in the open source community you should stop admitting mistakes and stop defending against false accusations. Only yesterday I posted some code with an obvious superflous construct in it, but rather than reply to my own post I would wait and give usenets selfpurging system a chance to correct it. Remember there's no method to get good information that functions as swift as posting false information (even if noone replies to it). Anton From vivek at cs.unipune.ernet.in Fri Sep 12 08:51:48 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Fri, 12 Sep 2003 18:21:48 +0530 Subject: python program not running from different folders In-Reply-To: <004701c37925$5ea86170$3aa2e7c1@integrasoft.ro>; from jboti@integrasoft.ro on Fri, Sep 12, 2003 at 02:59:50PM +0300 References: <001701c3791f$e80fea10$3aa2e7c1@integrasoft.ro> <20030912170828.A4664@cs.unipune.ernet.in> <004701c37925$5ea86170$3aa2e7c1@integrasoft.ro> Message-ID: <20030912182148.A6083@cs.unipune.ernet.in> On Fri, Sep 12, 2003 at 02:59:50PM +0300, Jozsa Boti wrote: > > ----- Original Message ----- > From: <vivek at cs.unipune.ernet.in> > To: "Jozsa Boti" <jboti at integrasoft.ro> > Cc: <python-list at python.org> > Sent: Friday, September 12, 2003 2:38 PM > Subject: Re: python program not running from different folders > > > > On Fri, Sep 12, 2003 at 02:20:43PM +0300, Jozsa Boti wrote: > > > Hi! > > > > > > I have a strange problem: I wrote a program in python, and I get an > error: ImportError: dynamic module does not define init function > (initESSClientAPI) but only if I run the program in certain folders. The > same program runs without any error from other folders. Any ideas? > > > > > > > As u have described it seems that the folder from which u are trying to > run the > > script contains some dll/so which have the same name as one of the modules > u are > > using in your script. > > > > eg. like in your script u have: > > > > import xyz > > #call some function from xyz > > xyz.funct() > > > > here xyz is some python module u are using. > > > > but as the error message says it may be that the particular folder from > which > > the script gives ImportError contains some dll/so with the same name i.e. > > xyz.dll or xyz.so. > > > > Still it is just a wild guess :-) > > > > Regards > > Vivek Kumar > > Thanks for the tip! > This was the problem indeed. I had a dll written in C++, which is needed by > another application, once that dll was removed, the program was running > without any error. > My concern is how can I overcome this error without renaming some files? > > Boti In that case you better place you script in a separate folder and make sure that that particular dll in not in the system path, coz it is mainly a path related problem. When u import a module then first of all the current folder is searched for the module, so if u want to keep ur script and the dll in the same folder then AFAIK u are out of luck. Regards Vivek Kumar From bokr at oz.net Sun Sep 7 23:15:33 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Sep 2003 03:15:33 GMT Subject: Is there a unicode EOF mark like DOS ascii ctl-z or unix crl-d ? References: <bjgf10$d5s$0@216.39.172.122> <3F5BD4DD.57D90AF5@alcyone.com> Message-ID: <bjgs8l$6d0$0@216.39.172.122> On Sun, 07 Sep 2003 18:01:17 -0700, Erik Max Francis <max at alcyone.com> wrote: >Bengt Richter wrote: > >> I couldn't find one. > >Unicode subsumes the normal ASCII control characters, so U0004 is EOT >(end of transmission) just like 0x04 in ASCII is: > > http://www.unicode.org/charts/PDF/U0000.pdf > >Unicode also includes a _symbol_ for it at U2404. > Thanks. I tried EOT on the assumption, but windows console type command doesn't stop on it, much less notepad, so I guess I have to do something else. Regards, Bengt Richter From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 24 01:53:09 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 24 Sep 2003 06:53:09 +0100 Subject: Pre-PEP: reverse iteration methods References: <HA5cb.185$kD3.168@nwrdny03.gnilink.net> Message-ID: <f4b2nv8vs81v6egonckq7935jmh6a8gku6@4ax.com> On Wed, 24 Sep 2003 00:30:31 GMT, "Raymond Hettinger" <vze4rx4y at verizon.net> wrote: >Proposal >======== > >Add a method called iter_backwards() to sequence objects that can benefit >from it. The above examples then simplify to:: > > for i in xrange(n).iter_backwards(): > print seqn[i] > > for elem in seqn.iter_backwards(): > print elem That is a pretty long name. Can we use the convention from itertools where an 'i' prefix is sufficient to suggest an iterator, giving 'ibackwards' or 'ireverse' or similar. Second, I'm not quite ready to drop my property idea ;-) An advantage is that the object returned by the property can sensibly support more than just iteration - e.g. slicing (as touched on in the PEP284 thread). So for instance... >>> x = range(10) >>> list(x.backward) [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> list(x.backward [::2]) [8, 6, 4, 2, 0] >* Should file objects be included? Implementing reverse iteration may not > be easy though it would be useful on occasion. IMO no - doing this essentially needs the whole file to be read into memory, in which case you may as well read the whole file into a list and then iterate the list backwards. >* Should enumerate() be included? It would only provide reverse iteration > whenever the underlying sequence supported it. Why not... for i, j in enumerate (listname.iter_backwards ()) : in other words, as enumerate can handle the already-reversed sequence/iteration, I don't see the point. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From amk at amk.ca Fri Sep 12 07:40:48 2003 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 12 Sep 2003 06:40:48 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911162016.02027750@telecommunity.com> <mailman.1063342640.29560.python-list@python.org> Message-ID: <ipicnag7OpxdLfyiRTvUpQ@speakeasy.net> On Fri, 12 Sep 2003 07:56:55 +0300, Harri Pesonen <fuerte at sci.fi> wrote: > I don't know, I got mail about writing a PEP. It is clear that it would > not be accepted, because it would break the existing API. The change is > so big that I think that it has to be called a different language. It would just be a different implementation of the same language. Jython has different garbage collection characteristics from CPython, but they still implement the same language; Stackless Python is still Python. > because this is too important to be ignored. Python *needs* to be > free-threading... On the other hand, considering that the last free threading packages were for 1.4, and no one has bothered to update them, the community doesn't seem to find the subject as important as you do. :) --amk From hawkfish at trustedmedianetworks.com Mon Sep 8 18:30:45 2003 From: hawkfish at trustedmedianetworks.com (Richard Wesley) Date: 08 Sep 2003 22:30:45 GMT Subject: Massive unit test vs MySQL References: <hawkfish-F6DB4C.13344404092003@tribune.sj.sys.us.xo.net> <mailman.1062774119.18681.python-list@python.org> Message-ID: <hawkfish-96D864.15285508092003@spectator.sj.sys.us.xo.net> In article <mailman.1062774119.18681.python-list at python.org>, Andy Todd <andy47 at halfcooked.com> wrote: > Richard Wesley wrote: > > I don't know if this is really a Python question of a MySQL question, > > but i am hopen that there is enough overlap that someone can help me ;-) > > > > I have a unit test suite for our server that loads a clean database > > image for many of the tests. I use > > > > p = os.popen('mysql -u uid -ppassword mydatabase', 'w') > > p.write(sql_commands) > > > > to load the database. > > > > While the tests are running, I find that mysql has a growing number of > > "Sleeping" threads in the 'show processlist' table. Towards the end of > > the test suite, the database loads start to fail with a MySQL error of > > "ERROR 1040: Too many connections". > > > > So my question would be, is there any way to shut down the child process > > so that MySQL notices and cleans up after itself before it runs out of > > threads? > > > > TIA, > > > > As you aren't using the Python MySQL module and just piping commands to > an OS process then its likely to be a MySQL problem. > > However, its hard to figure out what you're doing wrong because you > don't tell us what you are doing. What, for instance, are the contents > of 'sql_commands'? They are the output of a mysqldump command that was read in from a file. > Generally, if a database complains about too many connections it is > because you are explicitly (and repeatedly) connecting to it and then > not releasing those connections when you are finished with them. Yes, that is the problem, but it is not clear how to release the connections. They get released immediately when the script terminates. I am wondering of it is a gc problem. > Then again, if you are just loading test data into a clean database I'd > suggest using some of the MySQL utilities to back up and restore and not > writing your own code. Have a look at mysqldump > (http://www.mysql.com/doc/en/mysqldump.html) That is what I am doing. -- - rmgw <http://www.trustedmedianetworks.com/> ---------------------------------------------------------------------------- Richard Wesley Trusted Media Networks, Inc. "You miss too much these days if you stop to think." - U2, "Waiting for the End of the World" From mark at hahnca.com Wed Sep 17 20:13:44 2003 From: mark at hahnca.com (Mark Hahn) Date: Wed, 17 Sep 2003 17:13:44 -0700 Subject: wanted($): mac and linux python gui coders for porting References: <EHr9b.36540$n94.18214@fed1read04> <8dsfmvo15uftg7qvc0oivmsg6eeeqelvtm@4ax.com> <6ee58e07.0309170528.9c81592@posting.google.com> <U3%9b.39616$n94.30901@fed1read04> <6ee58e07.0309171554.57e4a44@posting.google.com> Message-ID: <XM6ab.40410$n94.3516@fed1read04> I'm not going to be marketing it. Discussions are under way with several "re-distributors" who would do the actual marketing. Apparently there is money to be made in the $10 "throw-away-money" market. Anyway, I just write it, I don't care who buys it or why. In any case, my understanding is that the intended market is friends and relatives of computer-savvy people, not the computer-savvy people themselves. You may have a big dsl pipe but I'll bet your parents don't. As to whether linux people would use it, that's beyond my understanding. Are there non-computer-savvy people using linux who had their pc set up by others, who could benefit from gut-simple software? I know there are non-gurus using macs. I gave my mom a mac and she is really challenged by AOL. This app would be great for her. As to your problem: What version are you using? I've been fixing bugs like crazy the last few days. I think it is settling down now. Try the latest version. If you still have problems let me know. P.S. If you don't mind, extend the testing all the way to using PayPal. I promise that I'm reversing all charges at the end of beta testing. (I know that may sound suspicious, but I really am honest :) "Lothar Scholz" <llothar at web.de> wrote in message news:6ee58e07.0309171554.57e4a44 at posting.google.com... > "Mark Hahn" <mark at hahnca.com> wrote in message news:<U3%9b.39616$n94.30901 at fed1read04>... > > >With his marketing skills > > > > Whose skills are you reffering to? > > Yours. Maybe a website is on the way, instead of the current simple > page. > > > By the way: The program throws an exception when i want to add a > picture. > > Traceback (most recent call last): > File "<string>", line 378, in OnMouseDown > File "<string>", line 695, in OnAddPhoto > File "C:\Installer\EzPicMailer\buildEzPicMailer\out1.pyz/photochooser_dialog", > line 434, in choose_photo > File "C:\Installer\EzPicMailer\buildEzPicMailer\out1.pyz/photochooser_dialog", > line 392, in __init__ > File "C:\Installer\EzPicMailer\buildEzPicMailer\out1.pyz/photochooser_dialog", > line 288, in set_path > File "C:\Installer\EzPicMailer\buildEzPicMailer\out1.pyz/photochooser_dialog", > line 208, in PaintNow > File "C:\Installer\EzPicMailer\buildEzPicMailer\out1.pyz/photochooser_dialog", > line 222, in paint > File "C:\Installer\EzPicMailer\buildEzPicMailer\out1.pyz/photochooser_dialog", > line 137, in get_bitmap_bigpath > File "<string>", line 522, in save_datastore > IOError: [Errno 2] No such file or directory: 'data/app_datastore.pkl' From llothar at web.de Fri Sep 12 10:04:23 2003 From: llothar at web.de (Lothar Scholz) Date: 12 Sep 2003 07:04:23 -0700 Subject: Internal Debugger Question Message-ID: <6ee58e07.0309120604.3a1f4985@posting.google.com> Hello, i'm currently writing a debugger for python and found that some modules store an absolute file path in "co_filename" of there methods/functions and some store a relative file path. Because the relative file path can never be expanded to an absolute file path later (the sys.path may have changed) it is impossible to find the source code location. Is there anything i have missed or is this simply a bug. I would highly recommend to fix this bug ! From aahz at pythoncraft.com Fri Sep 26 14:13:15 2003 From: aahz at pythoncraft.com (Aahz) Date: 26 Sep 2003 14:13:15 -0400 Subject: PEPs link gone from the Python homepage? References: <un0crhase.fsf@boost-consulting.com> Message-ID: <bl1vjr$fha$1@panix1.panix.com> In article <un0crhase.fsf at boost-consulting.com>, David Abrahams <dave at boost-consulting.com> wrote: > >Since a significant part of Python is only documented in PEPs, I am >disappointed to see that they can't be easily found. Where are they? I've gone ahead and added a link to the /doc/ sidebar. I was the one who argued that if we were reducing the size of the home page, the PEP link should go. Note that there is a /dev/ link in the sidebar, too, listed as "Python Project: bugs, patchs, cvs". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Thu Sep 18 05:06:25 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Thu, 18 Sep 2003 13:06:25 +0400 Subject: how to write-protect names In-Reply-To: <mailman.1063841844.13119.python-list@python.org> References: <3F68C499.1060604@aon.at> <3F68C60C.AC611276@engcorp.com> <3F68CE89.20601@aon.at> <3F68D53B.CE7DF693@engcorp.com> <mailman.1063841844.13119.python-list@python.org> Message-ID: <bkbsih$102e$1@news.peterlink.ru> python wrote: > Can you post a trivial example of how to use __setattr__() and how to > set the namespace in the interpreter? > > Thanks. > > Really basic one: class Namespace(object): def __setattr__(self, name, value): if name in self.__dict__: raise "oops" object.__setattr__(self, name, value) util = Namespace() util.x = 1 print util.x util.x = 2 From mwh at python.net Fri Sep 26 14:04:24 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 26 Sep 2003 18:04:24 GMT Subject: why the inconsistency? References: <mailman.1064537919.23612.python-list@python.org> Message-ID: <7h3brt7o2h8.fsf@pc150.maths.bris.ac.uk> "Tim Peters" <tim.one at comcast.net> writes: > [Christos "TZOTZIOY" Georgiou' > >>> If only math.log(2**64)/math.log(10) worked with longs without > >>> converting them into floats first... :( > >> > >> And after reading the FM, if only > >> > >> def count_digits(x): > >> return int(math.log(x, 10)) > >> > >> worked correctly for *all* large values, like 10**70... > > [Michael Hudson] > > Um, it does :-) > > > > >>> float(40**200) > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > OverflowError: long int too large to convert to float > > >>> math.log(40**200, 14) > > 279.56038792470861 > > > > (10**70 is well within the range of an IEEE double). > > You're not used to answering floating-point questions <wink>. Or prehaps just conveniently ignoring what "work" means in a given context :-) Cheers, mwh -- Make this IDLE version 0.8. (We have to skip 0.7 because that was a CNRI release in a corner of the basement of a government building on a planet circling Aldebaran.) -- Guido Van Rossum, in a checkin comment From theller at python.net Wed Sep 17 15:07:12 2003 From: theller at python.net (Thomas Heller) Date: Wed, 17 Sep 2003 21:07:12 +0200 Subject: Sound, time and platform issues References: <bka4k6$j9a$1@news.peterlink.ru> Message-ID: <oexjgrof.fsf@python.net> anton muhin <antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru> writes: > Hello everybody! > > I need advice and expertise of the community for the following problem. > > I'm going to make a psycholinguistic experiment. In this experiment > the auditor is asked to listen to some text and to press the button > when some event occurs. I need to find out reaction time on different > inputs and, therefore, I need 1) rather accurate (or, at least, > constantly biased) estimates for the moment the button was pressed, > and 2) "real-time" sound playing. > > Googling finds out several Python toolkits for dealing with sound, but > they are for Linux, not Windows. > > Therefore questions: > 1. Does anybody know about Python tools that might help to solve the > problem above for Windows? The winsound module included with Python? It allows playing wav files. And time.clock() will provide accurate timing, AFAIK. Thomas From klapotec at chello.at Fri Sep 26 11:10:37 2003 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 26 Sep 2003 15:10:37 GMT Subject: PEPs link gone from the Python homepage? References: <un0crhase.fsf@boost-consulting.com> <3F74546F.AF665B35@engcorp.com> Message-ID: <skl8nvc4jud22cfrrf7i4on9ecnftmlm8s@4ax.com> On Fri, 26 Sep 2003 10:59:59 -0400, Peter Hansen <peter at engcorp.com> wrote: >David Abrahams wrote: >> >> Since a significant part of Python is only documented in PEPs, I am >> disappointed to see that they can't be easily found. Where are they? > >Why on the the Documentation page, of course. ;-) > >-Peter ...and also on the Developers page. --Christopher From BrenBarn at aol.com Mon Sep 8 13:29:28 2003 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 8 Sep 2003 17:29:28 GMT Subject: exec code with timeout? References: <Xns93EFD117DA30FOKB@130.133.1.4> <mailman.1062996311.6727.python-list@python.org> <Xns93EFE34728E26OKB@130.133.1.4> <mailman.1062999372.21845.python-list@python.org> <qaY6b.29120$hE5.1041098@news1.tin.it> <87n0dfcx7v.fsf@pobox.com> <9X_6b.44056$R32.1398393@news2.tin.it> <ad9fp9zg.fsf@yahoo.co.uk> Message-ID: <Xns93F06A27527F3OKB@130.133.1.4> Paul Moore wrote: >>>> import thread >>>> import time > >>>> def alarm(sec): > ... def wait(sec): > ... time.sleep(sec) > ... thread.interrupt_main() > ... thread.start_new_thread(wait, (sec,)) This looks perfect! Many thanks. -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From mcherm at mcherm.com Wed Sep 3 11:38:12 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 3 Sep 2003 08:38:12 -0700 Subject: Difference of hash and __hash__() Message-ID: <1062603492.3f560ae4ea60d@mcherm.com> Jeff Epler wrote: > No, it's apparently deliberate that slices don't hash (so that > {}[1:2] raises an error). I think that slice(None).__hash__ is from > object.__hash__, but this is rightfully(?) ignored by PyObject_Hash() > which looks at tp_hash (NULL for slice objects) and tp_compare (non-NULL > for slice objects) with the result that the object is treated as > unhashable. Leaving Stefan Fleiter somewhat puzzled: > So, should I write a bugreport or not? > Are you sure it is "rightfully ignored" or not? > > Somewhat puzzled, > Stefan Stefan: Go ahead and submit the bugreport. If it's desired that {}[1:2] raises an error (and I believe Guido has been asked and has declared that this is his desired behavior), then slice(1,2).__hash__() should raise an exception -- to do otherwise is misleading. You wanted to know if slices were hashable, so you tried out __hash__ -- IMHO that's the proper approach, and you shouldn't have to examine the C code. So submit the bugreport, but I'm guessing that slices will remain unhashable. IIRC, Guido felt that the risk of confusion (folks thinking that {}[1:2] would return some part or subset of the dict) was greater than the utility of using slices as keys in a dict (for which, I believe, he was unable to come up with a single plausible use case). -- Michael Chermside From aleax at aleax.it Thu Sep 25 08:19:51 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Sep 2003 12:19:51 GMT Subject: getting a value from a web-page References: <mailman.1064454334.1269.python-list@python.org> <d3c9c04.0309250049.2f06b7d5@posting.google.com> <mailman.1064486917.24431.python-list@python.org> Message-ID: <H3Bcb.163889$R32.5271319@news2.tin.it> Gerrit Holl wrote: > Mark Carter wrote: >> > And a value from an excel located in a web-server? (Sheet1!cell A1) >> >> Do you mean an excel file located on your server, or somebody else's >> server? If it is on your server, you could manipulate the file >> directly using Mark Hammond's excellent win32all: >> http://starship.python.net/crew/mhammond/ > > Is it possible to do so without Windows? No, win32all only runs on Windows (perhaps it might be ported to WINE or something, but I know of nothing like that ever being done). Microsoft Excel can run just fine on Linux thanks to "Crossover Office" (or, presumably, other versions of Wine, too), but I do not know how to "programmatically" drive it from Python under such environments. One possibility might be to use OpenOffice 1.1 (which is able to open and read XLS files, and can in turn be driven by Python with the new "Python-UNO bridge" included in OO release 1.1) -- but I have, as yet, no practical experience doing that. Alex From robin at jessikat.fsnet.co.uk Mon Sep 22 03:54:44 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 22 Sep 2003 08:54:44 +0100 Subject: pop3 email header classifier? References: <GmZAOKA6Uya$Ew2E@jessikat.fsnet.co.uk> <r81tmvo2rph8109ohf357mq2fajkliqhoh@4ax.com> Message-ID: <5enPgJAErqb$Ewbv@jessikat.fsnet.co.uk> In article <r81tmvo2rph8109ohf357mq2fajkliqhoh at 4ax.com>, Tim Roberts <timr at probo.com> writes >Robin Becker <robin at jessikat.fsnet.co.uk> wrote: >> >>Hi, I'm getting vast numbers of fake upgrade emails containing some kind >>of virus. My rather old client can be made to reject these based on some >>patterns in the subject line. They're nearly all based on the word >>'New', 'Latest', 'Microsoft', 'Patch', 'Pack', ... etc etc. >> >>Is there a python tool that can be made to delete these from my POP3 >>mail box rather than let my client reject? Quite a few seem to have >>semi-valid return addresses so I get postmaster rejects from >>xxx at microsoft.com etc. > >Is your e-mail client actually set up to send a RESPONSE when you receive a >virus attachment? If so, can you please STOP IT AT ONCE? > I have no virus detection in the client and am deliberately not rejecting. That was the whole point of my question I wanted to do better. As a point of fact with this SWEN worm, it does seem possible to kill by a combination of the subject, from address and attachment size. The spambayes approach would certainly work, but it wouldn't improve my download times. I estimate I had about 50Mb of these things to download yesterday (ie 3-4 hours @ 56k). By employing a kill script I could keep up fairy easily. I'm certainly not sending any response or rejecting, I'm using DELE which should be a sink. >ALL viruses released in the last 3 years choose random names for both the >sender AND recipient. It is not possible to automatically extract the >infected individual's e-mail address from a virus message. You can find >the address of their e-mail server, but that's all. > >By sending a polite "you sent me a virus" message, you are doing NOTHING to >stop the viruses, you are ANNOYING an innocent person, and you are DOUBLING >the e-mail volume damage caused by the virus script kiddies. > >I got close to 10,000 helpful and completely bogus "you sent my a virus" >messages during the "SoBig" fiasco. -- Robin Becker From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Mon Sep 22 12:40:41 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Mon, 22 Sep 2003 18:40:41 +0200 Subject: Where to publish my code In-Reply-To: <APBbb.116957$bo1.12014@news-server.bigpond.net.au> References: <1f0bdf30.0309212039.16c9bef0@posting.google.com> <87r829t75e.fsf@pobox.com> <APBbb.116957$bo1.12014@news-server.bigpond.net.au> Message-ID: <3f6f2609$0$58701$e4fe514c@news.xs4all.nl> Neil Hodgson wrote: > After a couple of months of doing this I received a request to move the > files from the web space to the release system. May depend on how often your > files are downloaded. Probably because the files on the file release system are mirrorred to SF's download mirrors, while the web content always comes from their own server. --Irmen From max at nospam.com Fri Sep 26 15:56:24 2003 From: max at nospam.com (max) Date: Fri, 26 Sep 2003 19:56:24 GMT Subject: PIL: Group4 Tiff Images In-Reply-To: <l449nvo49lq8jvmndluvtb4lqq894889eg@4ax.com> References: <mqm8nvsetc3vtddlt05p24jn6bevbnuvuh@4ax.com> <z5%cb.28323$nU6.4440971@twister.nyc.rr.com> <l449nvo49lq8jvmndluvtb4lqq894889eg@4ax.com> Message-ID: <IR0db.17372$lZ6.4486895@twister.nyc.rr.com> > How do the headers come through now? I think I set them the same as > my sig e-mail. > > > Doug Tolton > (format t "~a@~a~a.~a" "dtolton" "ya" "hoo" "com") Now you got it :) From gerrit at nl.linux.org Wed Sep 24 16:11:27 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Wed, 24 Sep 2003 22:11:27 +0200 Subject: Python Glossary In-Reply-To: <16241.53538.40615.455582@montanaro.dyndns.org> References: <16241.53538.40615.455582@montanaro.dyndns.org> Message-ID: <20030924201127.GA5122@nl.linux.org> Skip Montanaro wrote: > Thanks to people who submitted content for the Python Glossary: > > http://manatee.mojam.com/python-glossary I think it may also be useful to add some terms that are not related to programming, but do occur in the tutorial and may be difficult for some users. When I first read the tutorial (years ago), I was really frightened by the section on complex numbers. I had never heard of them, and I did also not understand immediatly that I could skip this section. I would have been helped then by a note that I would not need them, and maybe even a short introduction of what they are (however, I was 14, so I would probably not be able to understand them). Gerrit. -- 164. If his father-in-law do not pay back to him the amount of the "purchase price" he may subtract the amount of the "Purchase price" from the dowry, and then pay the remainder to her father's house. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From avera at coes.org.pe Thu Sep 25 09:45:53 2003 From: avera at coes.org.pe (Alberto Vera) Date: Thu, 25 Sep 2003 08:45:53 -0500 Subject: send email References: <338366A6D2E2CA4C9DAEAE652E12A1DEBF99AB@au3010avexu1.global.avaya.com> Message-ID: <003101c3836b$56b72b90$1603a8c0@pc22> Thanks for your reply. I'd like to explain the problem to get a better idea about this. A python program check every minute if a value is 0 in a register on a database. In this case using Python, it'll send an email. Thanks ----- Original Message ----- From: "Delaney, Timothy C (Timothy)" <tdelaney at avaya.com> To: "Alberto Vera" <avera at coes.org.pe>; <python-list at python.org> Sent: Wednesday, September 24, 2003 9:24 PM Subject: RE: send email > > From: Alberto Vera [mailto:avera at coes.org.pe] > > > > Could you tell me How I can send an email using WIN2000? What do I need? > > Most people use an email client. Common ones are Outlook, Outlook Express and Eudora. > > For more information, look here: > > http://www.catb.org/~esr/faqs/smart-questions.html > > Tim Delaney > > -- > http://mail.python.org/mailman/listinfo/python-list From nospamius at lundhansen.dk Mon Sep 1 12:45:04 2003 From: nospamius at lundhansen.dk (Bertel Lund Hansen) Date: Mon, 01 Sep 2003 18:45:04 +0200 Subject: HELP : class and variables References: <5c184570.0309010801.2353a3cc@posting.google.com> Message-ID: <ujt6lvgp7j0id2h42jnin1uf5r2g5ilis7@news.telia.dk> vincent delft skrev: >Can you explain the following ? Yes. >class test: > var1=1 > var2=2 > res=var1+var2 >t=test() >print t.res >>> 3 >t.var1=6 >print t.res >>> 3 Changing var1 does not change res. You might like to make it a function instead: class Test: var1=1 var2=2 def res (self): return self.var1+self.var2 t=Test() t.var1=6 print t.res() I learned in Java to give classes names with the first letter capitalized. I find that a useful convention. -- Bertel, Denmark From peter at engcorp.com Tue Sep 16 11:57:15 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Sep 2003 11:57:15 -0400 Subject: Duck Typing References: <221d8dbe.0309160101.4a09f2ad@posting.google.com> <mailman.1063720351.23661.python-list@python.org> <3gG9b.12137$3Y2.2543@news2.central.cox.net> Message-ID: <3F6732DB.F31A954E@engcorp.com> Steve Holden wrote: > > exquacktly [ducks and runs] ^^^^^ Steve, did you even _know_ you did this? You're sick! -Peter :-) From peter at engcorp.com Tue Sep 23 09:25:39 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Sep 2003 09:25:39 -0400 Subject: Need arguments for "Python vs. Perl as an OOPL" References: <roy-002696.23242122092003@reader2.panix.com> Message-ID: <3F7049D3.14C48D43@engcorp.com> Roy Smith wrote: > > I'm working on a prototype of a new application in Python. At some > point, if this ever turns into a product, the powers that be will almost > certainly demand that it be done in Perl. My job will be to convince > them otherwise. Do you need to convince them now, to allow you to continue working on it in Python, or are you just preparing for the time when they will come and ask for it to be done in Perl? I ask because I suspect the best way of convincing them will be to do nothing, and stand back watching as your Python prototype continues to work without problems, while those attempting to rewrite it in Perl waste a lot of time and never get it quite working... and even if they do, just print out a couple of pages from both and show them to the "powers that be" and that ought to do the trick. Unless they are wholly uninterested in readability and maintainability. :-( -Peter From grey at despair.dmiyu.org Mon Sep 15 16:45:50 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Mon, 15 Sep 2003 20:45:50 -0000 Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <oprvd7fyp7fhfgdd@news.chello.no> <mailman.1063381340.26766.python-list@python.org> <17d520f6.0309130704.7944c876@posting.google.com> <87znh89ufv.fsf@pobox.com> <slrnbm8l54.o3i.grey@dmiyu.org> <878yoqoudj.fsf@pobox.com> Message-ID: <slrnbmc97u.vpg.grey@dmiyu.org> On 2003-09-15, John J. Lee <jjl at pobox.com> wrote: > Steve Lamb <grey at despair.dmiyu.org> writes: >> I run several GTK apps that don't touch Gnome: >> Sylpheed-Claws >> Pan >> XChat >> GTK != GNOME. > [...] > Yep: that's exactly what I don't understand! *Why* did you do that? What, run GTK apps that don't touch Gnome? Simple reason: Gnome sucks. I run KDE. I wouldn't want to load the full gamut of gnome libs but the GTK libs are ok. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From tweedgeezer at hotmail.com Mon Sep 22 18:29:19 2003 From: tweedgeezer at hotmail.com (Jeremy Fincher) Date: 22 Sep 2003 15:29:19 -0700 Subject: Slicing vs .startswith References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> <bkk4h1$9ke$06$1@news.t-online.com> <mailman.1064154389.29357.python-list@python.org> <bkmd4q$t13$05$1@news.t-online.com> <DUCbb.100826$hE5.3550910@news1.tin.it> <mailman.1064245938.12315.python-list@python.org> Message-ID: <698f09f8.0309221429.589e4a9a@posting.google.com> Shu-Hsien Sheu <sheu at bu.edu> wrote in message news:<mailman.1064245938.12315.python-list at python.org>... > For example, which one of the following would be more efficient, or , > moreover, more pythonic? > > if aa[:3] == 'abc': > > vs > > if aa.startswith('abc'): Python is about maintainability, and the latter is significantly more maintainable than the former; if the string you're checking against changes in size, using .startswith doesn't require you to change your sourcecode anywhere else. Jeremy From sholden at holdenweb.com Mon Sep 29 19:28:08 2003 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2003 23:28:08 GMT Subject: error explanation References: <13df83a2.0309291345.32db8a2b@posting.google.com> Message-ID: <ce3eb.1758$603.1657@news2.central.cox.net> "Mac Wood" <malcolm.wood3 at ntlworld.com> wrote in message news:13df83a2.0309291345.32db8a2b at posting.google.com... > Could someone please explain this error message: > > Traceback (most recent call last): > File "C:\Python23\time.py", line 1, in -toplevel- > time.py > NameError: name 'time' is not defined > > I tried entering the following example: > > time.py > #This programs calculates rate and distance problems > print "Input a rate and a distance" > rate = input("Rate:") > distance = input("Distance:") > print "Time:",distance/rate > > which according to the tutor should have run as this: > > > python times.py > Input a rate and a distance > Rate:5 > Distance:10 > Time: 2 > Thanks for your help Try using raw_input() rather than input() regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From mwh at python.net Mon Sep 29 10:10:26 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 29 Sep 2003 14:10:26 GMT Subject: FTP access to starship.python.net? References: <d7fcf8b4.0309271341.72304331@posting.google.com> Message-ID: <7h3fzif1yi8.fsf@pc150.maths.bris.ac.uk> samschul at pacbell.net (Samuel Schulenburg) writes: > Who should I contact about accessing my account on Starship. I need to > obtain a new password and access process. > > I think i am having a memory lapse as it has been over a year sense I > have had a need to access my files. I think emailing <your username>-starship at python.net will lead to enlightenment. Cheers, mwh -- > Touche! But this confirms you are composed of logic gates. Crud, I thought those were neurons in there. -- Thomas F. Burdick, Kenny Tilton, comp.lang.lisp From anton at vredegoor.doge.nl Tue Sep 16 18:41:53 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 17 Sep 2003 00:41:53 +0200 Subject: Is there "let binding" in Python? References: <mailman.1063743924.1995.python-list@python.org> Message-ID: <bk83rt$2o3$1@news.hccnet.nl> Rob Hunter <rhunter007 at yahoo.com> wrote: >wrong). What you're describing is "dynamic >scoping". That's where the body of a function >(or code block in this case) isn't evaluated >until it is used. And thus, free variables in >the body assume whatever values their calling >environment has. Dynamic scoping is a bad thing. > So bad, in fact, that lisp added (at least the >option of, I think) static scoping, Scheme >exclusively uses static scoping, and that Python >corrected their mistake (it used to be >dynamically scoped). What's wrong with dynamic scoping? Anyway, Python hasn't corrected this "mistake", see following code (I vaguely remember *something* about this was fixed, and while I don't know exactly what it was, I'm reasonably sure it wasn't what you write about above, since that still functions the way you think is bad) import sys def test(): L =[] for i in range(10): f = lambda : sys.stdout.write("%s" %i) g = lambda i=i : sys.stdout.write("%s" %i) L.append((f,g)) for x,y in L: x() y() print if __name__=='__main__': test() # output : 90919293949596979899 >But anyway, from my tests, and from what I've >read, Python has static scoping, but what >assignment allows you to do is violate, in a way, >this static scoping, which is what we see here. Probably assignment *enables* static scoping if following this line of reasoning, since if there's no statement "global i" in a function, assigning "i" results in binding a local name "i". Binding "i" in the test function name space to "i" in the name space of the lambda function gives the behavior you want. If no binding in the lambda name space is made, the "i" in the enclosing name space is used, which is bound to the value "9" by the time function x is called. Anton From bokr at oz.net Wed Sep 10 18:07:07 2003 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2003 22:07:07 GMT Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> <3F5F82A5.7DB9A717@alcyone.com> <3F5F9A02.D1A5ACAA@easystreet.com> Message-ID: <bjo7ab$e0f$0@216.39.172.122> On Wed, 10 Sep 2003 14:39:14 -0700, achrist at easystreet.com wrote: >Erik Max Francis wrote: >> >> >> Yep: >> >> generator.next() >> > >This style supports only output-driven processes. The generator, >being on the input side, is always the server, and the output >side is always the client. It doesn't fit the situation where the >input is heterogeneous and input has to get spewed in several >directions, depending on its content. > > Could you make some fantasy-code to illustrate what you mean? Regards, Bengt Richter From tjreedy at udel.edu Tue Sep 9 11:47:36 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 Sep 2003 11:47:36 -0400 Subject: Why the 'self' argument? References: <slrnblh5ru.nd5.gstaniak@inka.zagiel.pl> <vlh7otscuo8gb1@news.supernews.com> <3f58a2bd$0$156$a1866201@newsreader.visi.com> <vlhba85atlte07@news.supernews.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <vlhidvcpq9a980@news.supernews.com> <qpOW/ks/KnRV089yn@the-wire.com> <vlhtm1bmc7m295@news.supernews.com> <fc08a59c.0309060830.623d31c7@posting.google.com> <Ucp6b.3992$ZB4.3874@reader1.news.jippii.net> <3f5a2260$0$166$a1866201@newsreader.visi.com> <TRr6b.4056$ZB4.1410@reader1.news.jippii.net> <vlpeq9jko1l6b0@news.supernews.com> <7T47b.4753$ZB4.113@reader1.news.jippii.net> <vlpr14kfehrn46@news.supernews.com> <rKadnXfgmJJdosCiXTWJiQ@comcast.com> <vlrfohfp908qd7@news.supernews.com> Message-ID: <r96cnUpbeYOEa8CiXTWJjA@comcast.com> "John Roth" <newsgroups at jhrothjr.com> wrote in message news:vlrfohfp908qd7 at news.supernews.com... > > "Terry Reedy" <tjreedy at udel.edu> wrote in message > news:rKadnXfgmJJdosCiXTWJiQ at comcast.com... > > #define max(a,b) ... in C). And one has to adjust to and feel > > comfortable enough with the view that multiparam functions are a > > composition of single param functions. > > I'm not sure how central currying is to the type inference > mechanism. Completely central in that the type of functions *is* a curried type (in the *MLs I have looked at). For instance, the type of a binary int function is displayed something like: func(int)==>func(int)==>int with ==> associative right to left. The type of f(i,j)=>int is 'a function (of i) returning [a function (of j) returning an int]'. As I said, takes some adjustment for most. But occasional mental exercise like this is probably good for the brain. Terry J. Reedy From __peter__ at web.de Mon Sep 1 17:39:34 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 01 Sep 2003 23:39:34 +0200 Subject: Structured writing to console, such as a table References: <mailman.1062445143.10872.python-list@python.org> Message-ID: <bj0el5$2h6$05$1@news.t-online.com> Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Before I reinvent this wheel... please give me some tips, references, > examples... I wrote the following some months ago, but never really finished it, so it's not the kind of code you would want to publish on glossy paper. Anyway, hoping that nobody is watching, I quote it below :-) I've added two contrived examples only now to give you an idea how to use it. Peter <code> class StringCol(object): def __init__(self, caption, extract, format=str): self.caption = caption if callable(extract): self.extract = extract elif type(extract) == type(""): self.extract = lambda row: getattr(row, extract) else: assert type(extract) == type(1), "extract must be callable, attribute name or column index" self.extract = lambda row: row[extract] self.format = format def init(self): self.width = len(self.caption) def add(self, row): s = self.format(self.extract(row)) self.width = max(self.width, len(s)) def formatValue(self, row): return self.format(self.extract(row)).ljust(self.width) def formatCaption(self): return self.caption.ljust(self.width) def formatTotal(self): return " ".ljust(self.width) def formatDash(self, char="-"): assert len(char) == 1, "only one char, please" return char * self.width def done(self): pass class NumCol(StringCol): SUM = 1 ACCUMULATE = 2 def __init__(self, caption, extract, format=str, action=None): StringCol.__init__(self, caption, extract, format) self.action = action #print ">>>>>>>>>>>>", self.action def init(self): StringCol.init(self) self.total = 0 self.value = 0 def add(self, row): self.total += self.extract(row) def formatValue(self, row): if self.action == NumCol.ACCUMULATE: #print "hi" self.total += self.extract(row) value = self.total else: value = self.extract(row) return self.format(value).rjust(self.width) def formatCaption(self): return self.caption.rjust(self.width) def formatTotal(self): return self.format(self.total).rjust(self.width) def done(self): self.width = max(self.width, len(self.format(self.total))) if self.action == NumCol.ACCUMULATE: self.total = 0 def printTable(columnDefs, rows, seps=("| ", " | ", " |"), dest=None): #def printTable(columnDefs, rows, seps=("", " ", ""), dest=None): if type(seps) == type((None,)): #from otten.generic.struct import Struct class Struct: def __init__(self, **kwd): self.__dict__.update(kwd) seps = Struct(left=seps[0], mid=seps[1], right=seps[2]) if dest is None: import sys dest = sys.stdout # dry-run to determine column widths for col in columnDefs: col.init() for row in rows: for col in columnDefs: col.add(row) for col in columnDefs: col.done() # end dry-run def formatValue(col): return col.formatValue(row) def formatTotal(col): return col.formatTotal() def formatCaption(col): return col.formatCaption() def formatDash(col): return col.formatDash() def printRow(fmt, seps=seps): dest.write(seps.left) continued = False for col in columnDefs: if continued: dest.write(seps.mid) else: continued = True dest.write(fmt(col)) dest.write(seps.right) dest.write("\n") dashSeps = Struct(left="-" * len(seps.left), mid="-" * len(seps.mid), right="-" * len(seps.right)) printRow(formatCaption) printRow(formatDash, dashSeps) for row in rows: printRow(formatValue) printRow(formatDash, dashSeps) printRow(formatTotal) printRow(formatDash, dashSeps) #print "=" * width if __name__ == "__main__": # list of rows table = [ ["a", 1, 2, 3], ["bbbbb", 1000000, 2222222, 33], ] printTable( [StringCol("First", 0), NumCol("Second", 1), NumCol("Forth", 3)], table) # list of objects class Test: def __init__(self, n, a): self.name = n self.age = a table2 = [ Test("peter", 20), Test("john", 111), Test("sue", 30) ] print printTable( [StringCol("Name", "name"), NumCol("Age**2", lambda row: row.age*row.age, action=NumCol.SUM), NumCol("SigmaAge", "age", action=NumCol.ACCUMULATE), NumCol("Age", "age") ], table2) </code> From newsgroups at jhrothjr.com Fri Sep 26 10:05:09 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 26 Sep 2003 10:05:09 -0400 Subject: Where to import modules? References: <bl1bes$13qe$1@f1node01.rhrz.uni-bonn.de> <3F74375A.F9D4B0EB@engcorp.com> <bl1f7t$oig$1@fred.mathworks.com> Message-ID: <vn8hsuqh0kl670@news.supernews.com> "JCM" <joshway_without_spam at myway.com> wrote in message news:bl1f7t$oig$1 at fred.mathworks.com... > Peter Hansen <peter at engcorp.com> wrote: > ... > > > Basically doing this is an optimization, and you shouldn't be optimizing > > before the program is working, and you shouldn't be optimizing without > > a real need for it. (That is, just because it's a little faster doesn't > > mean it's worth doing.) > > Aside from being an optimization, it's also good for documentation. > If you see an import at the top of a file it might not be immediately > clear how or why the module is being used. It's similar reasoning to > why you might define variables in the narrowest scope posible. There are also reasons having to do with circular imports that you might not want to import at the top. However, this situation is hazardous enough that some effort in removing the circularity is usually warranted. In general, I agree with the style guide: put them at the top of the module unless there is a real, strong reason to put them somewhere else. Even then, I'd put a comment in with the main imports pointing out where the embedded import exists. John Roth From jordan at krushen.com Thu Sep 11 22:16:46 2003 From: jordan at krushen.com (Jordan Krushen) Date: Fri, 12 Sep 2003 02:16:46 GMT Subject: Flash Remoting in Python? References: <7712111.0309111357.3be3b591@posting.google.com> <2E78b.1002$8g2.829@news1.central.cox.net> <E5WcnXLOoPRMiPyiXTWJiQ@comcast.com> <VV88b.1024$8g2.587@news1.central.cox.net> Message-ID: <oprvc7dcpg5ctagx@shawnews> On Fri, 12 Sep 2003 01:01:41 GMT, Dave Benjamin <dave at 3dex.com> wrote: > I will note, however, that Flash's XML parser is slow, and WDDX is more > compact than XML-RPC (although it isn't, in itself, an RPC protocol, > unlike XML-RPC). God, is it ever slow. I'm working on a remote playlist editor (Flash talking to Python XML-RPC), and when sending a list of ~1000 entities across the wire, performance was increased nearly a hundred times simply by sending one delimited string element instead of 1000 XML elements. Of course, XML adds quite a bit of bloat, but all the time was consumed in CPU, not on the wire. On that note, I've been working on a rewrite of Pedro's ActionScript XML-RPC library, doing automatic marshalling/unmarshalling, shortening calls to the following: rpc = new rpc('http://host/path/') rpc.send(callbackFunc, 'method', arg1, arg2, arg3...) instead of the rather verbose and repetitive arg/result formatting which I found in the original library. Contact me if you'd like to test it out -- I haven't performed any regression testing on it yet, but I'm happily using it to pass arrays, ints, dicts, and strings back and forth. J. From bmiras at yahoo.com Tue Sep 23 12:00:05 2003 From: bmiras at yahoo.com (bmiras at yahoo.com) Date: 23 Sep 2003 09:00:05 -0700 Subject: problem using urllib2: \n Message-ID: <7cb14f9.0309230800.8d3a28b@posting.google.com> I've got a problem using urllib2 to get a web page. I'm going through a proxy using user/password authentification and i'm trying to get a page asking for a HTTP authentification. And I'm using python 2.3 Here is an exemple of the piece of code I use: import urllib2 #Proxy handler proxy_handler = urllib2.ProxyHandler({"http" : "http://proxyuser:proxypassword at myproxy:8050"}) #Site auth handler site_auth_handler = urllib2.HTTPBasicAuthHandler(); site_auth_handler.add_password( "This Realm", "www.mysite.com", "siteuser", "sitepassword" ); opener = urllib2.build_opener( site_auth_handler, urllib2.HTTPRedirectHandler, urllib2.HTTPHandler , proxy_handler) urllib2.install_opener(opener) req = urllib2.Request('http://www.mysite.com/protectedpage') page = urllib2.urlopen(req) I got a 401 error. Analyzing the request using 'strace' I can see the following request sent to the proxy: GET http://www.mysite.com/protectedpage HTTP/1.0\r\nHost: www.mysite.com\r\nUser-agent: Python-urllib/2.0a1\r\nProxy-authorization: Basic bWlyYXNiOm1pcjAz\n\r\nAuthorization: Basic bWlyYXM6bWlyYXMwMDE=\n\r\n\r\n As you can see there is additionnal \n sent to the server just after the Proxy-authorization and the Authorization fields. I think that in this case the web server get only this part: GET http://www.mysite.com/protectedpage HTTP/1.0\r\nHost: www.mysite.com\r\nUser-agent: Python-urllib/2.0a1\r\nProxy-authorization: Basic bWlyYXNiOm1pcjAz\n\r\n and so send me back an error 401, since I'm not authenticated for the site. I had a look in the urllib2.py . I think that base64.encodestring add an \n at the end of the string. It's the case in the method 'proxy_open': def proxy_open(self, req, proxy, type): orig_type = req.get_type() type, r_type = splittype(proxy) host, XXX = splithost(r_type) if '@' in host: user_pass, host = host.split('@', 1) if ':' in user_pass: user, password = user_pass.split(':', 1) user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))) req.add_header('Proxy-authorization', 'Basic ' + user_pass) host = unquote(host) req.set_proxy(host, type) ... I think it should be: user_pass = base64.encodestring('%s:%s' % (unquote(user), unquote(password))).split() have you any other clue? thank you! Bastien From cartermark46 at ukmail.com Fri Sep 5 05:09:36 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 5 Sep 2003 02:09:36 -0700 Subject: newbie question about dictionnary ? References: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Message-ID: <d3c9c04.0309050109.7b63dee@posting.google.com> > for doing this I thought the dictionary was excellent but the key is a > string while I want it > to be the 2 points forming the edge ? How to do it ? Good news: keys don't have to be strings. So this is perfectly valid code: d={} d[((1,2), (3,4))] = 'whatever' From jwdillworth at yahoo.com Wed Sep 3 09:03:16 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Wed, 3 Sep 2003 06:03:16 -0700 (PDT) Subject: Writing solid code book In-Reply-To: <b15d2792.0309030339.3ac939e7@posting.google.com> Message-ID: <20030903130316.79440.qmail@web41111.mail.yahoo.com> It does use C for its examples, but I think many of the principles would still apply to Python. Some, like "crashing early" happen as a side-effect of using Python. Python's exceptions accomplish this nicely. Crashing in the face of absurd circumstances rather than trying to recover or ignore them. I wish Perl had this, I once had a Perl script eat a few hundred files I was trying to have it rewrite. A server had run out of disk space, and since I didn't say "close FILE or die", the close silently failed to write the file... a few hundred times. The author *is* an ex-MS guy. There are commments in the book to the effect that the practices therein represent the ideal at Microsoft, not the reality. Good book. --- post400 <post400 at prontomail.com> wrote: > Hi, > > there is another famous book 'Writing solid code' but does it apply to > Python ? Or it's usable only by Microsoft C programmers ? The author > seems to be an ex-Microsoft guy ! > > Thanks , > post400 > -- > http://mail.python.org/mailman/listinfo/python-list From graham__fawcett at hotmail.com Tue Sep 9 12:58:34 2003 From: graham__fawcett at hotmail.com (Graham Fawcett) Date: 9 Sep 2003 09:58:34 -0700 Subject: os.listdir References: <2ce42702.0309081441.5c73a772@posting.google.com> <mailman.1063064892.16615.python-list@python.org> <bjk10v$ue0$04$1@news.t-online.com> Message-ID: <e9570f37.0309090858.17b8e271@posting.google.com> "Michael Peuser" <mpeuser at web.de> wrote in message news:<bjk10v$ue0$04$1 at news.t-online.com>... > "Graham Fawcett" <fawcett at teksavvy.com> > > Hari wrote: > > > >What I wanted to know was, is it guaranteed that between 2 calls > > >os.listdir any files added to the directory are appended and the > > >earlier order is maintained? > > As others pinted out, this is jighly improbably, espacially under windows > > > > There's no need for such sequence guarantees, though. It's probably not > > the most efficient but here's a way to do it: > > > > import os > > import time > > > > somedir = '/tmp' > > snapshot1 = os.listdir(somedir) > > time.sleep(...) > > snapshot2 = os.listdir(somedir) > > > > newfiles = [f for f in snapshot2 if not f in snapshot1] > > > > Pretty efficient, really: that's an O(n) comparison if I remember my > > Python internals correctly. Which I don't, so don't trust my word for > > it. ;-) > > > You are wright to mistrust it ;-) > Though 'f in list' looks harmless it itself is o(n) because there seems to > be a linear search (This is different whith 'f in dict' of course). So your > list comprehension is of o(n*n). > > Kindly > Michael P D'oh! Thanks, Michael, I *knew* I'd messed that up... I'll repeat "list searches linear, dict lookups constant..." a hundred times before bed tonight. -- Graham From tim.hochberg at ieee.org Tue Sep 23 15:43:34 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Tue, 23 Sep 2003 12:43:34 -0700 Subject: Thoughts on PEP284 In-Reply-To: <eppstein-CA53C5.12265623092003@news.service.uci.edu> References: <mailman.1064341934.21653.python-list@python.org> <eppstein-CA53C5.12265623092003@news.service.uci.edu> Message-ID: <Gn1cb.2779$gi2.756@fed1read01> David Eppstein wrote: > In article <mailman.1064341934.21653.python-list at python.org>, > Michael Chermside <mcherm at mcherm.com> wrote: > > >>Stephen Horne writes: >> >>>True, it is mostly just an alternative notation for range or xrange. >>>But the integer for loops thing is something that never seems to go >>>away. PEP284 itself quotes four previous PEPs on broadly the same >>>issue. >> >>I am of the opinion that the introduction of enumerate() (in 2.3) will >>go a long ways toward reducing the desire for better integer loop >>syntax. I'm sure it will never go away completely, but if the demand >>seems to die down after a year or so, then I'd guess it was due to >>enumerate(). > > > It will certainly reduce the typical range(len(L)) verbosity. It > doesn't do anything to help the readability of expressions like > range(dim-2,-1,-1) (example from some code I wrote a couple weeks ago). Dealing with reversed ranges is one area that range bugs me. However, in 2.3 you can replace ``range(n-1,-1,-1)`` with ``range(n)[::-1]``, which while still verbose is a lot easier for me to interpret. [Now if I could just convinve Armin Rigo to special case that in Psyco so that it was as fast as the original...] I know someone's going to suggest that, since I'm already using slices, I should be in favor of int[a:b:c] or similar. But, that doesn't work any better than range with reversed ranges since you still have to use two slices to make things clear. That is, to get the equivalent of ``range(n-1,-1,-1)`` one would need to use ``int[n-1:-1:-1]``, which is no clearer, or ``int[:n][::-1]`` which doesn't seem like a particular win over ``range(n)[::-1]``, which you can do now. > Actually, looking at that code, the range is not the least readable part > of it: [Snip dictionary comprehension stuff] -tim From robin at jessikat.fsnet.co.uk Fri Sep 26 11:13:08 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 26 Sep 2003 16:13:08 +0100 Subject: When did Windows start accepting forward slash as a path separator? References: <b16e4ef7.0309251550.724a57f@posting.google.com> Message-ID: <MxxyLIAEeFd$Ew$y@jessikat.fsnet.co.uk> In article <b16e4ef7.0309251550.724a57f at posting.google.com>, Stephen Ferg <steve at ferg.org> writes >I have a question that is not directly Python-related. But I thought >I'd ask the most erudite group that I know... :-) > >When did Windows start accepting the forward slash as a path separator >character? > >At one time, it was accepted as a truism that Windows (like MS-DOS) >was different from Unix because Windows used the backslash as the path >separator character, whereas Unix used the forward slash. > >But now, among a small group of cognoscenti, it is a truism that this >is a myth, and that Windows will allow you to use either the forward >or the backward slash as a pathname separator. > >I hypothesize that originally Windows accepted only the backslash, and >then at some time it changed to accept the forward slash as well. >Does anyone know when that change occurred? Was it with the >introduction of support for long filenames in NT and Win95? I seem to remember getting an early C compiler from M$ around 1983/5 and being pleasantly surprised that '/' was acceptable. So far as I know this has been true from the earliest days. I suspect it was because of all the unix C code that people wanted to work without effort. -- Robin Becker From essai1 at mci.local Mon Sep 15 03:13:58 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Mon, 15 Sep 2003 09:13:58 +0200 Subject: pyc2py References: <pan.2003.09.15.07.01.32.964993@thomas-guettler.de> Message-ID: <bk3p54$8ed$1@news-reader2.wanadoo.fr> Pirate ? From alessandro at sephiroth.it Mon Sep 22 11:07:40 2003 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Mon, 22 Sep 2003 15:07:40 GMT Subject: py2exe: dynamic module does not define init function References: <81zbb.99124$hE5.3508075@news1.tin.it> <FoCbb.100492$hE5.3545186@news1.tin.it> <qaDbb.101005$hE5.3554558@news1.tin.it> <SZDbb.140624$R32.4432440@news2.tin.it> Message-ID: <0fEbb.101429$hE5.3567510@news1.tin.it> > If audiere.dll is in the right directory, and it has the > initaudiere function in it, your behaviour is rather mysterious. > Perhaps you have some other file of the same name on your > machine and import is picking up THAT file instead (under > py2exe only) -- just guessing, of course. audiere.dll and .pyd are in my DLL python folder (as suggested in the info page of the project), but they also are in the dist folder.. I checked for duplicates but they didn't exist.. I also check the files copied (.dll and .pyd), are ok. I also used the force-import argument in the setup.bat file, but nothing changed :( The .exe file will not be for distribution, just for me.. so i can use always the .pyw file.. no problem, but maybe in the future i will find the same situation -- Alessandro Crugnola [sephiroth] Flash | PHP Developer http://www.sephiroth.it Team Macromedia Volunteer for Flash http://www.macromedia.com/go/team Flash-php mailing list http://www.flash-php.it/index.php?ml=fpcoders&action=subscribe From prabua at hotmail.com Tue Sep 30 10:53:07 2003 From: prabua at hotmail.com (Prabu) Date: 30 Sep 2003 07:53:07 -0700 Subject: can i implement virtual functions in python ? Message-ID: <e73c30c6.0309300653.24456567@posting.google.com> Hi, I'm new to python, so excuse me if i'm asking something dumb. Does python provide a mechanism to implement virtual functions? Can you please give a code snippet also...:) Thanx in advance -Prabu. From jim-usenet at jimdabell.com Wed Sep 3 11:11:23 2003 From: jim-usenet at jimdabell.com (Jim Dabell) Date: Wed, 03 Sep 2003 16:11:23 +0100 Subject: How to accelerate python application GUI speed References: <43e3984e.0309030532.3fe88bbc@posting.google.com> Message-ID: <-aOdndsss-PdmMuiRVn-vg@giganews.com> ulysses wrote: > I use wxPython make a bittorrent client. I find wxPython very slow and > use many many memory. > When app start, it need 19MB memory. I only use common GUI components. > Python is a really good programming language. But how to do a small,smart, > efficency GUI in win32,it's a big question. In my opinion, the Qt toolkit is far better in terms of quality and speed than wx/tk/whatever. It's also dead simple to code for. The Python bindings are here: <URL:http://www.riverbankcomputing.co.uk/pyqt/>. Check out the license first, some people don't like any of the choices available. -- Jim Dabell From max at ucmg.com.ua.remove.it Mon Sep 29 07:27:06 2003 From: max at ucmg.com.ua.remove.it (Max Ischenko) Date: Mon, 29 Sep 2003 13:27:06 +0200 Subject: data encoding for Python COM interface Message-ID: <bl94sp$ctm$1@hyppo.gu.net> I've wrote a COM Server (in python) to be used from .ASP pages (in VB). All work fine except data encoding. I need to pass Latin1 characters (with Umlauts) through the COM interface. If i simply pass my unicode data as is through the COM interface I got no errors but Umlauts simply disappears on the web pages (ae becomes a). If I do encode my data in 'iso8859-1' in COM Server I got this error while evaluating .ASP page: Python COM Server Internal Error (0x80004005) Unexpected Python Error: exceptions.UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 16: ordinal not in range(128) somepage.asp, line 33. Note, however that test python COM client able to read and save data in utf-8 encoding and it is displayed correctly (via NotePad). Error ... 'ascii' codec ... makes me suspect that I could (or should) somehow specify the correct codec for my COM interfaces. tia. From bokr at oz.net Sun Sep 7 19:29:36 2003 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2003 23:29:36 GMT Subject: Is there a unicode EOF mark like DOS ascii ctl-z or unix crl-d ? Message-ID: <bjgf10$d5s$0@216.39.172.122> I couldn't find one. (Hi Martin ;-) Regards, Bengt Richter From nav+posts at bandersnatch.org Fri Sep 5 22:58:30 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 05 Sep 2003 22:58:30 -0400 Subject: OT: best book in years References: <opruzmelopdd8opo@news.vo.lu> Message-ID: <m3fzja8vxl.fsf@tanelorn.bandersnatch.org> Patrick Useldinger <p.useldinger at myrealbox.com> writes: > As I have not come across anything spectacular recently (except > Python in a Nutshell), I would like to know what *you* consider to > be the best book you have read in the last few years, about Python > or IT in general. The Python Cookbook is the best technical book I've read in a long time. Python in a Nutshell is excellent, but lacks a certain narrative flow which the Cookbook does posses. I think the Cookbook also has better character development. The Cookbook really opened my eyes not just to some of Python's abilities, but also to some programming paradigms that I just hadn't gotten around to assimilating. I just read Matt Ruff's new book _Set_This_House_In_Order_ and was blown away. Brilliant, though not technical. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From Mike at DeleteThis.Geary.com Sun Sep 7 00:23:08 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 6 Sep 2003 21:23:08 -0700 Subject: Redesign of Python site References: <Xns93EEDC144D362whiteywidowyahoocom@216.77.188.17> Message-ID: <vllcldj3012u3d@corp.supernews.com> Thanks *very* much for pointing that out. This proposed redesign has some of the worst typography I've seen in a long time--it's just totally unacceptable. I left detailed comments on the site mentioned below, and I guess I should make some noise on the appropriate mailing lists too. I just hope it's not too late to head off this train wreck of a redesign. <sigh> -Mike rt lange wrote: > came across this page searching feedster. > dont know whether this is the official resdesign or just a proposal; > but the mockups look very nice. > > http://www.pollenation.net/journal/index.php?p=37&c=1 > > main page mockup: > http://www.pollenation.net/assets/public/python-main.html > > interior page: > http://www.pollenation.net/assets/public/python-interior.html From essai1 at mci.local Mon Sep 29 18:18:29 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Tue, 30 Sep 2003 00:18:29 +0200 Subject: PEP-0263 and default encoding References: <3f782aef-bdbbd6f1-a72a-4a6c-8b23-c4915b89a61f@news.szn.dk> Message-ID: <blaau5$b0r$1@news-reader3.wanadoo.fr> Yes ! Why ? And, me (french), i add : # -*- coding: cp1252 -*- at begin of my scripts. But... and if i want do a script for two, three, etc. languages ? or How have Ascii AND non-ascii caracters in scripts ? * sorry for my bad english * @-salutations -- Michel Claveau From cookedm+news at physics.mcmaster.ca Tue Sep 30 16:44:17 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 30 Sep 2003 16:44:17 -0400 Subject: Numeric C extension: bug or error ? References: <veronique.grosse-3009032128040001@mix-grenoble-104-3-14.w193-248.abo.wanadoo.fr> Message-ID: <qnku16u3t26.fsf@arbutus.physics.mcmaster.ca> At some point, veronique.grosse at wanadoo.fr (Philippe Grosse) wrote: > Hi, > > I don't understand this strange behaviour: > > I compile this code : [code clipped; it looks good] ... > /* registration table */ > static struct PyMethodDef testMethods[] = { > {"return_vector", return_vector, 1}, /* method name, C > funcptr, always-tuple */ > {NULL, NULL} /* end of table marker */ > }; Instead of the magic constant "1", use METH_VARARGS. ... > Very simple: this module takes a Numeric array (vector) as argument and > send this array back to python... > > If I compile it under macOSX, the result in python is: > >>>> import test >>>> from Numeric import * >>>> v=array([1.0,2.0,3.0,4.0],Float) >>>> v > array([ 1., 2., 3., 4.]) >>>> test.return_vector(v) > array([ 1., 2., 3., 4.]) > > but in linux the result is: > >>>> import test >>>> from Numeric import * >>>> v=array([1.0,2.0,3.0,4.0],Float) >>>> v > array([ 1., 2., 3., 4.]) >>>> test.return_vector(v) > array([ 1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j]) This isn't what I get; I get the same result under linux as you get from Mac OS X. Have you checked that the copies of the code are the same? -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From gh at ghaering.de Mon Sep 1 10:28:41 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 01 Sep 2003 16:28:41 +0200 Subject: Python Documentation? In-Reply-To: <vl6i5a2fjdrd2c@corp.supernews.com> References: <LQydncwLlNp2UM-iXTWJkA@comcast.com> <Xns93E975FCE1E58godlarz@62.243.74.162> <vl6dmm8jutl140@corp.supernews.com> <Xns93E99702FBABCgodlarz@62.243.74.162> <vl6i5a2fjdrd2c@corp.supernews.com> Message-ID: <3F535799.4050506@ghaering.de> Cameron Laird wrote: > [...] Pythoneers [...] have a vehicle for sharing code examples, > commentary, and related matters: the Wiki (complementing, > incidentally, the Cookbook). Well, these are already two places, not one :) My observation is that in Pythonia, there is quite a diversity in places where code snippets and tips are collected. In addition to the two big sources you mentioned, there's also the Python FAQ, for example. As far as Wikis are concerned, I'd like to humbly suggest that people really use the Wiki at python.org, instead of putting content that concerns Python itself into their own wikis. Yes, I also mean you, Twisted guys! :-P Decentralisation may have its places, but not for documentation and knowledge bases, IMO. That is, if you want to improve on Google being your documentation index ;) -- Gerhard From sheu at bu.edu Tue Sep 23 11:10:49 2003 From: sheu at bu.edu (Shu-Hsien Sheu) Date: Tue, 23 Sep 2003 11:10:49 -0400 Subject: Try/except vs. if/else In-Reply-To: <3F70598E.8020500@bu.edu> References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> <bkk4h1$9ke$06$1@news.t-online.com> <mailman.1064154389.29357.python-list@python.org> <bkmd4q$t13$05$1@news.t-online.com> <DUCbb.100826$hE5.3550910@news1.tin.it> <mailman.1064245938.12315.python-list@python.org> <nA2dnd3VipjjEfKiXTWJlg@comcast.com> <3F70598E.8020500@bu.edu> Message-ID: <3F706279.9000203@bu.edu> Hi, In my understanding, using try/except rather than if/else is more pythonic. However, sometimes it is difficult to use the later. For example, I want to search for a sub string in a list composed of strings. It is considered "possitive" if there is a match, no matter how many. my_test = ['something', 'others', 'still others'] case 1: try/except hit = 0 for i in my_test: try: i.index('some') hit = 1 except ValueError: pass case 2: if/else hit = 0 for i in my_test: if 'some' in i: hit = 1 It seems to me that in a simple searching/matching, using if might be better and the code is smaller. Try/except would have its strengh on catching multiple errorrs. However, problems occur if the criteria is composed of "or" rather than "and". For instance: if (a in b) or (c in b): *do something try: b.index(a) b.index(c) *do something except ValueError: pass The above two are very different. Am I right here? -shuhsien From shane at zope.com Thu Sep 11 18:50:51 2003 From: shane at zope.com (Shane Hathaway) Date: Thu, 11 Sep 2003 18:50:51 -0400 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <m3smn3t5xx.fsf@mira.informatik.hu-berlin.de> References: <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <3F60B545.6030100@sci.fi> <mailman.1063306316.30786.python-list@python.org> <m3smn3t5xx.fsf@mira.informatik.hu-berlin.de> Message-ID: <3F60FC4B.2070401@zope.com> Martin v. L?wis wrote: > Shane Hathaway <shane at zope.com> writes: > > >>I wonder whether others would consider such a thing valuable, or even >>feasible. :-) > > > I consider it valuable, but not feasible. Contrary to your analysis, I > believe the biggest problem with shared memory is pointer/address > management. E.g. if you have a shared list L, and do > > L.append(1) > > then a reference to the object 1 is put into L[0]. However, the > pointer is only valid in the process writing the reference, not in > other processes. Fixing that is nearly impossible, except *perhaps* by > reimplementing Python from ground up. There are two ways to solve that: - Copy the "1" object into shared memory before passing it to L.append(). This would be nice and transparent, but also a little DWIM. - Create special object types just for shared memory. As it turns out, POSH (see Jeremy's link) takes the second strategy, apparently quite successfully! Anyone who has concerns about the GIL should take a long, hard look at POSH. It just might solve the problem for lots of people. Shane From BjornPettersen at fairisaac.com Wed Sep 17 15:32:13 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Wed, 17 Sep 2003 14:32:13 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624C8F@stpmsg00.corp.fairisaac.com> > From: Harri Pesonen [mailto:fuerte at sci.fi] > > Jeff Epler wrote: > > > On Tue, Sep 16, 2003 at 08:22:41PM +0300, Harri Pesonen wrote: > > > > > > It is more efficient to have one process and several threads, than > > > several processes each having one thread. > > > > > > If it's easier to code "several processes each having one thread", then > > I'll sure do it. I've accepted a 2x-100x speed hit by using Python, so > > if it's a 25% difference in efficiency, I won't sign up to wait for code > > that doesn't exist yet. > > But wouldn't it be better if Python had real multitasking? Comments like the > above mean that you accept Python as it is, fine. But usually people want to > make things better when they see that something can be improved. If my roof is > leaking, I have two choices: fix it or accept it. If I am able to fix it, then > I'll probably do it. [...] No, comments like the above realizes that there are certain tradeoffs. Reference counting as a primary garbage collection mechanism is fundamentally incompatible with multithreading in an object oriented language -- unless you have mitigating factors like the GIL. The number of locking operations quickly overwhelm actual computation. (I'm aware that you don't want shared data, however I completely fail to see the utility..) There is some research indicating that generational gc is more efficient with regards to total program run time in heavily mt oo applications, so that's certainly an interesting area to look into -- it would, however, require a fundamentally different language implmentation (one which didn't have the nice finalization guarantees CPython currently has). When it comes to applicability, I'm assuming you're not heading in this direction to do heavy computational work in pure Python(?) If all you want to do is watch your Python programs run maximally paralell, I would suggest Jython as an alternative without a GIL... -- bjorn From nid_oizo at yahoo.com_removethe_ Sat Sep 27 15:49:59 2003 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Sat, 27 Sep 2003 15:49:59 -0400 Subject: Reduce need of backslash In-Reply-To: <v029nv4ohqofkcggbcrtehl9j1v3dgjid0@4ax.com> References: <h4Ycb.75236$PD3.4793080@nnrp1.uunet.ca> <3F745445.D9628351@engcorp.com> <zM_cb.75296$PD3.4794304@nnrp1.uunet.ca> <v029nv4ohqofkcggbcrtehl9j1v3dgjid0@4ax.com> Message-ID: <LUldb.74647$ev5.1010409@wagner.videotron.net> Stephen Horne wrote: > Basically, when I need to break an expression over multiple lines, the > odds are that it already has parentheses anyway. And I wouldn't indent > that way anyway, I'd do it as... > > a = ( firstitem > + seconditem > + ( thirditem > * fourthitem > ) > ) But that's indentation anyway. If the rule would be "all lines with a superior indentation are part of the previous line", would that work? This way it would not be necessary to add the parenthesis. I wonder if I'm missing something... Regards, Nicolas From peter at engcorp.com Tue Sep 16 13:34:46 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Sep 2003 13:34:46 -0400 Subject: Duck Typing References: <221d8dbe.0309160101.4a09f2ad@posting.google.com> <mailman.1063720351.23661.python-list@python.org> <3gG9b.12137$3Y2.2543@news2.central.cox.net> <3F6732DB.F31A954E@engcorp.com> <DaH9b.12147$3Y2.9399@news2.central.cox.net> Message-ID: <3F6749B6.74601D54@engcorp.com> Steve Holden wrote: > > "Peter Hansen" <peter at engcorp.com> wrote in message > news:3F6732DB.F31A954E at engcorp.com... > > Steve Holden wrote: > > > > > > exquacktly [ducks and runs] > > ^^^^^ > > > > Steve, did you even _know_ you did this? You're sick! > > > > -Peter :-) > > Aah, I see, you think I'm stupid. No, I just knew Irmen was asleep at his keyboard. ;-) > Of course I knew - without the bracketed afterthought it would hardly have > been worth posting. > > I'll send you a bill ;-) If you make it a twenty, would that be a "sawduck"? -Peter From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Sep 11 07:22:40 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 11 Sep 2003 12:22:40 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <bjne1b$jm5$07$1@news.t-online.com> <jnkulv8t6e1qc3mb4pmf0k706e98pgmss2@4ax.com> <3F5F83B1.48763F85@alcyone.com> <cg5vlvgorsi88elsn9ur5ueavpg27d7ui3@4ax.com> <lpQ7b.1147$G1.6248@tor-nn1.netcom.ca> Message-ID: <lcm0mvgommt3n01qdr755jnobvsslv3e75@4ax.com> On Wed, 10 Sep 2003 21:45:38 -0700, "Carl Waldbieser" <waldbie at attglobal.net> wrote: >I think you could still run into a problem here with aliasing. For example: > > obj = Obj_Type () > x = obj > > obj.Do_Setup_Stuff_1 () > obj.Do_Setup_Stuff_2 () > obj.Do_Setup_Stuff_3 () > container.Add (ref obj) #rebinds obj to None > #later... > x.alter() #alters containers copy anyway Yes - that's what I meant by "this is by no means foolproof of course" in my post with message ID jnkulv8t6e1qc3mb4pmf0k706e98pgmss2 at 4ax.com. >This kind o problem exists in other languages like C++, too. The containers >in the C++ standard library copy elements to side-step these problems. When >copying becomes expensive, pointers to elements are used instead, but since >you can have multiple pointers to the same object, you run the risk of >clobbering data in the container if you are not careful. Its not unusual to use a reference counting scheme to restore the apparant copy semantics while avoiding unnecessary copying, but of course you are correct. >In practice, though, this type of behavior has rarely been a problem for me. Yes - if I trim down your tail quoting somewhat... >> So my 'most compelling example' isn't compelling at all. Damn. >> >> I've been thinking on this for some hours now and still not come up >> with a more compelling example (or at least not one which can't be >> better handled a different way) so I guess the idea is a dud. >> >> Bet you never expected me to admit that so easy ;-) From creedy at mitretek.org Fri Sep 5 10:56:00 2003 From: creedy at mitretek.org (Chris Reedy) Date: Fri, 05 Sep 2003 10:56:00 -0400 Subject: OT: best book in years In-Reply-To: <opruzmelopdd8opo@news.vo.lu> References: <opruzmelopdd8opo@news.vo.lu> Message-ID: <3f58a45a$1_6@corp.newsgroups.com> Patrick Useldinger wrote: > Hi All, > > I am going to stay in hospital for a week or so (nothing serious), and > am trying to find a book or two to read there. As I have not come across > anything spectacular recently (except Python in a Nutshell), I would > like to know what *you* consider to be the best book you have read in > the last few years, about Python or IT in general. > > -Patrick This one's been out a few years, but I really enjoyed it when I got it as a Christman gift: Why Buildings Falls Down by Matthys Levy and Mario Salvadori It's an easy read and a good education in the kinds of "bugs" that infect building construction -- something that's always held up to software types as an example of a mature engineering discipline. Chris -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From andrew-pythonlist at puzzling.org Sun Sep 21 21:08:38 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 22 Sep 2003 11:08:38 +1000 Subject: Twisted Matrix and Python Scripts In-Reply-To: <7b454334.0309211241.4fce86ff@posting.google.com> References: <7b454334.0309211241.4fce86ff@posting.google.com> Message-ID: <20030922010838.GA2008@frobozz> On Sun, Sep 21, 2003 at 01:41:04PM -0700, Fazer wrote: > Hello, > > I am very interested in fooling around with Twisted Matrix's HTTP Web > Server. I was thinking if .rpy scripts would run much faster than > traditional CGI scripts? They'll generally be much faster, because there's no need to start a fresh python process for every request. It's worth noting, though, that .rpy scripts aren't meant to be Twisted equivalent of CGI scripts; they should simply create and configure a twisted.web.resource.Resource (or subclass thereof). If your .rpy is more than 10 lines, you're almost certainly using it the wrong way... see http://twistedmatrix.com/documents/howto/web-development. > After looking how asynchronous Twisted's framework really is, I have > been interested in it. By the way, you might find you have better luck with Twisted questions on the Twisted mailing list, twisted-python at twistedmatrix.com. Not all of the Twisted people read comp.lang.python regularly. -Andrew. From pieter at countersnipe.com Tue Sep 2 20:16:45 2003 From: pieter at countersnipe.com (Pieter Claassen) Date: Wed, 03 Sep 2003 01:16:45 +0100 Subject: python short conditional? Message-ID: <pan.2003.09.03.00.16.45.270773@countersnipe.com> I am looking to find a short conditional for python equivalent to the perl question mark operator statement? if true:else false Any recommendations on this? Pieter From bokr at oz.net Thu Sep 11 13:26:39 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Sep 2003 17:26:39 GMT Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> Message-ID: <bjqb8f$d9k$0@216.39.172.122> On Wed, 10 Sep 2003 14:59:43 +0100, Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: > >I have in the past suggested that Python functions could use some kind >of modifier token for parameters to indicate pass-by-reference, so >that immutable items in particular could be modified (or more >accurately replaced) by the function, with that modification affecting >what the caller sees. In case I'm explaining this badly, here is how >Python currently works... > >>>> def Inc(p) : >... p += 1 >... >>>> x = 1 >>>> Inc(x) >>>> x >1 > >... and here is (roughly) what I'd like to be able to do... > >>>> def Inc(ref p) : >... p += 1 >... >>>> x = 1 >>>> Inc(x) >>>> x >2 ref p logically implies that Inc will receive somehow both the information *behind* the name 'p' -- i.e., the caller's name for the value that the local parameter name 'p' is temporarily bound to -- *and* the specific namespace of the caller. The implication is that there is a name that should be unchanged, whatever it is, but rebound in its namespace to an updated value. We can't mess with the actual value at the other end of the binding, since that could be shared and/or immutable. You could do this very explicitly, e.g., explicitly pass both name space and name string, with an ordinary dict playing the namespace role: >>> ns = {'x':1} >>> ns['x'] 1 >>> def incr(namespace, name): ... namespace[name] += 1 ... >>> incr(ns, 'x') >>> ns['x'] 2 or, using the __dict__ of an object instance >>> ns2 = type('',(),{})() >>> ns2.y = 10 >>> incr(ns2.__dict__, 'y') >>> ns2.y 11 obviously, we could write incr to accept an instance and a name and do inst.__dict__[name]+=1 instead of nsdict[name]+=1, but the point is we are somehow being explicit in specifying both namespace and the name to be rebound. Implementing ref would imply automating something similar hidden in the compiled code, IWT. But it gets messy fast, I think. what if you write a =['foo',[23]]; Inc(a[1][0]) ? Should that 23 be rebound to a 24? You can't always analyze the expression statically, so you can't even presume that Inc will be the same global binding by the time a[1] has been evaluated. So you'd have to look ahead to see if Inc should be passed the address of the hidden pointer to 0 involved in the [0] or the pointer to 0 itself. But then you'd have to figure out whether <whatever-a[1]-is>[0] can be used that way. Should any mutable object that supports __getitem__ and __setitem__ be able to produce the target address for its __setitem__ for conditional passing to a function like Inc? ISTM a ref thing would ripple pretty far into the binding methodology of Python. Regards, Bengt Richter From peter at engcorp.com Wed Sep 17 09:29:33 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Sep 2003 09:29:33 -0400 Subject: Test message. Please ignore References: <e431ae34.0309120216.7ca12eb5@posting.google.com> <3F61AAA0.62F58E97@engcorp.com> <tyf8yonlks9.fsf@pcepsft001.cern.ch> Message-ID: <3F6861BD.71E8C638@engcorp.com> Jacek Generowicz wrote: > > Peter Hansen <peter at engcorp.com> writes: > > Use misc.test, > > Last time I tried that, I immediately got 12 spams, half of them > claiming that they weren't spam, because I explicitly asked for them > merely by posting to misc.test. > > That's really great, especially if you're just trying out your fresh > and unknown-to-spammers email account :-) Anyone using a real email account with either misc.test or comp.lang.python should expect to be instantly indundated with spam anyway. A fellow from work posted recently with a new-before-seen-on-Usenet email address and saw a step-increase in his spam at work immediately afterwards. Posting to misc.test doesn't seem likely to increase the amount of spam one gets if one has or intends to post to a regular newsgroup. If you're really concerned, you can easily spoof your address when posting the test as well... And there are tools to deal fairly effectively with spam anyway, so I personally pretty much ignore it. (Only a couple of spam messages a day slip through for me, and if I cared enough I could shut down the accounts pretty quickly as they all come from real people.) > > not a regular newsgroup, for tests please. > > Are you sure he wasn't posting to the mailing list ? Not at all, but it doesn't change the point. Test posts are almost never necessary to either a mailing list or a newsgroup, and when they are necessary an explanation in the message as to why it was required is always appropriate, and ought to be considered mandatory. All told, there's really no excuse for posting tests to c.l.p or the mailing list without a good reason, and an included explanation, so I plan to continue trying to educate the obvious newbies who don't follow this advice. My guess is that for every one who posts a test here, there are five who see my reply and have never heard of misc.test before, and it's worth it to help them avoid making the same mistake. -Peter From jwdillworth at yahoo.com Thu Sep 4 08:28:07 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Thu, 4 Sep 2003 05:28:07 -0700 (PDT) Subject: questions In-Reply-To: <HnWdnRoKt7GUP8uiU-KYgg@kconline.com> Message-ID: <20030904122807.97700.qmail@web41103.mail.yahoo.com> --- Andy <Hoosbruin at Kconline.com> wrote: > > Would like to try Python...... > > Can you use Python to access SQLServer... if so do you have an example. The win32all package includes an ODBC module. I've used this extensively, it works quite well. It's here: http://pywin32.sourceforge.net/ > > What are the strengths and weaknesses of Python.? > > Is it like vbscript ? > > > Example code of things that it's good at.... to get me started For code examples see the Python cookbook (though some examples are rather advanced): http://pythoncookbook.activestate.com/ These success stories are also interesting: http://www.pythonology.com/success > > Thanks... > > > > -- > http://mail.python.org/mailman/listinfo/python-list From amdescombes at qualicontrol.com Wed Sep 17 06:29:10 2003 From: amdescombes at qualicontrol.com (Andre Michel Descombes) Date: Wed, 17 Sep 2003 12:29:10 +0200 Subject: Free Data Quality Management with Python UK Seminar Message-ID: <bk9d04$a52$1@news-reader1.wanadoo.fr> Hi, Test&Go is a Python based tool, which makes developing Python DQM solutions a cinch. I am pleased to inform you that QualiControl (UK) Ltd are holding the first of a number of FREE Seminars on the issues of Data Quality and Control on 1st October 2003 at the Royal Oriental Hotel in Luton, Bedfordshire (the second will be 15th October). The seminar will cover the problems encountered by companies with their data quality as well as the knock on effects that these issues have across an organisation and on to its partners or customers. The seminar will also include a demonstration of Test&Go - one of Europe's leading software solutions for controlling the quality and integrity of data in all information processes, particularly focussing on Data Quality Management and Python. Test&Go has provided a great ROI within the Government and Financial industries as well as for Software Testing, Data Cleansing and eCommerce environments within a number of commercial organisations. Case studies will also feature in the seminar on how companies have overcome their data quality issues and the benefits gained. If you would like more information on Test&Go or to register for this seminar, please go to http://www.qualicontrol.com/eng/seminar/seminar.php?logo=logo_info.jpg Regards, Andre M. Descombes R&D Director QualiControl (UK) Ltd Tel: +44 (0)1582 513317 www.qualicontrol.com/eng/default.php From simonb at webone.com.au Sat Sep 6 19:51:36 2003 From: simonb at webone.com.au (Simon Burton) Date: Sun, 07 Sep 2003 09:51:36 +1000 Subject: Any tools to print source code call hierarchy References: <mailman.1062873250.31920.python-list@python.org> <6ee58e07.0309061534.5f8cf00f@posting.google.com> Message-ID: <pan.2003.09.06.23.51.35.802469@webone.com.au> On Sat, 06 Sep 2003 16:34:21 -0700, Lothar Scholz wrote: ... > > Because python is a dynamical typed non image language there is no > tool that can do this and there never will be any (at least one that > is not using heuristics or sampled data from previous runs). hmmm... I think (some) static analysis may be possible. The main thing to exclude is eval/exec but even then, yes you're right, some programs would just have to be run to find out what they do. I remember reading some interesting things here: http://www.python.org/doc/essays/cp4e.html In particular: "Cormac Flanagan and Matthias Felleisen. Componential Set-Based Analysis. ACM Transactions of Programming Languages and Systems" Simon. From enrica_dente at hotmail.com Thu Sep 4 08:50:04 2003 From: enrica_dente at hotmail.com (enrica dente) Date: Thu, 04 Sep 2003 12:50:04 +0000 Subject: Search and Replace in Zope Message-ID: <Law14-F116oygXLsxpT000341aa@hotmail.com> Dear All, I emailed you sometime ago. I need your help again. This time I really need it. I haven't been able to find a solution that allows me to search for all the <a href=/welcome links in the original pages created by Zope. How do I convert these pages into a files system that I can search so that I can also search and replace HTML code? Thanks for your help. Enrica _________________________________________________________________ Get Hotmail on your mobile phone http://www.msn.co.uk/msnmobile From skip at pobox.com Fri Sep 5 12:39:39 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Sep 2003 11:39:39 -0500 Subject: Anybody else having problem *sending* mail to this list? In-Reply-To: <yuGcnUKAscCcQ8qiXTWJjA@comcast.com> References: <mailman.1062713657.19120.python-list@python.org> <yuGcnUKAscCcQ8qiXTWJjA@comcast.com> Message-ID: <16216.48203.690034.549439@montanaro.dyndns.org> Terry> Yes, a worldwide virus-induced mail blizzard. This has been my biggest gripe about the damn virus. The virus itself was no problem for me since I don't use Windows, but the thousands of "you have a virus!" mails sent in response clogged my inbox until I trained SpamBayes to view them as spam. Is there any reasonable way to get the anti-virus vendors to realize they are a very large part of the problem? Shouldn't virus scanners simply eat the virus and not send another mail? Does anyone have a list of a-v vendors' email addresses so I can harangue them a bit on the topic? Thx, Skip From sheu at bu.edu Sat Sep 20 10:55:29 2003 From: sheu at bu.edu (Shu-Hsien Sheu) Date: Sat, 20 Sep 2003 10:55:29 -0400 Subject: Problems with string and lists (searching and replaceing) In-Reply-To: <bkhnpn$hgc$1@news.hccnet.nl> References: <pan.2003.09.20.10.51.37.875000@hotmail.com> <bkhnpn$hgc$1@news.hccnet.nl> Message-ID: <3F6C6A61.1010508@bu.edu> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20030920/a6747405/attachment.html> From jjl at pobox.com Wed Sep 3 08:53:16 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Sep 2003 13:53:16 +0100 Subject: Code complete electronic version ? References: <b15d2792.0309030332.364532d1@posting.google.com> Message-ID: <871xuyowxv.fsf@pobox.com> post400 at prontomail.com (post400) writes: > apparently there is a very famous book that every developer should > read: Code complete by Steve McConnell ! It's an interesting book, I agree, certainly well worth a read. > Is there an electronic version freely downloadable ? After all, the > book was released in 1993 , it should have been public domain by now ! Clearly not, since you're contemplating buying it ;-) It's not a narrowly-focused technical book, so it hasn't gone out of date (even though it says almost nothing about object orientation -- in fact, that's part of what makes it interesting). > It would be nice to have a try before ! 50? is not exactly cheap ! > What do you think ? Is it worth the money or not ? Do you have access to a public library? In North America and Western Europe, they're quite likely to be able to lend you a copy (even if it's not in your local library, they can borrow it from a larger library). John From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Sep 16 07:59:39 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 16 Sep 2003 13:59:39 +0200 Subject: Duck Typing In-Reply-To: <221d8dbe.0309160101.4a09f2ad@posting.google.com> References: <221d8dbe.0309160101.4a09f2ad@posting.google.com> Message-ID: <3f66fb2c$0$58709$e4fe514c@news.xs4all.nl> srijit at yahoo.com wrote: > I have been seeing this term "duck typing" for quite sometime now. It > will be nice if one of us can give an example in Python demonstrating > duck typing and/or link to some Python references. Is this helpful: http://www.razorvine.net/python/PythonLanguageConcepts (paragraph 'dynamic typing') ? --Irmen de Jong From bac at OCF.Berkeley.EDU Mon Sep 15 14:11:44 2003 From: bac at OCF.Berkeley.EDU (Brett C.) Date: Mon, 15 Sep 2003 11:11:44 -0700 Subject: strptime() backported to Jython 2.1 Message-ID: <3F6600E0.3000102@ocf.berkeley.edu> I have received a few requests since the 'Python Cookbook' was published to edit my code for a strptime() function in pure Python to run on Jython 2.1 . I have finally come about and made the necessary changes and put them online (thanks to Jon Franz for giving the final push). The code can be found at the Python Cookbook web site at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/56036 . It is not the fastest or best version of the code (that will always be in the Python CVS MAIN tree), but it seems to work (I have not done extensive testingm but all the changes were minor). I now consider this backport finished. All future enhancements to strptime will continue to go into the Python CVS but will not be backported. If you want the latest and greatest features then consider helping to move Jython forward to its next version or upgrading your version of CPython. -Brett From halley at play-bow.org Fri Sep 5 17:02:12 2003 From: halley at play-bow.org (Bob Halley) Date: 05 Sep 2003 14:02:12 -0700 Subject: file.close() freezes my script In-Reply-To: <c498bc9a.0309050041.3cc0a254@posting.google.com> References: <c498bc9a.0309050041.3cc0a254@posting.google.com> Message-ID: <m37k4n0x0r.fsf@woof.play-bow.org> schwerdy at web.de (schwerdy) writes: > I created a script that handles SC and CSV files. To convert CSV (or > in my case: pipe ('|') seperated values) to SC, I want to hunt my CSV > lines through /usr/bin/psc. Therefore I did: > > tofilter, fromfilter, error = os.popen3("psc -S -L -d '|'") > map(tofilter.write,lines) > tofilter.close() > > For some CSV-files my script freezes at tofilter.close(). Removing > some lines from the "lines" sequence (that represents the CSV-file) > always helps. But imho "psc" is not the cause. Piping my CSV-file > through psc in bash always works. Isn't it crazy? I tried python2.2 > and python2.3 from the debian distribution. > > Anyone who has an explanation, workaround, hint or anything? This sounds like a classic pipe deadlock. My guess is that the child process is blocked trying to write to its stdout, which you haven't read. The parent is blocking trying to finish all that writing. The issue is described in the Python Library Reference, section 6.8.2, "Flow Control Issues". If you wrote psc's output to a file, used select(), or used different threads (e.g. a writer thread and a reader thread), you could avoid the deadlock. /Bob From p-abel at t-online.de Fri Sep 19 05:37:11 2003 From: p-abel at t-online.de (Peter Abel) Date: 19 Sep 2003 02:37:11 -0700 Subject: file position *tell()* works different Message-ID: <13a533e8.0309190137.2df0cc60@posting.google.com> Hi all, I'm working under W2k with Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 I have a file *test_data.txt* with the following content: 0123456789 0123456789 abcdefghi ABCDEFGHIJKLMNOPQ and I work on it with the following python script: # Open NOT in binary mode fp=file('test_data.txt','r') a='xx' while a: print 'Filepointer: %3d' % fp.tell() a=fp.readline() fp.close() print # Open IN binary mode fp=file('test_data.txt','r+b') a='xx' while a: print 'Filepointer: %3d' % fp.tell() a=fp.readline() fp.close() Now, when test_data.txt is saved in PC-mode with 0xC, 0xA as newline it works correct. But when I save the file in UNIX-Mode with 0xA as newline, my script gives me the following output, where that one with the file not opened in binary mode is wrong: Filepointer: 0 Filepointer: 7 Filepointer: 19 Filepointer: 30 Filepointer: 49 Filepointer: 51 Filepointer: 0 Filepointer: 11 Filepointer: 22 Filepointer: 32 Filepointer: 50 Filepointer: 51 When I try this under HP-UX it works fine in both cases. So I wonder if the function *tell()* is not correctly implemented under win32. Regards Peter From __peter__ at web.de Wed Sep 24 14:46:16 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 24 Sep 2003 20:46:16 +0200 Subject: Pre-PEP: reverse iteration methods References: <HA5cb.185$kD3.168@nwrdny03.gnilink.net> <tth3nvcb9oprv23bincf80c74051227vgv@4ax.com> <vdlcb.287$kD3.194@nwrdny03.gnilink.net> Message-ID: <bksos0$jvi$07$1@news.t-online.com> Raymond Hettinger wrote: > * It behaves badly with infinite iterators as inputs [...] > def ireverse(obj): > assert not hasattr(obj, 'keys') # let inifinite iterators identify themselves assert not hasattr(obj, 'infinite') > try: > for i in xrange(len(obj)-1, -1, -1): > yield obj[i] > except (AttributeError, TypeError): > x = list(obj) # XXX fails with infinite iterators > x.reverse() > for elem in x: > yield elem As infinite iterators are rare, it would not be too cumbersome to let them identify themselves as such. Peter From paddy3118 at netscape.netNOTthisBIT Thu Sep 18 17:30:39 2003 From: paddy3118 at netscape.netNOTthisBIT (Donald 'Paddy' McCarthy) Date: Thu, 18 Sep 2003 22:30:39 +0100 Subject: Setting environment variables In-Reply-To: <cscab.12804$g4.258706@news1.nokia.com> References: <cscab.12804$g4.258706@news1.nokia.com> Message-ID: <5tpab.110$WD5.5@news-binary.blueyonder.co.uk> Sami Viitanen wrote: > Hello, > > Is there any other way to set variables than os.putenv(). > > Putenv doesn't actually put any values to actual system variables.. > > I'm trying to set CVSEDITOR variable automatically from script > so that user wouldn't have to set that him/herself. CVS can't use variable > set with putenv(). You could do the equivalent of: Paddy at maximillian ~ : echo $SHELL /bin/bash Paddy at maximillian ~ : unset foo Paddy at maximillian ~ : eval `python -c 'print "foo=Hello;export foo"'` Paddy at maximillian ~ : echo $foo Hello Paddy at maximillian ~ : I use the following for setting up quite complex environments at work: http://modules.sourceforge.net/ Pad. From hanzspam at yahoo.com.au Wed Sep 24 02:56:21 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 23 Sep 2003 23:56:21 -0700 Subject: Pre-PEP: reverse iteration methods References: <HA5cb.185$kD3.168@nwrdny03.gnilink.net> <hJ6cb.1252$RW4.107@newsread4.news.pas.earthlink.net> <vn1uus5a74ce3a@news.supernews.com> <w57cb.1289$RW4.1142@newsread4.news.pas.earthlink.net> Message-ID: <840592e1.0309232256.26f7fd1e@posting.google.com> "Andrew Dalke" <adalke at mindspring.com> wrote in message news:<w57cb.1289$RW4.1142 at newsread4.news.pas.earthlink.net>... > Sure. Then it'll given an exception. The implementation > should turn around and raise the proper exception there > instead of a "len doesn't exist" one. > > There's also a problem that len works on a dict but > __getitem__(int) will only work if the dict stores 0->n-1 > as keys. How about using a temporary sequence if __riter__ isn't defined? It's slow, but would work with all non-infinite iterators that don't have strange side effects (vast majority). def riter(obj): try: rit = getattr(obj, "__riter__") except AttributeError: # assuming list has __riter__, the following could be: # for x in riter(list(obj)): # yield x seq = list(obj) n = len(seq) while n != 0: n -= 1 yield seq[n] else: for term in rit(): yield term # reverse iteration of file f = file('riter.py') try: for line in riter(f): print line, finally: f.close() # reverse iteration of a dictionary for x in riter({'foo':1, 'bar':2}): print x, I changed it to use a shorter name as suggested by Reedy, to be similar with rfind etc. I also prefer a function instead of a method, as the function can provide (slow) default behaviour for iterators that don't explicitely support reverse iteration. From cliechti at gmx.net Sat Sep 6 20:00:23 2003 From: cliechti at gmx.net (Chris Liechti) Date: 7 Sep 2003 02:00:23 +0200 Subject: [Jargon] Python glossary - contribute your definitions References: <16218.13681.159432.907101@montanaro.dyndns.org> <mailman.1062881711.16669.python-list@python.org> Message-ID: <Xns93EF1469C4E3Ccliechtigmxnet@62.2.16.82> "Mike C. Fletcher" <mcfletch at rogers.com> wrote in news:mailman.1062881711.16669.python-list at python.org: > Skip Montanaro wrote: > ... >>I'm still interested in getting this off the ground, though. To make >>it more likely that something significant gets done, I created a Wiki >>to which people can add definitions: >> >> http://manatee.mojam.com/python-glossary > ... > Seems like something that could be hashed out faster and more > reasonably as a thread on comp.lang.python where people propose, then > vote on words (and/or definitions) suitable for a glossary. For > example: [cut the nice examples] if you entered those right away in the wiki it would have more entries by now ;-). Seriously, i think it makes more sense to write them in the wiki then discuss them here. One has not to look over dozzens of news threads to get the definitions but can look in one place, the wiki. that looks easier to me. and there is a good example on how it works when many people submit their part and the rating is done after a while, based on that submissions. i'm talking of the great python cookbook that is now available as a printed book. the use of a wiki may require a bit familiarization but then its realy a nice and efficent tool. chris [cut rules] -- Chris <cliechti at gmx.net> From SBrunning at trisystems.co.uk Mon Sep 29 11:00:22 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 29 Sep 2003 16:00:22 +0100 Subject: Prime number module Message-ID: <31575A892FF6D1118F5800600846864D014B29C3@intrepid> > From: Dag [SMTP:dag at velvet.net] > Is there a python module that includes functions for working with prime > numbers? I mainly need A function that returns the Nth prime number and > that returns how many prime numbers are less than N, but a prime number > tester would also be nice. I'm dealing with numbers in the 10^6-10^8 > range > so it would have to fairly efficient http://www.nmt.edu/~shipman/soft/clean/prime.html any good? Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- 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 holmboe at kth.se Sat Sep 6 17:20:00 2003 From: holmboe at kth.se (Michael) Date: 6 Sep 2003 14:20:00 -0700 Subject: Newbiequestion about lists and arrays.... Message-ID: <9193c0d1.0309061320.a0f430f@posting.google.com> Hi pythonians! (or whatever you call yourselfs...) I would like to use an multidimensional matrix (3D or more) with numbers (int:s and float:s). Could i use lists or arrays? How can i retrieve a single element out of a list thats already in an other list thats already in an other list (and so on...) An example... c=[1]*3 for y in range(3): for x in range(3): c[x]=[1,2,3] p[y]=c p[1][1][1]=888 print p[1][1][1] print p for this code example, how do i assign 888 to only one element (for example, the element in the middle) in the matrix and not to the three elements shown below? >>> 888 [[[1, 2, 3], [1, 888, 3], [1, 2, 3]], [[1, 2, 3], [1, 888, 3], [1, 2, 3]], [[1, 2, 3], [1, 888, 3], [1, 2, 3]]] >>> Why does: p[0][1][1]=888 and p[1][1][1]=888 print out the same result? Helping bitteplease. /Michael From andrea at proceryon.at Tue Sep 9 05:02:23 2003 From: andrea at proceryon.at (andrea) Date: 9 Sep 2003 02:02:23 -0700 Subject: Problem with ButtonRelease-2 event in Text widgets Message-ID: <4feefc55.0309090102.4ff7dad@posting.google.com> I have a dialog with a Pmw.ScrolledText widget were a user can paste a text with button-2. After pasting i want to know how many characters are pasted. But when the '<ButtonRelease-2>' event occurs the text is not pasted, this happens afterward. With '<KeyRelease>' events it works fine (eg 'Shift'+'Insert'). Why? Is there a possibility to get the pasted text at this moment? TIA! ### sample code: ### import Pmw class CText: def show (self): dlg = Pmw.Dialog() self.textbox = Pmw.ScrolledText(dlg.interior()) self.textbox.pack() self.textbox.component('text').bind('<KeyRelease>', self.printLength) self.textbox.component('text').bind('<ButtonRelease-2>', self.printLength) dlg.activate() def printLength (self, event): print len(self.textbox.get()) if( __name__ == '__main__' ): textObj = CText() textObj.show() From Vincent.Raaijmakers at ge.com Mon Sep 15 09:00:38 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Mon, 15 Sep 2003 08:00:38 -0500 Subject: I need to make Excel/Powerpoint-style charts. Message-ID: <971323274247EB44B9A01D0A3B424C85E46E0E@FTWMLVEM02.e2k.ad.ge.com> Take a look at www.reportlab.com !! Reportlab provides everything for you for creating pdf documents. Written in 100% python and it is for free (which is unbelievable) Full set of documentation and great demo's. Vincent -----Original Message----- From: python at sarcastic-horse.com [mailto:python at sarcastic-horse.com] Sent: Tuesday, September 09, 2003 11:19 AM To: python-list at python.org Subject: I need to make Excel/Powerpoint-style charts. Hi- My office produces a lot of charts based on time-series data. We use MS powerpoint and excel to make these charts. The data gets updated regularly, but there doesn't seem to be an easy way to automate updating the charts using these packages. So, we spend a non-trivial amount of time manually updating lots of spreadsheets to redraw the charts we need. I hope to find some sort of python graphics library that can make charts similar to Excel and Powerpoint, and then I can start automating these tasks. Here is an example of the charts we make: http://www.sarcastic-horse.com/example.pdf #52k size file. Are there any packages that can do similar charts? I need to be able to chart time-series data with occasional missing observations. I also need to be able to shade some regions of the charts, and add text titles, captions and notes. I'm (slowly) learning the reportlab package, and it looks good, but I wanted to check if there was an even better solution out there. Thanks for the help. -- http://mail.python.org/mailman/listinfo/python-list From cliechti at gmx.net Wed Sep 17 15:56:11 2003 From: cliechti at gmx.net (Chris Liechti) Date: 17 Sep 2003 21:56:11 +0200 Subject: distutils on win32 with link.exe -- use dlls? References: <mailman.1063735042.3212.python-list@python.org> <u65jssiml.fsf@fitlinxx.com> <Xns93F8DC80D7DDEcliechtigmxnet@62.2.16.82> <isnsikbf.fsf@python.net> Message-ID: <Xns93F9DF2B7A4CBcliechtigmxnet@62.2.16.82> Thomas Heller <theller at python.net> wrote in news:isnsikbf.fsf at python.net: > Chris Liechti <cliechti at gmx.net> writes: > >> the current gcc in cygwin/mingw can link directly against DLLs (it >> creates the imp lib on the fly) one reason more to use free software >> ;-) > > Can these implibs be used by MSVC? it does not strore them on the disk in that case. there are separate tools to generate import libs too but the msvc onces and the gnu ones are NOT compatible. chris -- Chris <cliechti at gmx.net> From davidsch at verity.com Fri Sep 19 20:00:45 2003 From: davidsch at verity.com (David Schnepper) Date: Fri, 19 Sep 2003 17:00:45 -0700 Subject: whitespace In-Reply-To: <20030919234817.GC2478@thoth.homegain.com> Message-ID: <DGEBJOLJPLKOEDDMLCGIGEPGCDAA.davidsch@verity.com> >>> a = " space tab\tlf\nreturn\rFF\f " >>> "".join(a.split()) 'spacetablfreturnFF' >>> Quoting RR (rr84 at cornell.edu): > Is there an easy way in python to remove whitespace from a string? From mcfletch at rogers.com Sun Sep 14 01:44:09 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 14 Sep 2003 01:44:09 -0400 Subject: [Ann] TTFQuery 0.2.5 (minor update) available Message-ID: <3F640029.2010104@rogers.com> TTFQuery has had a few minor bug-fixes over the last week (thanks to John Hunter). You can get the updated version from the homepage: http://ttfquery.sourceforge.net/ TTFQuery builds on the FontTools package to allow for searching fonts by font name or family, as well as extracting glyph outlines (note: FontTools now supports this last natively, but TTFQuery hasn't been updated to use that feature yet). As it directly interacts with font files, it does not require that the fonts be installed. There is also some rudimentary logic for locating font files on Win32 and Linux systems. Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Sep 26 00:46:35 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 05:46:35 +0100 Subject: Another Python rookie trying to port to C/C++ question. References: <GSGcb.24394$dk4.776543@typhoon.sonic.net> <8yoc1wwt.fsf@python.net> <b3Jcb.24430$dk4.777126@typhoon.sonic.net> <Pine.LNX.4.44.0309260022410.21689-100000@urchin.earth.li> Message-ID: <71h7nvg9gtktvb7ekn28et4rc6iicjnsh9@4ax.com> On Fri, 26 Sep 2003 00:33:46 +0100, Tom Anderson <twic at urchin.earth.li> wrote: >Patricia trees (my personal favourite :) Oh goody - Something new to look up! -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From grante at visi.com Thu Sep 25 22:55:57 2003 From: grante at visi.com (Grant Edwards) Date: 26 Sep 2003 02:55:57 GMT Subject: When did Windows start accepting forward slash as a path separator? References: <b16e4ef7.0309251550.724a57f@posting.google.com> <slrnbn74ch.s2.bignose-hates-spam@rose.localdomain.fake> Message-ID: <slrnap4tqk.18h.grante@localhost.localdomain> In article <slrnbn74ch.s2.bignose-hates-spam at rose.localdomain.fake>, Ben Finney wrote: >> But now, among a small group of cognoscenti, it is a truism that this is a >> myth, and that Windows will allow you to use either the forward or the >> backward slash as a pathname separator. > > I highly doubt it, since the forward slash (or just "slash") is the > conventional Windows command-line option indicator, That was configurable back in the DOS days. There was a "well-known" byte in system RAM that contained the "switch" character. IIRC, DOS even shipped with a utility to change that value. > analogous to the hyphen on Unix. To accept it as the start of a filename > would break zillions of existing systems, for no appreciable benefit to > Microsoft. Forward slashes always worked fine for me. > Python automagically determines the path component separator, os.sep, > and uses it for most file path transformations to and from the internal > language's '/'. > > <http://www.python.org/doc/2.3.1/lib/os-path.html#l2h-1552> > > Is this perhaps what gives you the impression? Forward slashes work in C as well. -- Grant Edwards grante Yow! Yow! It's some people at inside the wall! This is visi.com better than mopping! From buzzard at urubu.freeserve.co.uk Wed Sep 17 19:14:07 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Thu, 18 Sep 2003 00:14:07 +0100 Subject: convert ints in a range to strings References: <bkap6g$4o1$1@solaris.cc.vt.edu> Message-ID: <bkapkk$gpi$1@newsg1.svr.pol.co.uk> "hokieghal99" <hokiegal99 at hotmail.com> wrote in message news:bkap6g$4o1$1 at solaris.cc.vt.edu... > Hi, > > I'm trying to do this: > > ------------------------------ > a="192." > b="168." > c="1." > r = range(256) > for r in r: > print a + b + c + r > ------------------------------ > > But, I get this error: cannot concatenate 'str' and 'int' objects. So, I > need to convert the ints in the range to strs, but I do not know how to > do that. Could someone help me? Ultimately, I want to print out > something like this to a text file: > > 192.168.1.0 > 192.168.1.1 > 192.168.1.2 > ... > 192.168.1.255 > > Thanks!!!! > > > > >>> a="192." >>> b="168." >>> c="1." >>> r = 12 >>> a + b + c + str(r) '192.168.1.12' >>> '%s%s%s%d' % (a,b,c,r) '192.168.1.12' >>> I believe the second approach is generally faster. Duncan From mertz at gnosis.cx Fri Sep 26 12:40:56 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Fri, 26 Sep 2003 12:40:56 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <wCGcb.3064$yU5.2141@nwrdny01.gnilink.net> <8RScb.169633$R32.5449258@news2.tin.it> <uk77vhagj.fsf@boost-consulting.com> <WNYcb.12686$yD1.1505440@news20.bellglobal.com> <eppstein-B529F3.09181826092003@news.service.uci.edu> Message-ID: <YwGd/kKkXQgH092yn@gnosis.cx> David Eppstein <eppstein at ics.uci.edu> wrote previously: |ireverse, like imap(), izip(), etc., suggests that the operation happens |without the memory overhead of copying the whole sequence into a list |before reversing it. Do you have some plan for how to do that e.g. with |simple generators? Or easy to understand explanation for which things |can be ireversed and which can't? Or even just a DECIDABLE explanation for which things can be 'ireversed' and which can't[*]. Yours, Lulu... [*] And if you -can- produce such an explanation, I can almost guarantee you a Fields Medal, and probably a Nobel Prize also. -- 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 emile at fenx.com Mon Sep 29 15:37:10 2003 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Sep 2003 12:37:10 -0700 Subject: Where? run directory References: <37152603.0309291109.4f16d4b9@posting.google.com> Message-ID: <bla1g7$a0p8i$1@ID-11957.news.uni-berlin.de> "Adrian Smith" asks, > On a windows system. > I'm trying to get a Mcmillian created program to be 'independent' but > the first thing I need to do is find out where the program is being > run from, not the shortcut but the generated exe. This is where I keep > all the set-up files that I need to access. > Currently I have a fixed directory but don?t want to write anything > into the registry. > Is there a reg setting though that gives the address of the last run > program (presumably my program) or something like a working directory > setting. > I don?t want to have to search for the program through the directory > structure as that would be very time consuming. > I think you're looking for: import os print os.path.dirname(__file__) HTH, Emile van Sebille emile at fenx.com From toby at rcsreg.com Wed Sep 17 13:40:01 2003 From: toby at rcsreg.com (Tobiah) Date: 17 Sep 2003 10:40:01 -0700 Subject: "New" style classes Message-ID: <dad71773.0309170940.6dc68a8@posting.google.com> I gather that a "new style" class inherits from object. Is this to be considered the way to make all classes from now on? If not, when will I know to inherit from object? I noticed that it clutters up pydoc output. Thanks, Tobiah From tzot at sil-tec.gr Mon Sep 8 09:00:25 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 08 Sep 2003 16:00:25 +0300 Subject: datetime: .datetime-.datetime = .timedelta, .time-.time=TypeError ? Message-ID: <esuolvc6tuuhfub8jtobffv722281t7p56@4ax.com> Is there any reason for datetime.time subtraction not returning a datetime.timedelta object, just like datetime.datetime subtraction does? It doesn't feel good having to use dumb year, month, day arguments constructing datetime object when doing only time arithmetic. If there is no specific reason apart from lack of time (no pun), I'm willing to research it and write a patch (I haven't seen the code, but I believe it would be quite easy). TIA -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From basile-news at starynkevitch.net Sat Sep 6 08:35:13 2003 From: basile-news at starynkevitch.net (Basile STARYNKEVITCH) Date: 06 Sep 2003 14:35:13 +0200 Subject: Why python??? References: <mailman.1062790509.19411.python-list@python.org> <bjarq6$j45$00$1@news.t-online.com> <NO66b.30883$R32.926812@news2.tin.it> <bjb4hk$ohm$01$1@news.t-online.com> <87fzjalogu.fsf@pobox.com> <bjccn3$eb$07$1@news.t-online.com> <87vfs6unsx.fsf@pobox.com> Message-ID: <q5r4qzqnlha.fsf@hector.lesours> >>>>> "John" == John J Lee <jjl at pobox.com> writes: [...] John> "Michael Peuser" <mpeuser at web.de> writes: Michael>> Same argument holds for supercomputing as well. I may be Michael>> wrong but I doubt that the ASCIs will ever see much Michael>> Python in their production lifetime. John> ASICs, you mean? Well, no, but so what? I don't think John> anybody has ever *claimed* that Python is suitable for that John> kind of application. No, ASCI are big US government (DoE or DoD) supercomputers (used notably for nuclear weapons computations). However, contrarily to Michael's belief, it won't surprise me at all that some big numerical computations are driven by scripting languages (scripts which call big number crunching primitives coded in C or C++ or Fortran). At least in Europe, several number crunching applications are driven by scripts. Of course, a huge fraction of the CPU time (ie >= 98%) is spend in numerical routines coded in Fortran or C. Only a tiny fraction of the work is spent in interpreting scripts. I don't know if the ASCI boxes are running numerical computations driven by Python (or Ruby) scripts, but obviously they could (and sometimes similar applications are designed around a scripting language). -- Basile STARYNKEVITCH http://starynkevitch.net/Basile/ email: basile<at>starynkevitch<dot>net aliases: basile<at>tunes<dot>org = bstarynk<at>nerim<dot>net 8, rue de la Fa?encerie, 92340 Bourg La Reine, France From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 17:03:04 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 22:03:04 +0100 Subject: Thoughts on PEP284 References: <mailman.1064341934.21653.python-list@python.org> <eppstein-CA53C5.12265623092003@news.service.uci.edu> <Gn1cb.2779$gi2.756@fed1read01> Message-ID: <so81nvsosmukkds1ne3fbbocjliu3tbjaa@4ax.com> On Tue, 23 Sep 2003 12:43:34 -0700, Tim Hochberg <tim.hochberg at ieee.org> wrote: >I know someone's going to suggest that, since I'm already using slices, >I should be in favor of int[a:b:c] or similar. But, that doesn't work >any better than range with reversed ranges since you still have to use >two slices to make things clear. That is, to get the equivalent of >``range(n-1,-1,-1)`` one would need to use ``int[n-1:-1:-1]``, which is >no clearer, or ``int[:n][::-1]`` which doesn't seem like a particular >win over ``range(n)[::-1]``, which you can do now. One option is, of course... for i in int[:n] : j = n - i - 1 ... or... for i in int[1:n+1] : j = n - i ... And I thought half-open ranges were supposed to eliminate all those +1 and -1 things! I mentioned before that I have recently coded an extension module with some containers, and had to deal with some slicing issues. One issue which I haven't resolved yet is whether to add some sliceable properties for alternate slicing methods (mainly slicing by subscript on associative containers that are by default sliced by key). Running with this idea, how about... for i in int.backward [:n] : ... where 'backward' means you get the same slice, but iterated in reverse order. Actually, I'd vote for a 'backward' sliceable property in strings, lists and tuples too (though the name should probably be changed). I might even make the property give a more general proxy for the object that behaves as if the items were reversed (though maybe not - the number of methods to handle for string in particular would be a nightmare). A reverse function (not the existing reverse methods which work in-place) would of course handle most cases perfectly well. Why can't we have a built-in library function doing something like... def reverse(x) : y = x [:] y.reverse () return y Trivial, yes - but probably very useful if you ask me. And I swear it used to exist, though perhaps only for strings (before some string stuff got converted to methods). Anyway, I really don't think this 'backward' property should be part of the standard int type - I'm rapidly getting more into the idea of taking Seans prototype from here... Message-ID: <lWYbb.4739$yD1.697869 at news20.bellglobal.com> removing the inheritance from int (which is probably redundant) and making it purely into a library object or recipe. It may be time for me to properly figure out metatypes ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From brian at sweetapp.com Tue Sep 16 14:24:31 2003 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 16 Sep 2003 11:24:31 -0700 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <tmH9b.79$2k.36@reader1.news.jippii.net> Message-ID: <007a01c37c7f$c5fc6850$21795418@dell1700> > There is no object-level locking in my proposal. Just independent > free-threaded interpreters, which don't see the objects of other > interpreters at all. OK, but this is useless to the average Python programmer. It is only useful to people embedding Python interpreters in multithreaded applications. I would imagine that this represents <1% of Python users. > There could be an extra global interpreter state for shared-memory > object access. Accessing this would always be synchronized, but only > this. Python would automatically copy data from this state to > thread-local state and back when needed. This would require a special > syntax for variables in global state: So now you want to change the language definition for the benefit of a small minority of users? Cheers, Brian From gh at ghaering.de Mon Sep 15 07:29:55 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 15 Sep 2003 13:29:55 +0200 Subject: pyc2py In-Reply-To: <39324.202.175.228.157.1063620644.squirrel@webmail.chargedideas.com> References: <pan.2003.09.15.07.01.32.964993@thomas-guettler.de> <3F656561.6070701@ghaering.de> <39324.202.175.228.157.1063620644.squirrel@webmail.chargedideas.com> Message-ID: <3F65A2B3.8080501@ghaering.de> Andres Montiel wrote: > Hmmm... does this mean that any Python compiled can be decompiled? What if > someone was selling compiled Python programs. decompyle seems to be able > to decompile them. It depends on your business model if this is a problem or not. Looks like, for most people, it's not. I believe that apart from Python, even in Windows-land, this is much less of a problem than people would think. > Is there a way to make sure that compiled python code cannot be decompiled? Ask groups.google.com. This has been discussed many times. -- Gerhard From john.abel at pa.press.net Fri Sep 12 05:19:28 2003 From: john.abel at pa.press.net (John Abel) Date: Fri, 12 Sep 2003 10:19:28 +0100 Subject: Can This Code Be Made Faster? Message-ID: <3F618FA0.2060203@pa.press.net> I have a problem, in that the following code is sometimes failing. I am stat'ing a list of files, but, sometimes, one of the files may be moved by an external process, after the os.path.exists and before the lstat, causing the script to fail. My question, is there anything I can do to speed it up, or put in a trap, to stop the stat from failing? fileTimes = [ ( os.lstat( os.path.join( rootPath, fileName ) )[stat.ST_MTIME], fileName) for fileName in fileList \ if os.path.exists( os.path.join( rootPath, fileName ) ) ] I'd appreciate any pointers. John From aahz at pythoncraft.com Wed Sep 24 01:52:21 2003 From: aahz at pythoncraft.com (Aahz) Date: 24 Sep 2003 01:52:21 -0400 Subject: General Password questions References: <mailman.1064266830.20157.python-list@python.org> <pan.2003.09.23.16.02.35.675695@riquito.matrix> <bkpsng$knm$1@panix1.panix.com> <pan.2003.09.23.21.09.35.146080@riquito.matrix> Message-ID: <bkrbel$b0q$1@panix2.panix.com> In article <pan.2003.09.23.21.09.35.146080 at riquito.matrix>, Riccardo Attilio Galli <riquito at riquito.matrix> wrote: > >curiosity: what is "zie" intended to mean? It is maybe slang for he/she ? It's a gender-neutral pronoun. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From jjl at pobox.com Thu Sep 11 13:32:46 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Sep 2003 18:32:46 +0100 Subject: Newbie-question: Fetching web-address from the browser! References: <bff50f69.0309110444.55294d83@posting.google.com> Message-ID: <87u17jfcxt.fsf@pobox.com> dermoon at hotmail.com (dermoon) writes: > I want to fetch the address from the web-browser when it > visits a page on my web-server. > > I use win2k on this server. > > On linux I used os.environ[''], but it seemes it's not available on > win2k, is this correct? [...] Depends which server you're using, I guess (certainly, os.environ is available in the usual standalone Python execution environment on Windows, but programs running in webservers will no doubt have all kinds of variations). Is this IIS or something? If you want to have the same environment as on Linux, remember Apache runs on Windows too (if that's what you were using). > However, how do I get the address-string? [...] Read your server's documentation. John From martin at v.loewis.de Mon Sep 22 01:47:19 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 22 Sep 2003 07:47:19 +0200 Subject: Trouble sorting lists (unicode/locale related?) References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> <bkk4h1$9ke$06$1@news.t-online.com> <mailman.1064154389.29357.python-list@python.org> <87y8wh50ca.fsf@pobox.com> <bkl3fe$fst$01$1@news.t-online.com> <871xu9bok3.fsf@pobox.com> Message-ID: <m3ad8x2x3s.fsf@mira.informatik.hu-berlin.de> jjl at pobox.com (John J. Lee) writes: > > >>If this did work, then you can use the DSU pattern like so: > > > [...strxfrm...] > > > The advantage of which is that you don't have to mess with the > > > locale. > > > > No, it doesn't. > > It does set the locale, you mean? Calling locale.strxfrm does not cause locale.setlocale to be called, i.e. it does not set the locale. Likewise, calling locale.strcoll does not cause setlocale to be called. Instead, the application needs to call setlocale *explicitly* for proper operation of either function. > So I guess there's no advantage there at all? Using strxfrm is an advantage if you have to collate the same string multiple times, e.g. when sorting a list of strings. It is an advantage because sorting will complete faster. Regards, Martin From spam at magnetic-ink.dk Tue Sep 30 01:39:40 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Tue, 30 Sep 2003 05:39:40 +0000 (UTC) Subject: PEP-0263 and default encoding References: <3f782aef-bdbbd6f1-a72a-4a6c-8b23-c4915b89a61f@news.szn.dk> <blaau5$b0r$1@news-reader3.wanadoo.fr> <vnhh7etad1t566@news.supernews.com> Message-ID: <3f79171c-d4c587aa-d4ac-44b9-97da-5e0024d4d268@news.szn.dk> John Roth wrote: > Remember that the actual Python program has to be in ASCII - > only the text in string literals can be in different character > sets. I'm not sure about comments. Python barfs if there are non-ASCII characters in comments and there is no coding-line. Still beats me why it doesn't use the sys.getdefaultencoding() instead of inconveniencing me. // Klaus -- ><> unselfish actions pay back better From duncan at NOSPAMrcp.co.uk Thu Sep 11 11:21:18 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 11 Sep 2003 15:21:18 +0000 (UTC) Subject: os.listdir References: <HKYJXJ$IJtpKVwktIN8kOKo8RPo0eClW9NoSa2aMVXNcWgZA4d1srKaVwlRm@bol.com.br> <mailman.1063171515.17609.python-list@python.org> <bjq102$m21$03$1@news.t-online.com> Message-ID: <Xns93F3A4DD43D3Cduncanrcpcouk@127.0.0.1> "Michael Peuser" <mpeuser at web.de> wrote in news:bjq102$m21$03$1 at news.t- online.com: > It is generally very difficult to > compute the mean access time to a hash. It totally depends on the size of > the internal hash table allocated as to the number of elements you store > there. In Perl there is trick to manipulate that (i.e. to increase it > appropriately when you expect e.g. some 100.000 entries). I don't know > whether this is possible in (C)Python, according to which algorithm the > initial size is computed, and when or if the table is reconfigured (which > would be a major undertaking btw). Any info someone? In C Python, all dictionaries have an initial size of 8 elements. There is no way to override this (except recompiling!) Maximum dictionary load is 2/3, i.e. when an insertion would result in more than 2/3 of the cells being filled[*], the dictionary is resized. Usually the resize involves doubling the size, but if a lot of dictionary slots have been deleted it can instead reduce the size (or leave it unchanged). This may be surprising: deleting elements from a Python dictionary never decreases the memory allocated to the dictionary, but inserting elements can. The first probe into a dictionary uses only the least significant bits of the hash value, but if there is a collision the other hash bits are gradually incorporated, so eventually all 32 bits of the hash value are used. This means that most collisions diverge quickly. [*] Terminology: Cells may be free, filled, or used. Initially all cells are free, inserting an element changes a cell from free or filled to used, deleting changes a cell from used to filled. Lookup probes cells until a free cell is seen. > > Apart from that, you will generally find the value to your key with the > first access if the table is decently dimensioned. -- 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 lists at webcrunchers.com Thu Sep 4 22:14:05 2003 From: lists at webcrunchers.com (John D.) Date: Thu, 4 Sep 2003 19:14:05 -0700 Subject: in Ram database? Message-ID: <v03110742bb7da1ba2767@[192.168.0.2]> Does anyone know if there is an "in-ram" dictionary based database for Python. I can see some applications where this can really be powerful in applications requiring 10,000 records or less. Is such a database available? If so, who is working on it, or where is it? I've heard that Python supports a stand-alone database. I looked for it in the Docs, and see the "dbm" module. I haven't found any examples of code, so don't know how to use them. I'm one of those guys that learn through examples, and have very little luck in figuring out how to use anything unless I can see examples of their use. My idea is that ALL datums would be Python Dictionary objects, so not only can you store data, but python objects as well. Storage to disk would be through pickled files, or through CSV format, allowing easy import and export from other databases. I'm sure something like this exists, I just haven't found it yet, and if not, then I'm well on my way of implementing one myself. I kinda like the idea of being able to define smaller tables as "in-memory" types, and the really large massive ones in other forms managed by mySQL, PostGres, or bsddb3 databases. Any leads you guys??? JD From newsgroups at jhrothjr.com Tue Sep 9 07:52:57 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 9 Sep 2003 07:52:57 -0400 Subject: Why the 'self' argument? References: <slrnblh5ru.nd5.gstaniak@inka.zagiel.pl> <vlh7otscuo8gb1@news.supernews.com> <3f58a2bd$0$156$a1866201@newsreader.visi.com> <vlhba85atlte07@news.supernews.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <vlhidvcpq9a980@news.supernews.com> <qpOW/ks/KnRV089yn@the-wire.com> <vlhtm1bmc7m295@news.supernews.com> <fc08a59c.0309060830.623d31c7@posting.google.com> <Ucp6b.3992$ZB4.3874@reader1.news.jippii.net> <3f5a2260$0$166$a1866201@newsreader.visi.com> <TRr6b.4056$ZB4.1410@reader1.news.jippii.net> <vlpeq9jko1l6b0@news.supernews.com> <7T47b.4753$ZB4.113@reader1.news.jippii.net> <vlpr14kfehrn46@news.supernews.com> <rKadnXfgmJJdosCiXTWJiQ@comcast.com> Message-ID: <vlrfohfp908qd7@news.supernews.com> "Terry Reedy" <tjreedy at udel.edu> wrote in message news:rKadnXfgmJJdosCiXTWJiQ at comcast.com... > > "John Roth" <newsgroups at jhrothjr.com> wrote in message > news:vlpr14kfehrn46 at news.supernews.com... > > It's not a simple thing to do, and the fact that ML > > family languages manage to do it without having > > to have explicit type declarations (well, most of the > > time anyway) is a major achievement, IMO. > > As I remember, part of the cost (for ML at least) is having separate > operators for ints and floats. As well as separate operators for a number of other things. This isn't unique to ML, though. For other reasons, Perl has a seperate set of operators for string versus numeric comparisons, and even Python has separate operators for division. > Bye bye generic functions. Actually, they seem to be able to have generic functions, at least in some restricted cases. > I don't > remember if there was any escape from the type straightjacket (like > #define max(a,b) ... in C). And one has to adjust to and feel > comfortable enough with the view that multiparam functions are a > composition of single param functions. I'm not sure how central currying is to the type inference mechanism. > But I agree that the type > inferencing is an interesting achievement. Yes, it is. That is, I think, my point. If we want to have some form of static typing and still keep Python reasonably close to the streamlined language we all know and love, this seems like an interesting research direction. John Roth > > Terry J. Reedy > > From zsh-announce-help at sunsite.dk Thu Sep 4 18:32:34 2003 From: zsh-announce-help at sunsite.dk (zsh-announce-help at sunsite.dk) Date: 4 Sep 2003 22:32:34 -0000 Subject: ezmlm response Message-ID: <1062714754.18498.ezmlm@sunsite.dk> Hi! This is the ezmlm program. I'm managing the zsh-announce at sunsite.dk mailing list. Acknowledgment: The address python-list at python.org was not on the zsh-announce mailing list when I received your request and is not a subscriber of this list. If you unsubscribe, but continue to receive mail, you're subscribed under a different address than you currently use. Please look at the header for: 'Return-Path: <zsh-announce-return-1234-user=host.dom at sunsite.dk>' The unsubscribe address for this user would be: 'zsh-announce-unsubscribe-user=host.dom at sunsite.dk'. Just mail to that address, substituting user=host.dom for the real values, reply to the confirmation request, and you should receive a message that you're off the list. For some mail programs, you need to make the headers visible to see the return path: For Eudora 4.0, click on the "Blah blah ..." button. For PMMail, click on "Window->Show entire message/header". If this still doesn't work, I'm sorry to say that I can't help you. Please FORWARD a list message together with a note about what you're trying to achieve and a list of addresses that you might be subscribed under to my owner: zsh-announce-owner at sunsite.dk who will take care of it. My owner is a little bit slower than I am, so please be patient. --- Administrative commands for the zsh-announce list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: <zsh-announce-subscribe at sunsite.dk> To remove your address from the list, send a message to: <zsh-announce-unsubscribe at sunsite.dk> Send mail to the following for info and FAQ for this list: <zsh-announce-info at sunsite.dk> <zsh-announce-faq at sunsite.dk> Similar addresses exist for the digest list: <zsh-announce-digest-subscribe at sunsite.dk> <zsh-announce-digest-unsubscribe at sunsite.dk> To get messages 123 through 145 (a maximum of 100 per request), mail: <zsh-announce-get.123_145 at sunsite.dk> To get an index with subject and author for messages 123-456 , mail: <zsh-announce-index.123_456 at sunsite.dk> They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: <zsh-announce-thread.12345 at sunsite.dk> The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: <zsh-announce-subscribe-john=host.domain at sunsite.dk> To stop subscription for this address, mail: <zsh-announce-unsubscribe-john=host.domain at sunsite.dk> In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at zsh-announce-owner at sunsite.dk. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: <sandip at puroga.com> Received: (qmail 18492 invoked from network); 4 Sep 2003 22:32:34 -0000 Received: from localhost (HELO sunsite.dk) (127.0.0.1) by localhost with SMTP; 4 Sep 2003 22:32:34 -0000 X-MessageWall-Score: 0 (sunsite.dk) Received: from [66.98.128.18] by sunsite.dk (MessageWall 1.0.8) with SMTP; 4 Sep 2003 22:32:33 -0000 Received: from [210.7.86.22] (helo=pluto.puroga.com) by master.puroga.com with asmtp (TLSv1:DES-CBC3-SHA:168) (Exim 4.20) id 19v2eV-0005tt-Ag for zsh-announce-uc.1062623247.cbehnoegidjnndepmmcn-python-list=python.org at sunsite.dk; Fri, 05 Sep 2003 04:02:32 +0530 Received: from neptune.home ([192.168.254.1] helo=neptune.puroga.com) by pluto.puroga.com with esmtp (Exim 4.20) id 19v1cJ-0000fG-FU for zsh-announce-uc.1062623247.cbehnoegidjnndepmmcn-python-list=python.org at sunsite.dk; Fri, 05 Sep 2003 02:56:11 +0530 Message-Id: <5.2.1.1.2.20030905040143.0109ec00 at master.puroga.com> X-Sender: sandip at puroga.com@master.puroga.com X-Mailer: QUALCOMM Windows Eudora Version 5.2.1 Date: Fri, 05 Sep 2003 04:01:51 +0530 To: zsh-announce-uc.1062623247.cbehnoegidjnndepmmcn-python-list=python.org at sunsite.dk From: Sandip Bhattacharya <sandip at puroga.com> Subject: Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii"; format=flowed X-AntiAbuse: This header was added to track abuse, please include it with any abuse report X-AntiAbuse: Primary Hostname - master.puroga.com X-AntiAbuse: Original Domain - sunsite.dk X-AntiAbuse: Originator/Caller UID/GID - [47 12] / [47 12] X-AntiAbuse: Sender Address Domain - puroga.com --- ------------------------------------------------------------------------ Sandip Bhattacharya Puroga Technologies Pvt. Ltd. sandip <@> puroga.com http://www.puroga.com ------------------------------------------------------------------------ From tjreedy at udel.edu Thu Sep 11 20:46:06 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Sep 2003 20:46:06 -0400 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <bjnh03$7d3$1@fred.mathworks.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> <mv_7b.215$o71.11@news2.central.cox.net> <66t0mv410it5ftvjokfpkov0v029trv6lp@4ax.com> <A8Ccna05HMkwQ_2iXTWJiQ@comcast.com> <uo02mv0dugi9ijk0k3llar0g3nmtnm59m6@4ax.com> Message-ID: <CACdnZh3QbnSivyiXTWJiA@comcast.com> "Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:uo02mv0dugi9ijk0k3llar0g3nmtnm59m6 at 4ax.com... > On Thu, 11 Sep 2003 16:44:28 -0400, "Terry Reedy" <tjreedy at udel.edu> > wrote: > > >realize that 'ref x' would have to have much the same effect of Lisp's > >FEXPR defun keyword -- of automatically quoting rather than evaluating > >args -- although on just one rather than all. Perhaps you should be > >accused of 'trying to Lispify Python' -- or perhaps not ;-). > > I didn't know Lisp could do that. Based on my reading of Winston&Horn's LISP (1st ed, 1981, MacLisp based), auto quoting is the key to how Lisp conveniently turns statements into syntactic functions. Example: Python statement: a=b # a is *not* evaluated but used literally Python function: set('a',b) # requires explicit quote to not eval a where, for instance, def set(nam,val): globals()[nam]=val Lisp s-expression 1: (set 'a b) # call is like Python function Lisp s-expression 2: (setq a b) # where setq is an FEXPR-type function that evaluates b but uses a literally, like Python statement Autoquoting is also used for macro manipulation of code. >I have to read up on Common Lisp one of these days. LISP, 3rd ed, 1989, still in print, uses standard Common Lisp. Chapter 12 Macros and Backquote might be of interest to you. Terry J. Reedy From tim at remove_if_not_spam.digitig.co.uk Tue Sep 23 10:40:33 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Tue, 23 Sep 2003 15:40:33 +0100 Subject: Thoughts on PEP315 References: <oalumvopu9afuhno85tbp2erl52rk9hht1@4ax.com> <m2isnkduqt.fsf@mycroft.actrix.gen.nz> Message-ID: <dul0nv0v3tqhp05kd5pbalsf677ku12obg@4ax.com> On Tue, 23 Sep 2003 15:55:06 +1200, Paul Foley <see at below.invalid> wrote: >On Tue, 23 Sep 2003 01:47:03 +0100, Stephen Horne wrote: > >> In terms of flexible loops, Ada is basically the Daddy. > >http://www.lispworks.com/reference/HyperSpec/Body/m_loop.htm Young upstart compared to ALGOL! From alanmk at hotmail.com Fri Sep 12 06:33:43 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 12 Sep 2003 11:33:43 +0100 Subject: Trouble with source-code encoding References: <9u63mvoij7b8h2fh6tmj2e9af1akqjl3de@4ax.com> Message-ID: <3F61A107.835F0F77@hotmail.com> Fernando Rodriguez wrote: > However, the pep doesn't list the name of valid encodings. What's > the name for west european encoding? Unfortunately, there is no way, from code, to get a list of valid encodings. You can get a good idea of supported encodings, their names and various aliases, by looking at the source of Lib/encodings/aliases.py which gives the following list of possible names for the "latin_1" codec '8859' 'cp819' 'csisolatin1' 'ibm819' 'iso8859' 'iso_8859_1' 'iso_8859_1_1987' 'iso_ir_100' 'l1' 'latin' 'latin1' Any of those should work as your script encoding. -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From vincent at visualtrans.de Tue Sep 16 13:47:09 2003 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 16 Sep 2003 19:47:09 +0200 Subject: Tkinter.Text can never be empty? References: <70df36e9.0309160826.596dd5ab@posting.google.com> Message-ID: <bk7h90$geg$1@news1.tilbu1.nb.home.nl> "Harry Pehkonen" <harry.pehkonen at hotpop.com> schrieb im Newsbeitrag news:70df36e9.0309160826.596dd5ab at posting.google.com... | While setting up some unit tests, I came to the conclusion that a | Tkinter Text widget can never be empty, but will always (?) contain a | \n. Here is a brief example: | | >>> import Tkinter | >>> t = Tkinter.Text() | >>> t.get(0.0, Tkinter.END) | '\n' | >>> t.delete(0.0, Tkinter.END) | >>> t.get(0.0, Tkinter.END) | '\n' | >>> | | My apologies, but I have not checked whether or not this can be | reproduced in Tcl/Tk (which I think might have been appropriate). | | My question is: Is there *always* a trailing \n, is this a bug, or am | I doing something silly? Nope, this is one of the idiosyncrasies of our friend the Text widget; there's always this immortal LF at the end. Vincent Wehren | | Thanks! | Harry. From mxlplx2003 at yahoo.com Tue Sep 2 11:40:45 2003 From: mxlplx2003 at yahoo.com (mxlplx) Date: 2 Sep 2003 08:40:45 -0700 Subject: Zope from Interwoven References: <3cf2990f.0308280620.3dec0c39@posting.google.com> <pan.2003.08.28.16.01.29.135591@exultants.org> Message-ID: <3cf2990f.0309020740.45b34489@posting.google.com> Thanks for the info. I knew this was going to be ugly! Van Gale <news at exultants.org> wrote in message news:<pan.2003.08.28.16.01.29.135591 at exultants.org>... > On Thu, 28 Aug 2003 07:20:47 -0700, mxlplx wrote: > > > I'm currently working on a project to convert an Interwoven-based site > > to use Zope instead. Has anyone attempted this before and if so, were > > you able to do it with Zope? Could you use the XML files produced by > > Interwoven? Any ideas would be appreciated. > > I can't think of a single thing the 2 systems have in common really, so it > won't be an easy task. > > The conversion to Zope should mostly be possible, and is probably worth it > considering the cost of the conversion will probably be less than > licensing costs... but you'll have to develop custom tools to convert any > data that can be converted and the rest will have to be developed from > scratch. > > Some bits, such as workflow XML/perl templates probably cannot be > converted at all and you'll need to redesign workflows in the Zope way. > > If your pages are ASP or PHP you'll have to convert them to Zope's DTML or > TAL. > > If you use metadata you'll need to design objects with attributes to > match. > > The XML from Teamsite templates would also be replaced by python objects, > which means processing the teamsite XML to create a new object, merging > the metadata, and then getting that object into Zope's object storage. > > You might get a better answer on the Zope mailing list, but I bet it'll be > the same general "Ugh!" :) > > Van From myles at geocities.com Mon Sep 22 21:18:52 2003 From: myles at geocities.com (Myles) Date: 22 Sep 2003 18:18:52 -0700 Subject: Proxy Authentication using urllib2 References: <mailman.1064015428.25301.python-list@python.org> Message-ID: <a4638b9b.0309221718.1774d393@posting.google.com> Andre Bocchini <lists at andrebocchini.com> wrote in message news:<mailman.1064015428.25301.python-list at python.org>... > I'm having some trouble using proxy authentication. I can't figure out > how to authenticate with a Squid proxy. I know for a fact the proxy is A piece of code that works through a Squid proxy here - originally clipped from comp.lang.python - possibly an eff-bot post if my dim memory serves me correctly. ---- snip ---- import urllib2 proxy_info = { 'user' : 'username', 'pass' : 'password', 'host' : "proxy.name.com", 'port' : 80 # or 8080 or whatever } # build a new opener that uses a proxy requiring authorization proxy_support = urllib2.ProxyHandler({"http" : \ "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) # install it urllib2.install_opener(opener) # use it f = urllib2.urlopen('http://www.python.org/') print f.headers print f.read() ---- snip ---- Regards, Myles. From wilkSPAM at OUTflibuste.net Wed Sep 17 16:23:23 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Wed, 17 Sep 2003 22:23:23 +0200 Subject: Simple python cgi question References: <MHGdnfoYyrH0-fWiXTWc-g@speakeasy.net> <87llsnmrw4.fsf@flibuste.net> <wG6dneAarP2YP_WiXTWc-g@speakeasy.net> Message-ID: <87znh3411g.fsf@flibuste.net> Stephen Boulet <stephen at SPAM.theboulets.IS.BAD.net> writes: > Wilk wrote: >> Stephen Boulet <stephen at SPAM.theboulets.IS.BAD.net> writes: >> >>>First of all, I'm not sure that the easiest way to do this is with >>>python ... >>> >>>I'd like to set up a web page that would accept a text file, process >>>it with a local program, and then make available generated pdf and >>>postscript files for downloading. >>> >>>I'd like to limit the size of the file to be uploaded. >>> >>>I have apache2 already up. Is this a job for (mod_)python? >> Yes why not ? > > I was hoping for a bit more detail ... > If you will do it in cgi, look at the cgi module, and for the pdf look at http://www.reportlab.com After, try to be more precise in your question if you want more details... bye -- William Dode - http://flibuste.net From CousinStanley at hotmail.com Wed Sep 24 21:22:09 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 24 Sep 2003 18:22:09 -0700 Subject: RELEASED Python 2.3.1 References: <mailman.1064390741.20344.python-list@python.org> <bksi8l$5bce8$1@ID-130333.news.uni-berlin.de> <878yoe2jsc.fsf@pobox.com> Message-ID: <bktfn0$5ood1$1@ID-130333.news.uni-berlin.de> | You can download the HTML docs separately, | or decompile the .chm back to HTML. | See recent threads about this. John .... Thanks for the reply .... It's nice to know there are options .... -- Cousin Stanley Human Being Phoenix, Arizona From user at invalid.domain Thu Sep 25 09:31:08 2003 From: user at invalid.domain (Invalid User) Date: Thu, 25 Sep 2003 15:31:08 +0200 Subject: "for" with "else"? Message-ID: <bkuqmu$ajv$1@ctb-nnrp2.saix.net> While trying to print a none empty list, I accidentaly put an "else" statement with a "for" instead of "if". Here is what I had: if ( len(mylist)> 0) : for x,y in mylist: print x,y else: print "Empty list" which was supposed to be: if ( len(mylist)> 0) : for x,y in mylist: print x,y else: print "Empty list" Is this to be expected? (python 2.2.2) ++++++++++++++++++++++++++++++= >>> for x in range(5): ... print x*x ... else: ... print "done" ... 0 1 4 9 16 done ++++++++++++++++++++++++++++++= From mark at hahnca.com Sat Sep 27 14:24:35 2003 From: mark at hahnca.com (Mark Hahn) Date: Sat, 27 Sep 2003 11:24:35 -0700 Subject: [ANN] pylint-0.2 References: <mailman.1064594507.31702.python-list@python.org> Message-ID: <EBkdb.3354$hp5.1305@fed1read04> > Pylint is a lint-like tool for Python code Does pylint only work for modules? When I tried to run it on my code file (ezpicmailer.py) , it raised an exception: No config file found, using default configuration <snip> Exception: Unable to find module for C:\photoedit\ezpicmailer in <snip> and then it gave a long list of modules in my sys.path. It seems to insist that the argument I give it be a module in sys.path, not just an arbitrary python code file. ------------------------------------------ "Alexandre Fayolle" <Alexandre.Fayolle at logilab.fr> wrote in message news:mailman.1064594507.31702.python-list at python.org... Logilab has released pylint-0.2 What's new? ----------- In addition to a large number of bug fixes, this release adds two new checkers, for missing encoding declaration, and for FIXME comments. Zope support was improved. About Pylint ------------ Pylint is a lint-like tool for Python code. It performs almost all the verifications that pychecker does, and additionally can perform some stylistic verification and coding standard enforcements. The checked code is assigned a mark based on the number and the severity of the encountered problems. The previous mark of a given piece of code is cached so that you can see if the code quality has improved since the last check. URLs ---- Homepage: http://www.logilab.org/projects/pylint Download: ftp://ftp.logilab.org/pub/pylint/pylint-0.2.tar.gz -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From peter at engcorp.com Wed Sep 17 12:41:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Sep 2003 12:41:40 -0400 Subject: replace %(word) in a string References: <mailman.1063788123.2509.python-list@python.org> <slrnbmgi1d.e5h.mirko-lists@zeibig.net> <Xns93F9BB479FE03PaCmAnRDLM@213.228.0.75> Message-ID: <3F688EC4.F39D551B@engcorp.com> Fred Pacquier wrote: > > Mirko Zeibig <mirko-lists at zeibig.net> said : > > > Especially useful together with the locals() function, which returns a > > dictionary of locally defined variables: > > > > def foo(): > > a = "Hello" > > b = "World" > > print "%(a)s %(b)s" % locals() > > Yes, that's a wonderful feature. Recently though, I've wondered a couple of > times : is there an easy way to substitute with both local AND global > variables ?... tempDict = locals() tempDict.update(globals()) then just use tempDict for the dictionary... You can also do it the other way around, of course, and you must decide which you really want since the last-added dictionary will of course mask any keys which are also in the first-added dictionary. -Peter From adfgvx at free.fr Sat Sep 20 06:33:04 2003 From: adfgvx at free.fr (adfgvx) Date: Sat, 20 Sep 2003 12:33:04 +0200 Subject: Sick (yaml library) and Python Message-ID: <3f6c2cdf$0$2770$626a54ce@news.free.fr> I am looking for a Compiled version of the Sick extension for Python (Windows XP and Python 2.2). Does anyone have one and send it to me ? Thanking you by advance, Bruno From tebeka at cs.bgu.ac.il Wed Sep 17 07:10:37 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 17 Sep 2003 04:10:37 -0700 Subject: Can Python Module Locate Itself? References: <VYR9b.1109$c17.866@newssvr24.news.prodigy.com> Message-ID: <33803989.0309170310.56c749d6@posting.google.com> Hello sj, > I have written several small shell utilities in Python and typically use > comments at the start of the source file as documentation. A command line > option allows the user to read this documentation. The problem is that I > have to explicitly code the source files location within the source which > is not very portable. Is there anyway for a python module to locate its > own source ? sys.argv[0] is always the name of the script. Have you looked at the new optparse module? (http://www.python.org/doc/current/lib/module-optparse.html) HTH. Miki From ajsiegel at optonline.net Mon Sep 8 18:40:56 2003 From: ajsiegel at optonline.net (Arthur) Date: Mon, 08 Sep 2003 18:40:56 -0400 Subject: Comments on Python Redesign Message-ID: <000901c3765a$45d7f160$0c02a8c0@Arts> >I do not believe that Economics is the relevant field to consult as to the >purpose of the python.org website. OT, to be sure: but, as it happens a favorite of mine website pays homage to the Economist. http://www.foulds2000.freeserve.co.uk/economists.htm Less OT, is my confusion about an approach promoting Python which does not adequately distinguish itself from the approach that may be appropriate to promoting, say, peoplesoft. An analogy that has been made. I had the same confusion at the PBF meeting at PyCon. There it was Java based technologies, for example, that was discussed as a competitor. But in my view, *especially* from the managers point of view, the implementation language of a particular technology is not particularly of interest and the people promoting a specific technology generally assume that is so. It will mostly be of interest, only in the negative. If it's Java or C++, let's move on. If its Python or Ocaml - perhaps it needs to be discussed. And I understand the "promoting Python" campaign as an organized effort to assist some in getting past that discussion. The issue boils down to a chicken and egg thing. As the critical mass number of programmers using Python grows, the discussion begins to go away of its own accord. So that "promoting python" should, in that case, remain directed toward the hard core developer community. OTOH, it could be argued that that critical mass of Python programmers will not be achieved before there is support from managment. So that is where promotion should be directed. But it is my guess that efforts of a programming language community to promote its favorite language that is transparently the efforts of a programming language community to promote its favorite programming language can have - let's say - unintended consequences. Especially, if it moves too far from the aesthetic that got it to where it has gotten. So I would advise a gradualist approach. Not a shocking break from the past approach of python.org. Which is blandly, but cheerfully, informational - in a generalist way. Having gotten the ball rolling to the extent it has, it is an approach with a track record. I like track records. Art From mertz at gnosis.cx Mon Sep 8 17:31:52 2003 From: mertz at gnosis.cx (David Mertz) Date: Mon, 08 Sep 2003 17:31:52 -0400 Subject: Eureka! References: <mailman.1062962051.23295.python-list@python.org> <bjibik$g3n$1@panix3.panix.com> <3F5CD10B.2020709@teksavvy.com> <200309072018.05589.dave@pythonapocrypha.com> <mailman.1063053974.13083.python-list@python.org> <3F5CF116.2F755AA6@engcorp.com> <8LPX/kKkX89D092yn@gnosis.cx> Message-ID: <IVPX/kKkXEUO092yn@gnosis.cx> Peter Hansen <peter at engcorp.com> wrote previously: |* You can't tell ahead of time what site you are going to be redirected to. | As a result, you lose complete freedom to choose whether or not you should | follow the link. As Dave Brueck noted, the same is true of ANY URL. I use a few redirects on my own website, so just because you think you are going to a gnosis.cx address doesn't mean you'll wind up there. In an innocuous case, the URL <http://gnosis.cx/TpiP/> redirects you to my actual book page (which differs in capitalization)--this just addresses a typo AW made on my jacket. Even so, the page you wind up seeing has a different URL that what you copy to your browser. A slightly greater change is with <http://gnosis.cx/voting-project/>, which directs you to an entirely different host (for now, I might more it to the same host later). While there's no malice here, readers had no idea they would wind up on gnosis.python-hosting.com. If I wanted to be REALLY malicious, I could post a link like: http://gnosis.cx/python/ :-). Yours, David... -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From dgallion at yahoo.com Sun Sep 7 15:35:51 2003 From: dgallion at yahoo.com (darrell) Date: Sun, 07 Sep 2003 19:35:51 GMT Subject: Automated code generation In-Reply-To: <3f58ba15$0$97267$edfadb0f@dread12.news.tele.dk> References: <3f58ba15$0$97267$edfadb0f@dread12.news.tele.dk> Message-ID: <rML6b.10256$3t2.812@twister.nyroc.rr.com> I write tools for testing embedded systems. They parse the .h files and doc files to associate names with hex values... This produces meg's of .py files which then support writing tools and test scripts. Everything from structure layout to: EMERGENCY_STOP_CMD=0x1234567L ... SOME_STRUCT=(["f1","f2","f3"],">fI10s") ... ERROR_100="Somethig bad" Does this qualify as code generation? When the project wants to change something like how we "log". Python is used to parse the entire source tree making changes. Not Python code generation but it's more complicated than search/replace. And could be applied to a Python code base as well Is this code generation? --Darrell Max M wrote: > Yesterday there was an article on Slashdot: > http://books.slashdot.org/article.pl?sid=03/09/04/1415210&mode=flat&tid=108&tid=126&tid=156 > > > It is about automatic code generation. > > I got interrested in the subject, did a web search, and it seems kind of > powerfull. > > My main interrest is web development in Zope/CMF/Plone, where there is a > lot of repeated code in the products. So automated code generation seems > like a natural fit. > > But every time I think of a use case, I immediately think of a way to do > it with encapsulation instead. > > Does anybody have any experience using Python and automated code > generation where it actually make sense? > > Or os it useless in a language as dynamic as Python? > > > regards max M > From max at alcyone.com Sun Sep 14 17:06:28 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 14 Sep 2003 14:06:28 -0700 Subject: checking type of my own objects References: <db65c3606f4aa39dd8459eb92fa5f5e4@news.teranews.com> Message-ID: <3F64D854.E1EF5B27@alcyone.com> Tobiah wrote: > What is the best way to check the type? e.__class__ is Event or if you want to include subclasses: isinstance(e, Event) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ If the sun comes up / And you're not home / I'll be strong \__/ India Arie From jordan at krushen.com Tue Sep 23 01:35:57 2003 From: jordan at krushen.com (Jordan Krushen) Date: Tue, 23 Sep 2003 05:35:57 GMT Subject: Thoughts on PEP315 References: <oalumvopu9afuhno85tbp2erl52rk9hht1@4ax.com> <vmv9hsp53qfi18@news.supernews.com> <r2Qbb.195$eB.185@twister.southeast.rr.com> <18kvmvobs9jsq50o91m35cveu49heev7mh@4ax.com> Message-ID: <oprvxtxmiq5ctagx@shawnews> On Tue, 23 Sep 2003 06:08:06 +0100, Stephen Horne wrote: > for ever : > <statements> > break if <condition> : You could always hide something similar in a generator: def forever(): while True: yield True for now in forever(): print 'looping forever...' ...although I must admit, I don't really mind "while True:" that much. syntactic-sugar-is-bittersweet-ly y'rs, J. From max at alcyone.com Tue Sep 23 15:54:51 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 23 Sep 2003 12:54:51 -0700 Subject: Factory function to generate a named class References: <3f702b3a$0$23594$5a62ac22@freenews.iinet.net.au> <mailman.1064318131.14654.python-list@python.org> Message-ID: <3F70A50B.F22539AA@alcyone.com> Jeff Epler wrote: > Populate a dict with a mapping from class names to class objects: He already has such a dictionary. It's globals(). :-) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Golf is a good walk spoiled. \__/ Mark Twain From jepler at unpythonic.net Sat Sep 20 17:56:57 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 20 Sep 2003 16:56:57 -0500 Subject: 2nd iteration of a character In-Reply-To: <bkigte$1e3b$1@biggoron.nerim.net> References: <bkigte$1e3b$1@biggoron.nerim.net> Message-ID: <20030920215657.GB10939@unpythonic.net> You probably want to write this in terms of find with a start argument specified. This minimally-tested function seems to do the job. def findn(haystack, needle, n, start=0): while 1: idx = haystack.find(needle, start) if idx == -1 or n==1: break n -= 1 start = idx+1 return idx >>> findn("axbxcx", "x", 2) 3 >>> findn("axbxcx", "z", 2) -1 Jeff From prochak at netzero.net Thu Sep 11 02:37:47 2003 From: prochak at netzero.net (Erik Lechak) Date: 10 Sep 2003 23:37:47 -0700 Subject: a quick program to download tv listings Message-ID: <1f0bdf30.0309102237.d29f0de@posting.google.com> Hello all, Is there anyone out there that has written anything in python to download tv listings (no XML)? All the tv listing stuff that I can find is way too complex for my taste (includes XML overkill or is not in python). I wrote the test program below and it works. I am just curious if anyone has a more robust python implementation before I take the time to add all the bells and whistles. Chron is just a class like datetime, but I wrote it to accept just about every english way of expressing time. The important thing is to put the epoch time in the URL. If anyone is interested in Chron, I can post it or send it to them. Hope you enjoy the code, Erik Lechak import urllib import re from pygra.Chron import Chron class Show: ''' Just a structure to hold program information ''' def __init__(self): name="" channel="" station="" start="" end="" def getGrid(timestring): shows=[] t=Chron(timestring) f = urllib.urlopen('http://tv.yahoo.com/grid?lineup=us_DMA560&genres=&dur=&starttime='+str(int(t.epoch))+'&.intl=us') data = f.read() data=[d.strip('\n') for d in data] data="".join(data) data=data.split("</A>") for d in data: progs = re.findall('<A HRef="\/tvpdb\?d=tvp&id=(.*)',d) for s in progs: m= re.search('(\d*)&cf.*channels=us_([^&]*).*&chname=([^\+]*)\+(\d+)&progutn=(\d*)&.*>(.*)',s) show=Show() show.name=m.group(6) show.start=m.group(5) show.channel=int(m.group(4)) show.station=m.group(3) shows.append(show) return shows shows =getGrid('now') for s in [s for s in shows if s.channel==17]: print s.name From jjl at pobox.com Wed Sep 3 08:47:57 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Sep 2003 13:47:57 +0100 Subject: pyQT pushButton References: <bj4cn1$ibu$1@reader10.wxs.nl> Message-ID: <8765kaox6q.fsf@pobox.com> Tom Van den Brandt <guineapig at pi.be> writes: > Is there anyone using pyQt who can tell me if I can set/change the internal > id of a pushbutton myself ? I can't find anything in the docs... What internal id? I don't remember one. What problem are you trying to solve? John From sdementen at hotmail.com Thu Sep 4 05:07:36 2003 From: sdementen at hotmail.com (Sebastien de Menten) Date: 4 Sep 2003 02:07:36 -0700 Subject: python plugin for excel (ala gnumeric) Message-ID: <8dad5312.0309040107.7f1b6aff@posting.google.com> Hi, I've read lot of messages on googlegroups without finding what I'm looking for :-( I need a plugin that enables me to access a python VM directly from excel (the COM server path is not satisfactory as it uses the registry). Grosso modo, if I have the equivalent of the python module/plugin of gnumeric (http://grub.ath.cx/gnumeric-python/ or http://www.csse.monash.edu.au/~ctwardy/starting-with-python.html) it would be great ! tx for any hint Sebastien From peter at engcorp.com Mon Sep 22 19:32:50 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Sep 2003 19:32:50 -0400 Subject: General Password questions References: <mailman.1064266830.20157.python-list@python.org> Message-ID: <3F6F86A2.DC29472A@engcorp.com> Todd Johnson wrote: > > I am creating a dialog in wxPython for log in > purposes. Basically when the user clicks the ok > button, the dialog box saves the user name and > password as class attributes. Then as long as the > dialog exists calling MyDialog.GetUserName() and > MyDialog.GetPassword() returns them. This seems > insecure to me. Why do you feel it's insecure? > On a similar note, I want to save the password to a > file. How do I encrypt the password? You don't encrypt passwords, you hash them. That means use a cryptographically strong hashing algorithm such as SHA or MD5 and store the resulting value. Later, when a user has entered a password which you want to check against the correct one, you run the same hash algorithm on the password-under-test and compare the result with the stored result. The hash algorithm is designed so that it's computationally infeasible to reverse-engineer a password that corresponds to a given hash value, making it about as good as storing the real thing without the insecurity in that approach. Luckily, these algorithms are already implemented for you so you don't need to deal with the complexities. Note, however, the likelihood that somebody interested in cracking this whole system could easily do things like change the Python source, or modify the password file that contains the hash value, substituting their own pre-calculated hash which matches the password they wish to enter. Assuming you are just trying to prevent casual intrusion and there's really nothing valuable involved, a simple hash using the sha or md5 module would probably do fine. Of course, at this point I fully expect a dozen people with more background in security to start stomping all over this advice and tell you how wrong it is, but I live to provide people with that kind of opportunity. ;-) I encourage you to learn more about this, too, by searching the web or something. Time spent studying security issues will always repay itself, no matter your current level of expertise... -Peter From mmmmn77NOSPAM at NOSPAMhotmail.com Wed Sep 10 01:47:15 2003 From: mmmmn77NOSPAM at NOSPAMhotmail.com (M) Date: Wed, 10 Sep 2003 07:47:15 +0200 Subject: Interested in learning Python with me? Message-ID: <bjmdvq$64d$1@news.cybercity.dk> Hi, i'm trying to gather a small group of people who wants to learn Python from the beginning with me. First a few lines about myself (very few!:)): I have practically no experience with any kind of programming (tried some, but always got stuck in the beginning with various languages) - but now I feel its the time to finally learn a programming language. Having read a bit in various programming-groups on usenet, i've come to the conclusion that Python is the most suitable (easy to use, platform-independant, easy syntax, free, and very powerful - or so i've read anyway :-)). My goal is to be able to make small utilities for myself mainly, in a MS Windows environment (and MAYBE later Linux), and if I really get the hang of programming - I imagine taking a closer look on some of the different "web"-languages (php, asp, xml etc. etc.) or even another "real" language like Java. My plan is that we (maybe 2-10 people) follow a few of the same books/tutorials, not neccesarily at the same speed, and then on a daily (or so) basis exchange experiences and ask things one might have had trouble understanding etc. A combination of a forum and icq/msn/etc. might be a good idea to keep in contact during the learning-process, but I'm of course open for other suggestions. I've been skimming through various tutorials and books about Python, and the free book named "How to Think Like a Computer Scientist:Learning with Python" - http://www.ibiblio.org/obp/thinkCSpy/ I find to be a good book for beginners - not TOO big, and yet it contain some nice explanations. So unless any better suggestions, I think we should be following that book for a start. It's not my plan to make a very strict reading-plan we all HAVE to follow - I see it more as an attempt to create an open forum for total beginners where we help eachother out with problems we get from the tutorials/books we read. And hopefully it will end up with small projects we help eachother with or even work together on! :) If you are interested, drop me an email on mmmmn77NOSPAM at NOSPAMhotmail.com (remove 'nospam') and tell me in a couple of lines of yourself, and your experience or lack of, with programming. Or feel free to ask any questions in here or come with suggestions, or even critique of my "plan" :-). M From Vincent.Raaijmakers at ge.com Mon Sep 15 09:17:05 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Mon, 15 Sep 2003 08:17:05 -0500 Subject: I need to make Excel/Powerpoint-style charts... oops Message-ID: <971323274247EB44B9A01D0A3B424C85E46EB2@FTWMLVEM02.e2k.ad.ge.com> Sorry, just see that you already looked at reportlab. Sorry, it is Monday morning here... Vincent -----Original Message----- From: python at sarcastic-horse.com [mailto:python at sarcastic-horse.com] Sent: Tuesday, September 09, 2003 11:19 AM To: python-list at python.org Subject: I need to make Excel/Powerpoint-style charts. Hi- My office produces a lot of charts based on time-series data. We use MS powerpoint and excel to make these charts. The data gets updated regularly, but there doesn't seem to be an easy way to automate updating the charts using these packages. So, we spend a non-trivial amount of time manually updating lots of spreadsheets to redraw the charts we need. I hope to find some sort of python graphics library that can make charts similar to Excel and Powerpoint, and then I can start automating these tasks. Here is an example of the charts we make: http://www.sarcastic-horse.com/example.pdf #52k size file. Are there any packages that can do similar charts? I need to be able to chart time-series data with occasional missing observations. I also need to be able to shade some regions of the charts, and add text titles, captions and notes. I'm (slowly) learning the reportlab package, and it looks good, but I wanted to check if there was an even better solution out there. Thanks for the help. -- http://mail.python.org/mailman/listinfo/python-list From google at evpopov.com Tue Sep 9 12:35:00 2003 From: google at evpopov.com (popov) Date: 9 Sep 2003 09:35:00 -0700 Subject: Pb when connecting to unopened ports and using socket timeout Message-ID: <7eecf173.0309090835.38610d3b@posting.google.com> Hello, When using the timeout option with a socket object (python 2.3), I don't have the same behaviour under Windows than under Linux / Mac. Specifically, if trying to connect to an unopened port of the localhost, I get a timeout exception on Windows (tested under W2K Server), whereas I get a "111 - Connection Refused" exception on Linux and "22 - Invalid Argument" on Mac (OS X). Even if the error message under Mac is not really appropriate, I think that the behaviour under Linux and Mac is the right one, in that it sends (quickly) an error message and not timeouting. Note that when using blocking socket the behaviour is ok under all platforms: they each return back quickly a "Connection refused" error message (err codes are different depending on the platform (61=Mac, 111=Linux, 10061=Windows)). What do you think ? I heard that the timeout option was implemented based on Timothy O'Malley timeoutsocket.py. Then, maybe the pb can come from the usage of select in the connection function: select is not asked to get back exceptions in the returned triple, whereas I think some errors can be returned back through this mean under Windows (according to Tip 25 of Jon C. Snader book's "Effective TCP/IP Programming"). So, by not checking the returned exceptions, we would miss the "connection refused" error and get instead the timeout error... From juneaftn at REMOVETHIShanmail.net Wed Sep 3 14:15:16 2003 From: juneaftn at REMOVETHIShanmail.net (Changjune Kim) Date: Thu, 4 Sep 2003 03:15:16 +0900 Subject: Tkinter Text widget getting too slow References: <ba1e306f.0309030713.ef2ec4a@posting.google.com> Message-ID: <bj5b4g$jtg$1@news.hananet.net> "Jane Austine" <janeaustine50 at hotmail.com> wrote in message news:ba1e306f.0309030713.ef2ec4a at posting.google.com... > As you add more items, say text lines, in Text widget, it gets too > slow and almost impractical to use on. Take idle for example. If the > text gets bigger(e.g. print > urllib.urlopen('http://www.amazon.com').read() ), it becomes too > sluggish to use as an "interactive" shell. > > I have tried wxPython and it seems to have the same problem (from my > experience using PyCrust). > > Is there any way to speed up Text widget, or should I look for another > GUI library? > > Jane Yes, it gets real slow. It happens quite often when a long single line is shown on the window currently, like in your amazon html example. Try this instead, pprint(urllib.urlopen('http://www.amazon.com').readlines()) It won't get slow even when it's still on the screen; it inserts multiple (short) lines. If you have to insert a lot of long lines, maybe you have to look into WCK and customize it as Michael said in his posting to the thread. (I'm interested to see his "extremely fast" text widget, too) Best regards, June Kim From eppstein at ics.uci.edu Thu Sep 11 17:11:41 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Thu, 11 Sep 2003 14:11:41 -0700 Subject: metaclasses for type comparison References: <pan.2003.09.11.01.50.58.897682@webone.com.au> <GBR7b.415613$uu5.75083@sccrnsc04> <pan.2003.09.11.04.48.46.966122@webone.com.au> <eppstein-B61455.11450111092003@news.service.uci.edu> <q6o1mv0tt1lgnhmmcvig9926rmuimc60he@4ax.com> Message-ID: <eppstein-401CE9.14114111092003@news.service.uci.edu> In article <q6o1mv0tt1lgnhmmcvig9926rmuimc60he at 4ax.com>, Gon?alo Rodrigues <op73418 at mail.telepac.pt> wrote: > ><= is supposed to be a total ordering, so it is not a good idea to use > >it for partial orders such as subclass hierarchies. > > Is it? I never came across such a supposition, which in itself says > nothing because I have very little experience anyway, but what about > set inclusion in the sets module which can be written as <=? I don't have 2.3 yet, so haven't used sets yet, but what happens if you try to sort a list of sets? I found a message <http://mail.python.org/pipermail/python-bugs-list/2003-January/015454.h tml> from Guido wondering about this but didn't see what the response was... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From dave at pythonapocrypha.com Sun Sep 21 21:47:27 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 21 Sep 2003 19:47:27 -0600 Subject: Connect to VBA Objects? In-Reply-To: <vmv8d1hdf55ia0@corp.supernews.com> References: <vmv8d1hdf55ia0@corp.supernews.com> Message-ID: <200309211947.27309.dave@pythonapocrypha.com> On Monday 22 September 2003 07:38 pm, Kenneth Hutson wrote: > Hi, > I wonder if Python can connect to the object models exposed by Excel or > Word. > Thanks in advance, > Ken Hutson > San Antonio, Texas Yep, assuming you have the win32all extensions installed: from win32com.client import Dispatch d = Dispatch('Word.Application') d.Visible = 1 ... -Dave From aleax at aleax.it Mon Sep 8 05:56:38 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Sep 2003 09:56:38 GMT Subject: Comments on Python Redesign References: <mailman.1062969251.5905.python-list@python.org> <qU9W/kKkXURB092yn@gnosis.cx> <mailman.1062983352.15417.python-list@python.org> Message-ID: <qnY6b.42704$R32.1360114@news2.tin.it> Lulu of the Lotus-Eaters wrote: > "Tim Parkin" <tim.parkin at pollenationinternet.com> wrote previously: > |Please could we move this discussion to one of the appropriate lists as > |well. I suggest python-marketing to begin with. > > A marketing list is just not an appropriate forum for discussing > redesigning the main python website. The page www.python.org just > simply should not be driven primarily, or even significantly, by > "marketing" issues... it's us developers who use it, in the overwhelming > majority. So, you're asserting that the target audience of the site IS and SHOULD BE "developers". Surprise, surprise: this assertion IS "a marketing issue". Marketing BEGINS with the identification of target audiences and the products and services that will best meet the target audiences' need. Many techies think of "marketing" as a dirty word because it's so often misused as an inappropriate synonym for "selling". Using words properly, marketing is a perfectly legitimate and important activity: identify who you're addressing, address their needs through appropriate products and services, communicate to them that your products and services do address their needs, listen to their feedback and adjust your products and services to meet their needs even better, look for other audiences that might get their needs met by your products and services possibily with some modifications. Alex From janeaustine50 at hotmail.com Thu Sep 4 09:31:58 2003 From: janeaustine50 at hotmail.com (Austine Jane) Date: Thu, 04 Sep 2003 22:31:58 +0900 Subject: Active Scripting in Python Message-ID: <BAY2-F91vvQ0Puz63Bm00011035@hotmail.com> >From: Mark McEahern <marklists at mceahern.com> >To: Jane Austine <janeaustine50 at hotmail.com> >CC: Python <python-list at python.org> >Subject: Re: Active Scripting in Python >Date: Thu, 04 Sep 2003 08:12:06 -0500 > >On Wed, 2003-09-03 at 23:23, Jane Austine wrote: > > I donwloaded win32all for Python 2.3 and installed it. > > > > I manually run pyscript.py and it returned "successfully registered" > > message. > > > > For a simple test(on client side), I created the following html: > > > > <script language=Python> > > alert("hello world") > > </script> > > > > And opened it in IE6.0 on WinXP. Unfortunately, it doesn't show > > anything. > >I can't test this right now because my Windows machine at home is dead >(long story), but have you tried using: > >print "hello world" > >OR > >document.write("hello world") > >I guess my question is whether "alert" is available when you're using >language="Python". > >// m > Tried. Neither one of both works. Thanks, anyway. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From mwilson at sarcastic-horse.com Tue Sep 23 12:43:31 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Tue, 23 Sep 2003 12:43:31 -0400 (EDT) Subject: idle import problem Message-ID: <49799.199.169.240.132.1064335411.squirrel@svr1.turboweb.net> Hi- I'm trying to import a countylist.py file in idle, and it isn't working. What am I doing wrong? >>> os.listdir(os.getcwd()) ['4dcountylist.txt', 'CBP90KY_TXT.htm', 'CBP90OH_TXT.htm', 'CBP90PA_TXT.htm', 'CBP90WV_TXT.htm', 'countylist.py', 'geocode.txt', 'mvsales.xls', 'mvsalesbyfirm.xls', 'production_in_4d.xls', 'USSalesSummary0308-1.xls'] >>> import countylist Traceback (most recent call last): File "<pyshell#15>", line 1, in -toplevel- import countylist ImportError: No module named countylist >>> Any ideas? From usenet at microtonal.co.uk Mon Sep 8 17:28:38 2003 From: usenet at microtonal.co.uk (Graham Breed) Date: Mon, 08 Sep 2003 22:28:38 +0100 Subject: win32com: create email message in windows default app? In-Reply-To: <cTZ6b.29715$hE5.1059970@news1.tin.it> References: <z9I6b.18545$n94.7236@fed1read04> <bjfpt5$l3s$1@news-reader4.wanadoo.fr> <TJK6b.18840$n94.10086@fed1read04> <cTZ6b.29715$hE5.1059970@news1.tin.it> Message-ID: <3w67b.3150$p%5.1938@news-binary.blueyonder.co.uk> Alex Martelli wrote: > Oh btw, > > os.system('start "mailto:foo at bar.com?subject=what ever"') > > if you want to pump the subject into the msg as well as the recipient. If I click that link in Mozilla, I get "whatever" as a single word. I don't think I ever worked out a way for Outlook and Mozilla to agree that there's a space in a subject. Either could be the default Windows mail client. Graham From essai1 at mci.local Thu Sep 18 17:47:03 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Thu, 18 Sep 2003 23:47:03 +0200 Subject: win32comm References: <mailman.1063896746.31017.python-list@python.org> <924a9f9c.0309181220.17bf6984@posting.google.com> Message-ID: <bkd98g$k9$1@news-reader5.wanadoo.fr> LOL -- Michel Claveau news://news.zoo-logique.org/programmation.Paradox From davidsch at verity.com Fri Sep 26 18:31:06 2003 From: davidsch at verity.com (David Schnepper) Date: Fri, 26 Sep 2003 15:31:06 -0700 Subject: When did Windows start accepting forward slash as a path separator? In-Reply-To: <b16e4ef7.0309251550.724a57f@posting.google.com> Message-ID: <DGEBJOLJPLKOEDDMLCGIKEBHCEAA.davidsch@verity.com> I use cygpath --mixed mode for converting. http://cygwin.com/cygwin-ug-net/using-utils.html#CYGPATH >From experimenting, a backslash seems required only at the beginning of a path, eg: cd /orant Error All the following are OK cd \orant cd c:/orant cd orant/win cd \orant/win Dave Schnepper -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of Stephen Ferg Sent: Thursday, September 25, 2003 4:51 PM To: python-list at python.org Subject: When did Windows start accepting forward slash as a path separator? I have a question that is not directly Python-related. But I thought I'd ask the most erudite group that I know... :-) When did Windows start accepting the forward slash as a path separator character? At one time, it was accepted as a truism that Windows (like MS-DOS) was different from Unix because Windows used the backslash as the path separator character, whereas Unix used the forward slash. But now, among a small group of cognoscenti, it is a truism that this is a myth, and that Windows will allow you to use either the forward or the backward slash as a pathname separator. I hypothesize that originally Windows accepted only the backslash, and then at some time it changed to accept the forward slash as well. Does anyone know when that change occurred? Was it with the introduction of support for long filenames in NT and Win95? -- http://mail.python.org/mailman/listinfo/python-list From missive at frontiernet.net Thu Sep 11 16:01:22 2003 From: missive at frontiernet.net (Lee Harr) Date: Thu, 11 Sep 2003 20:01:22 GMT Subject: PyQt: Can't show PY variable in QT filedialog as initially parameter References: <43e3984e.0309110814.7d759662@posting.google.com> Message-ID: <slrnbm1laj.96g.missive@localhost.my.domain> In article <43e3984e.0309110814.7d759662 at posting.google.com>, ulysses wrote: > Hi, > > I use PyQt 3.8 non-commercial version in win32. I get a big question. > I Can't show PY variable in QT filedialog as initially parameter. > > Code sample is following: > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > fileName="test.avi" > > def saveSomething(aString): > dl = QFileDialog.getSaveFileName(aString, "*.*", self, "FileDialog") > or > dl = QFileDialog.getSaveFileName(QString(aString), "*.*", > self, "FileDialog") > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > these code can't show corrent string. > > If I use string constant. > dl = QFileDialog.getSaveFileName("test.avi", "*.*", self, "FileDialog") > > Dialog show it correctly. > Maybe try: dl = QFileDialog.getSaveFileName(str(aString), "*.*", self, "FileDialog") From jjl at pobox.com Wed Sep 10 20:33:54 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Sep 2003 01:33:54 +0100 Subject: Heisenberg strikes again! References: <a82d9823.0309101254.39f8f05@posting.google.com> <nRM7b.311656$Oz4.100417@rwcrnsc54> Message-ID: <87wucg2mfh.fsf@pobox.com> "David C. Fox" <davidcfox at post.harvard.edu> writes: [...] > Apparently, readline treats an exception in the completer as > equivalent to returning None. In fact, you seem to be relying on this [...] That's pretty unpleasant. Naked except:s (with no specific exception) can cause about the weirdest bugs it's possible to get in Python. I think it's worth filing an SF documentation bug (or a patch, better) about that: set_completer should mention it. While debugging your completer function, try putting the whole content of the function in a big try: except:, and use the traceback module: from traceback import print_exc def my_completer(text, state): try: # put everything here ... except: print_exc() John From franck.lepoutre at caramail.com Tue Sep 30 03:03:27 2003 From: franck.lepoutre at caramail.com (francois lepoutre) Date: Tue, 30 Sep 2003 09:03:27 +0200 Subject: Group4 Tiff Images References: <mqm8nvsetc3vtddlt05p24jn6bevbnuvuh@4ax.com> <mailman.1064609500.411.python-list@python.org> Message-ID: <3f792925$0$19340$79c14f64@nan-newsreader-01.noos.net> > > Does PIL still not have a Group4 Tiff decoder available? > > http://mail.python.org/pipermail/image-sig/2003-July/002354.html Any chance that G4 Tiff make their way into the standard win32 PIL distribution? No C compiler here. Just plain python and a hell database work (including a load of G4 Tiff stored in blob). Thanx for your great stuff:) Franck From paustin at eos.ubc.ca Sun Sep 7 14:05:55 2003 From: paustin at eos.ubc.ca (Philip Austin) Date: 07 Sep 2003 11:05:55 -0700 Subject: OT: best book in years References: <opruzmelopdd8opo@news.vo.lu> <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <bj8el7$12m$07$1@news.t-online.com> <3F5868BA.85F506B4@engcorp.com> <bjaomi$ocq$06$1@news.t-online.com> <87oexyls54.fsf@pobox.com> <bjdm21$nr2$1@wheel2.two14.net> <mailman.1062908472.9309.python-list@python.org> <DGB6b.24532$hE5.902016@news1.tin.it> Message-ID: <m3smn8qxrw.fsf@gull.eos.ubc.ca> Alex Martelli <aleax at aleax.it> writes: > > Gould is a great writer, even though in his later works he often gives in to > unstructured rambling (I can of course well sympathize with THAT > temptation:-) -- Dawkins, IMHO, isn't, even though in "The selfish gene" he > does manage (by a mix of his powerful ideas and his dry direct prose) to > be truly riveting. My personal choice for Gould's masterpiece is "The > Mismeasure of Man". If you do want to see (essentially) Dawkins' ideas > presented by a truly great writer, try Matt Ridley -- "Genome", "Origins of > Virtue", "Red Queen", all superb writing (haven't read "Nature via Nurture" > yet -- I'll wait for the paperback). Not to be confused with *Mark* Ridley, > who also writes (quite worthwhile books and antologies) in exactly the > same field, mind you. See Allen Orr's New York Review of Books article for a cogent critique of Ridley's "Nature via Nurture": http://www.nybooks.com/articles/16522 Phil Associate Professor Atmospheric Sciences Programme Department of Earth and Ocean Sciences The University of British Columbia 6339 Stores Road Vancouver, BC V6T 1Z4 From prochak at netzero.net Mon Sep 22 00:39:09 2003 From: prochak at netzero.net (Erik Lechak) Date: 21 Sep 2003 21:39:09 -0700 Subject: Where to publish my code Message-ID: <1f0bdf30.0309212039.16c9bef0@posting.google.com> Hello All, I have started working on a graphical programming tool for Python. It is similar to Matlab's Simulink (block diagram programming tool). I am at a point where I would like to publish the code, but I am not sure where to put it. I don't need public CVS, bug list, feature suggestions ... I do need space on the server to store the application (it just can't point to my site). I would like the ability to update my code easily and frequently. It would be nice but not necessary to see how many people have downloaded the code. So far some solutions are: 1) Vaults of Parnassus - have not tried it yet. The registration process makes it looks like they don't provide the space for the application. I could be wrong? 2) Sourceforge - A little too bloated for my needs. But they do provide the space to put my code. I used them before and it was kind of a pain to do updates. 3) wxpython-pit.sourceforge.net - Is this a popular site? Are there other locations? Any recommendations? Thanks, Erik Lechak From bokr at oz.net Sat Sep 20 16:20:16 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2003 20:20:16 GMT Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> <AqQab.40174$NM1.1797@newsread2.news.atl.earthlink.net> <S6Tab.2$eb4.0@twister.southeast.rr.com> Message-ID: <bkicq0$vl5$0@216.39.172.122> On Sat, 20 Sep 2003 07:13:54 GMT, "M-a-S" <NO-MAIL at hotmail.com> wrote: >> "Andrew Wilkinson" <ajw126 at NOSPAMyork.ac.uk> wrote in message >> > >> > def fac(n): >> > return reduce(long.__mul__, range(1,n+1), 1L) >> > >> > ..would probably be a bit quicker. I'm not sure how much quicker though. >> > >> > Anyway, hope this is of some use, >> > Regards, >> > Andrew Wilkinson > >def factorial_rec(n): > if n <= 1: > return 1 > else: > return n*factorial_rec(n-1) > >def factorial_iter(n): > s = 1 > for i in range(2,n+1): > s *= i > return s > >def factorial_rdc(n): > return reduce(long.__mul__, range(1,n+1), 1L) > > >Best times (seconds) on Compaq 5430US, Pentium 4, 1.8GHz, 512MB >Windows XP, Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > >Calculations of 950!, 1000 times each (xrange(1000)) -- > >recursion ..... 8.01 >reduction ..... 4.20 >iteration ..... 3.79 > You could also let the factorial benefit from its own experience, e.g., >>> def factorial(n, cache={}): ... fn = cache.get(n) ... if fn: print 'got cached %s!'%n; return fn ... if n<2: cache[n]=1; return 1 ... return cache.setdefault(n, n*factorial(n-1)) ... >>> factorial(4) 24 >>> factorial(4) got cached 4! 24 >>> factorial(3) got cached 3! 6 >>> factorial(6) got cached 4! 720 >>> factorial(7) got cached 6! 5040 >>> factorial(7) got cached 7! 5040 >>> factorial(10) got cached 7! 3628800 >>> factorial(9) got cached 9! 362880 Or more concisely: >>> def fact(n, cache={}): ... return cache.get(n) or cache.setdefault(n, n<2 and 1 or n*fact(n-1)) ... >>> for i in range(10): print i, fact(i) ... 0 1 1 1 2 2 3 6 4 24 5 120 6 720 7 5040 8 40320 9 362880 Regards, Bengt Richter From tcronj at ananzi.co.za Tue Sep 30 03:46:50 2003 From: tcronj at ananzi.co.za (tertius) Date: Tue, 30 Sep 2003 09:46:50 +0200 Subject: append special chars with "\" Message-ID: <3f793544$0$64721@hades.is.co.za> Is there a better way to append certain chars in a string with a backslash that the example below? chr = "#$%^&_{}" # special chars to look out for str = "123 45^ & 00 0_" # string to convert n = "" # init new string for i in str: if i in chr: # if special character in str n+='\\' # append it with a backslash n+=i print "old:",str print "new:",n Thanks Tertius From brucedickey at micron.com Mon Sep 29 13:14:24 2003 From: brucedickey at micron.com (Bruce Dickey) Date: Mon, 29 Sep 2003 11:14:24 -0600 Subject: Meta programming question References: <vnce64dgqj047c@corp.supernews.com> <slrnbncfom.118.bignose-hates-spam@rose.localdomain.fake> <vnciijiteci947@corp.supernews.com> <ufzih2ali.fsf@boost-consulting.com> Message-ID: <bl9p9f$3an$1@admin-svc.micron.com> "David Abrahams" <dave at boost-consulting.com> wrote in message news:ufzih2ali.fsf at boost-consulting.com... > Bruce Dickey <ceiesa at excite.com> writes: > > > Ben Finney wrote: > >> On Sat, 27 Sep 2003 19:18:15 -0600, Bruce Dickey wrote: > >> > >>>I've read a number of the meta progamming articles. I have not found > >>>what I am looking for. I want to override assignments to variables > >>>which are in the module namespace (not object members -- no classes > >>>involved). Can this be done? > >> AFAIK, no. If it were possible, it would be very confusing. > >> What is it you're trying to achieve? Perhaps a better alternative > >> can > >> be suggested that doesn't break expected behaviour. > >> > > I'm investigating the use of Python as a grammar language. I'm trying > > to achive minimal required syntax/verbage. > > Cool! You might take a look at http://spirit.sf.net for some ideas. > Python's a great language for metaprogramming because of its rich > syntax. If you were willing to discourage left-recursion you might go > with something like: > > expression = term._('+').expression | term._('-').expression > > On the other hand, when I had to do something like this I built my own > "python-like" syntax for the grammar rules and left the semantic > actions in pure Python, then ran the files through a simple > preprocessor. It's just too ugly to write grammar rules in pure > python without overloaded whitespace. > > -- > Dave Abrahams > Boost Consulting > www.boost-consulting.com I'll look into it, thanks. But I had essentially come to the same conclusion. Bruce From NO-MAIL at hotmail.com Fri Sep 19 06:17:15 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Fri, 19 Sep 2003 10:17:15 GMT Subject: file position *tell()* works different References: <13a533e8.0309190137.2df0cc60@posting.google.com> Message-ID: <LIAab.7544$9G2.6227@twister.southeast.rr.com> I'm not sure if that't the reason, but the binary mode for reading is 'rb'. Actually, the order of 'r' and 'b' shouldn't matter. But the '+' has a different meaning: the file should allow "opposite" access as well, e.g. 'r+', 'rb+' means that you can write to the file too, while 'w+' means: open it for writing but permit reading too. You can try to say 'rt' for the read/text mode. Anyway, you program works under Windows XP/Python 2.3 as expected: Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Home\Programming\Python\2>py Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>^Z C:\Home\Programming\Python\2>test.py Filepointer: 0 Filepointer: 12 Filepointer: 24 Filepointer: 35 Filepointer: 54 Filepointer: 0 Filepointer: 12 Filepointer: 24 Filepointer: 35 Filepointer: 54 I'm sorry if it doesn't help. The bug must be somewhere else then. M-a-S "Peter Abel" <p-abel at t-online.de> wrote in message news:13a533e8.0309190137.2df0cc60 at posting.google.com... > Hi all, > I'm working under W2k with > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 > > I have a file *test_data.txt* with the following content: > 0123456789 > 0123456789 > abcdefghi > ABCDEFGHIJKLMNOPQ > > and I work on it with the following python script: > > # Open NOT in binary mode > fp=file('test_data.txt','r') > a='xx' > while a: > print 'Filepointer: %3d' % fp.tell() > a=fp.readline() > fp.close() > > print > > # Open IN binary mode > fp=file('test_data.txt','r+b') > a='xx' > while a: > print 'Filepointer: %3d' % fp.tell() > a=fp.readline() > fp.close() > > Now, when test_data.txt is saved in PC-mode with 0xC, 0xA as newline > it works correct. > But when I save the file in UNIX-Mode with 0xA as newline, > my script gives me the following output, where that one with > the file not opened in binary mode is wrong: > Filepointer: 0 > Filepointer: 7 > Filepointer: 19 > Filepointer: 30 > Filepointer: 49 > Filepointer: 51 > > Filepointer: 0 > Filepointer: 11 > Filepointer: 22 > Filepointer: 32 > Filepointer: 50 > Filepointer: 51 > > When I try this under HP-UX it works fine in both cases. > So I wonder if the function *tell()* is not correctly implemented under win32. > > Regards > Peter From webmaster at beyond-thoughts.com Thu Sep 25 15:44:22 2003 From: webmaster at beyond-thoughts.com (Christoph Becker-Freyseng) Date: Thu, 25 Sep 2003 21:44:22 +0200 Subject: Comment on PEP-0322: Reverse Iteration Methods In-Reply-To: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> Message-ID: <3F734596.80207@beyond-thoughts.com> Hello, While I'm +1 for this PEP in general, I still miss a proper definition of a "reverse-iteration". I've previoulsly posted one. Yours Sincerly, Christoph Becker-Freyseng From andrew-pythonlist at puzzling.org Mon Sep 15 05:54:49 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 15 Sep 2003 19:54:49 +1000 Subject: Finally found a use for lambda! In-Reply-To: <840592e1.0309150033.3622d1f9@posting.google.com> References: <roy-FFBAC5.22283914092003@reader2.panix.com> <840592e1.0309150033.3622d1f9@posting.google.com> Message-ID: <20030915095449.GA2226@frobozz> On Mon, Sep 15, 2003 at 01:33:06AM -0700, Hannu Kankaanp?? wrote: > Roy Smith <roy at panix.com> wrote in message news:<roy-FFBAC5.22283914092003 at reader2.panix.com>... > > > > so I guess I didn't really need the lambda after all :-) > > Lambda is pretty useless in Python, unfortunately. List comprehensions > reduce their uses with filter and map, and any more complex closure > has to be written as a named function anyway.. I wish lambda would > allow statements in them also, so I could do > > func(lambda x: arr[x] = y) Well, you *could* do func(lambda x: arr.__setitem__(x, y)). But you probably shouldn't ;) -Andrew. From __peter__ at web.de Sun Sep 21 08:10:16 2003 From: __peter__ at web.de (Peter Otten) Date: Sun, 21 Sep 2003 14:10:16 +0200 Subject: Trouble sorting lists (unicode/locale related?) References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> Message-ID: <bkk4h1$9ke$06$1@news.t-online.com> Erlend Fuglum wrote: > Hi everyone, > > I'm having some trouble sorting lists. I suspect this might have > something to do with locale settings and/or character > encoding/unicode. > > Consider the following example, text containing norwegian special > characters ?, ? and ?. > >>>> liste = ["ola", "erlend", "trygve", "?rlige anders", "Lars", >>>> "?ksemorderen", "?sne", "Akrobatiske Anna", "leidulf"] liste.sort() >>>> liste > ['Akrobatiske Anna', 'Lars', 'erlend', 'leidulf', 'ola', 'trygve', > '\xc5sne', '\xc6rlige anders', '\xd8ksemorderen'] > > There are a couple of issues for me here: > * The sorting method apparently places strings starting with uppercase > characters before strings staring with lowercase. I would like to > treat them them equally when sorting. OK, this could probably be fixed > by hacking with .toupper() or something, but isn't it possible to > achieve this in a more elegant way? > > * The norwegian special characters are sorted in a wrong way. > According to our alphabet the correct order is (...) x, y, z, ?, ? ?. > Python does it this way: (...) x, y, z, ?, ?, ? ? > > I would really appreciate any help and suggestions - I have been > fiddling with this mess for quite some time now :-) Try setting the appropriate locale first: import locale locale.setlocale(locale.LC_ALL, ("no", None)) Then for a case-insensitive sort: wordlist.sort(locale.strcoll) should do (disclaimer: all untested). Peter From gherron at islandtraining.com Mon Sep 22 05:40:06 2003 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 22 Sep 2003 02:40:06 -0700 Subject: Begineer Question : Global string substitution with re In-Reply-To: <Law11-F51JfEg897Bqg00010f1e@hotmail.com> References: <Law11-F51JfEg897Bqg00010f1e@hotmail.com> Message-ID: <200309220240.06441.gherron@islandtraining.com> On Monday 22 September 2003 02:22 am, peter leonard wrote: > Hi, > This is a basic question but I can't figure out what is wron - even after > reading the documentation. I have a script that normalizes strings. One of > the steps is to convert all fractions too the tag 'fraction'. For example : > > import re > line = "This is the first ratio, 170/37, and this is the second 170/37 " > > > def normalise(text): > > #Tag fractions > fraction = r'(\s+\d+\/\d+\s+)' > regfr = re.compile(fraction) > text = regfr.sub(" |fraction| ",text) > > #Remove punctuation > punc = r'\,' > regpunc = re.compile(punc) > text = regpunc.sub("",text) > > return text > > print line,"\n" > print normalise(line),"\n" > > > The output from this script is : > > This is the first ratio, 170/37, and this is the second 170/37 > > This is the first ratio 170/37 and this is the second |fraction| > > > I can't understand why only one of the fractions gets substituted. The > documentation for sub states that the default argument for sub is 0 which > means replace all occurences. The output of my script should be : > > This is the first ratio |fraction| and this is the second |fraction| The problem is that your regular expression ends with "\s+". This means the digits of the fraction *must* be followed by at least one space, and the digits of your first fraction are followed by a comma and not a space. Your re is matching spaces--fraction--spaces. I'd guess that you don't really want to match spaces on either side of the fraction. Gary Herron From adalke at mindspring.com Tue Sep 30 23:38:51 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 01 Oct 2003 03:38:51 GMT Subject: "for" with "else"? References: <bkuqmu$ajv$1@ctb-nnrp2.saix.net> <bkuru4$532$1@news.wrc.xerox.com> <vn61legdn9jf56@news.supernews.com> <2c9knv86m1il4ajng85655dm7u5j5b992i@4ax.com> <vnkds7nbjf8420@news.supernews.com> Message-ID: <f%reb.10797$NX3.1826@newsread3.news.pas.earthlink.net> John Roth: > I don't see what exceptions have to do with it. There are three > special ending cases: with break, empty sequence and sequence > exhausted. Empty sequence is the only one that isn't handled easily. Could you give an example of when you would actually use an 'empty_sequence' in the real world? It's never been a problem for me (that I can recall) where that distinction was important. > What I'd like to see is a more general exit clause that also > applies to the while statement. Something like: > > on break: > on normal_exit: > on empty_sequence: > on body_not_executed: Aren't 'empty_sequence' and 'body_not_executed' identical? Could you give examples using each one? What about code which uses a return in the block? Is that counted under 'break'? What about raising an exception? Andrew dalke at dalkescientific.com From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Tue Sep 23 13:49:00 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Tue, 23 Sep 2003 21:49:00 +0400 Subject: Sound, time and platform issues In-Reply-To: <bka4k6$j9a$1@news.peterlink.ru> References: <bka4k6$j9a$1@news.peterlink.ru> Message-ID: <bkq127$1lnf$1@news.peterlink.ru> anton muhin wrote: [skipped] thank you everybody for input, anton. From bit_bucket5 at hotmail.com Tue Sep 23 08:11:54 2003 From: bit_bucket5 at hotmail.com (Chris Stromberger) Date: Tue, 23 Sep 2003 12:11:54 GMT Subject: Need arguments for "Python vs. Perl as an OOPL" References: <roy-002696.23242122092003@reader2.panix.com> Message-ID: <01e0nvkhjp8t6dsu34f9g1a9p9v2h0mrrb@4ax.com> On Mon, 22 Sep 2003 23:24:21 -0400, Roy Smith <roy at panix.com> wrote: >I'm working on a prototype of a new application in Python. At some >point, if this ever turns into a product, the powers that be will almost >certainly demand that it be done in Perl. My job will be to convince >them otherwise. > >The basic design of the application is object oriented. I've never used >Perl's OO features, so I'm not in a good position to make a comparison >of the two languages from an OO point of view. Can somebody who's done >OOP in both Python and Perl help me out? > >I certainly know why Perl sucks in general, but for this purpose, I need >to specifically compare the OO features of the two. I'm looking for >something more fundamental than "->{} is ugly". Perl classes: unintuitive, hard to learn, IS ugly! Good luck. I work in a Perl shop. Only a few of us are on to Python. Cannot seem to break through to the Perl Zombies. http://www.strombergers.com/python/python_perl_class.html http://www.strombergers.com/python/python_perl_inheritance.html From martin at v.loewis.de Mon Sep 15 17:39:19 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 15 Sep 2003 23:39:19 +0200 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911162016.02027750@telecommunity.com> <mailman.1063342640.29560.python-list@python.org> <ipicnag7OpxdLfyiRTvUpQ@speakeasy.net> <Hqk8b.382$BS5.239@newsread4.news.pas.earthlink.net> <V_mdnZ3eKoGjif6iRTvUpQ@speakeasy.net> <3F632226.2010607@earthlink.net> <lcydnasf88GLyP6iRTvUrg@speakeasy.net> <EIL8b.6564$ZB4.1083@reader1.news.jippii.net> <f575e202.0309151024.2b7981ea@posting.google.com> <mwo9b.242$B13.103@reader1.news.jippii.net> Message-ID: <m3y8wpwx2w.fsf@mira.informatik.hu-berlin.de> Harri Pesonen <fuerte at sci.fi> writes: > The point I was trying to make (not in this message but in general) is > that it would be simple (trivial but tedious) to create a version of > Python that is thread-safe, and the only reason it is not done is > because it would break old code. So we are in this GIL world just > because of that old code... This statement is not true. It is not trivial, and it is not being not done because of old code. Your approach to support "multi-threading" (add an interpreter state to all functions) would allow to use different interpreters across different threads, and those interpreters could not share a single object. I doubt that this is what most users would want as "SMP Python", and it has no significant difference over a multi-process solution. IOW, it is a useless approach. > It's like Visual Basic 6, it can't multitask properly either (but > for other reasons). All other modern languages are > free-threaded. Before I learned Python I assumed that it is as well. You mean, like Tcl, Perl, or Ruby? Neither of these has free threading (plus, your proposed implementation strategy would not offer free threading, either) > Only one global variable left (in fact there is Py_None as well). Why > not get rid of it, then?? Because global variables are not the only problem. Not even the most important one. Atleast not if you want free threading. Regards, Martin From dave at pythonapocrypha.com Sun Sep 7 22:18:05 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 7 Sep 2003 20:18:05 -0600 Subject: Eureka! (Re: Comments on Python Redesign) In-Reply-To: <3F5CD10B.2020709@teksavvy.com> References: <mailman.1062962051.23295.python-list@python.org> <bjibik$g3n$1@panix3.panix.com> <3F5CD10B.2020709@teksavvy.com> Message-ID: <200309072018.05589.dave@pythonapocrypha.com> On Monday 08 September 2003 12:57 pm, Graham Fawcett wrote: > Aahz wrote: > >Many people, me included, won't follow tinyurl links; please provide a > >standard URL, too. [snip] > Thanks for the heads-up re: tinyurl. I realize that some unfriendly folk > may enjoy sending people to goatse or some similarly unsavoury site; I > guess I haven't been burned and have enjoyed the brevity of those URLs. I don't know of any problem with tinyurls - *any* server can provide a "bad" redirect; as with any URL whether or not you follow it depends on the context and on how much you trust the sender. Maybe Aahz has another reason in mind, but I don't know of any reason to stop using them. -Dave From hans at zephyrfalcon.org Tue Sep 9 10:58:02 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 09 Sep 2003 10:58:02 -0400 Subject: What does the keyword 'global' really mean In-Reply-To: <3f5db3b6$0$252$fa0fcedb@lovejoy.zen.co.uk> References: <3f5db3b6$0$252$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3F5DEA7A.2050209@zephyrfalcon.org> John Dean wrote: > Hi > I have been looking through some Python code and I came across the keyword > 'global'. I have looked through the docs and two or three Python programming > books for a full explanation of what 'global' really means. Would I be > correct in assuming that any variable prefixed with the keyword global would > allow that variable to be accessible across translation units, in other > words global is equivalent to the 'C' keyword 'extern' ? It's really quite simple. Within a function, assignments are local (by default): >>> x = 42 >>> def f(): x = 3 print x >>> f() 3 >>> x 42 When executing f(), it creates a local variable x with value 3, and prints it. The global variable x is unaffected. You can change this behavior by using the 'global' statement: >>> def g(): global x x = 6 print x >>> g() 6 >>> x 6 'global x' tells Python that the x in this function is global rather than local, so 'x = 6' refers to the global variable x we already created. (As a side note, it may seem like you change an existing variable, but what it actually does it rebind the name 'x' that already existed in the global namespace.) As you can see, the global variable x is overwritten and how has a value of 6. To make matters a bit more confusing, you don't need 'global' to *access* a global variable from within a function, only when you assign to it. This works: >>> def h(): print x >>> h() 6 There's no local variable x this time, but 'x' obviously refers to the global one. > Also, does Python have the equivalent of the 'C' keyword 'static'? No. There are (clumsy) ways to fake it, but you'll probably be better off writing code in a Pythonic way, rather than trying to emulate a C style. HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Thu Sep 18 11:54:32 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Thu, 18 Sep 2003 19:54:32 +0400 Subject: How to inheritance overwrite non virtual? In-Reply-To: <slrnbmjjp4.her.axel@pizza.home.kosnet.com> References: <slrnbmjhjr.gud.axel@pizza.home.kosnet.com> <bkchst$q0r$03$1@news.t-online.com> <slrnbmjjp4.her.axel@pizza.home.kosnet.com> Message-ID: <bkckfm$177k$1@news.peterlink.ru> Axel Straschil wrote: > Hi! > > >>The following will do: >> >>class Derived(Base): >> def method(self): >> return Base.method(self) # call base class method > > > I tried in my chield-class: > class K2(KObject): > def bestCaption(self): > return "Overwritten" > def bestCaptionlong(self): > return KObject.bestCaptionlong(self) > > The Problem ist inside of KObject.bestCaptionlong(self): > return self.bestCaption() > > The mother-class is calling the method of the child-class, not > it own method. I want the mother-method to be called like "the > chield never was existing", but I find no way. > > Anny other idea? > > Thank, AXEL. Change return self.bestCaption() to return KObject.bestCaption(self) hth, anton. From mcherm at mcherm.com Thu Sep 11 13:22:22 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Thu, 11 Sep 2003 10:22:22 -0700 Subject: Pass-by-reference : Could a C#-like approach work in Python? Message-ID: <1063300942.3f60af4e8dd38@mcherm.com> First, thanks to Stephen Horne for bringing up this subject. I learn more about language design in this newsgroup than anywhere else (perhaps people who appreciate good language design gravitate to Python?). I started by looking for use cases... where would this proposed pass-by-reference actually prove useful? Stephen basically found one good use case: I wish to "transfer ownership" of an object that gets passed into a method call, and protect against the caller accidently continuing to use the object. [So, we'll use a "ref" parameter and set the caller's variable to None.] But "pass by reference" isn't the first idea I have on reading the use case. I agree with Peter Otten, who writes: > if copying is costly and only > sometimes necessary, wrap the item into a copy-on-write proxy for every > logically distinct but physically identical instance. Excellent idea! But, how do I write a copy-on-write proxy in Python? Seems like this would make an excellent cookbook recipie, but I couldn't figure out how to do it. Proxying is easy, but how does one distinguish between mutating and non-mutating methods? Does the proxy need to be customized for each class to be wrapped? Also I wanted to mention what _I_ saw as the major reason why including reference parameters in Python would be a bad idea. Stephen himself pointed out that without compelling use cases, YAGNI should rule. But the counter argument of "it will allow unexpected changes whenever I invoke a method" is completely bogus -- from the beginning Stephen pointed out that special syntax should be required BY THE CALLER. And the counter argument of "it will slow things down" is dubious at best (cPython method calls are already so slow that it's unclear how much difference this would make). But my counter argument would be that this breaks one of the elegent simplicities of Python -- that callables of all kinds are equivalent and have a very simple interface. A callable receives (in effect) one tuple of values, and one map of values. That's it. That's a very simple protocol. Functions and methods are written with a bunch of ordered, named parameters, (some of which may have defaults), that are filled in from this tuple and map, and perhaps an overflow tuple and map for additional inputs. There's no place in this simple protocol for type declarations (of course), and there would be no place for tracking whether an argument was "ref" or not. To add even that one boolean property would significantly complicate callables. I think that having a small number of protocols that are very simple yet very powerful is a wonderful way to design a language. Python's callables are very simple, yet powerful. Iterators are another such example. Making classes consist primarily of a namespace (__dict__) was another, although that has gotten much more complicated as things like descriptors are introduced. Anyway, just wanted to share some thoughts you had triggered. Thanks for the ideas. I'd-cc-Stephen-Horne-directly-but-it'd-be-rejected-as-a-Nigerian-scam lly, -- Michael Chermside From gherron at islandtraining.com Wed Sep 24 02:08:37 2003 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 23 Sep 2003 23:08:37 -0700 Subject: float problem In-Reply-To: <bkrai0$50pag$1@ID-70710.news.uni-berlin.de> References: <bkrai0$50pag$1@ID-70710.news.uni-berlin.de> Message-ID: <200309232308.37325.gherron@islandtraining.com> On Tuesday 23 September 2003 10:34 pm, Indigo Moon Man wrote: > for the formula J = I / (12 * 100) where I is low (like about 8 to 15) I > get 0. But when I do it with a calculator it's actually .008333 for > example if I were 10. Is there a way I can get python to recognize the > .008333 instead of it just giving me 0? You're getting bit by the difference between integer and float division. In versions of python prior to 2.3 (and in 2.3 under normal circumstances), division of two integers returns an integer and division of two floats (or a float and an integer )returns a float: >>> 2/3 0 >>> 2/3.0 0.66666666666666663 >>> 2.0/3.0 0.66666666666666663 >>> So one solution would be to make sure the numbers you are dividing are floats when you want a float in return. In future version of Python, there will be two dividion operators: / will always return a float // will always return an int In Python 2.3, you can experiment with the future behavior by starting your program with: >>> from __future__ import division >>> 2/3 0.66666666666666663 >>> 2//3 0 >>> So depending on your version of Python, this may be another solution. Gary Herron From p.useldinger at myrealbox.com Sat Sep 6 10:19:33 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Sat, 06 Sep 2003 16:19:33 +0200 Subject: OT: best book in years References: <opruzmelopdd8opo@news.vo.lu> <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <bj8el7$12m$07$1@news.t-online.com> <3F5868BA.85F506B4@engcorp.com> <bjaomi$ocq$06$1@news.t-online.com> <m3brty8vs2.fsf@tanelorn.bandersnatch.org> Message-ID: <b4rjlvs00ptpv9pjat02ug0vlahbnd6equ@4ax.com> On 05 Sep 2003 23:01:49 -0400, Nick Vargish <nav+posts at bandersnatch.org> wrote: >Good god, man! The guy's already going to be in the hospital. GEB is >something that should be tackled at full health. > >Nick To tell you the truth, one book on my list is also "The Tibetan Book of Living and Dying" ;-) Did I mention that it was *nothing* serious (unless the surgeon runs into an uncatched exception...) -Patrick From neelk at cs.cmu.edu Mon Sep 1 11:58:22 2003 From: neelk at cs.cmu.edu (Neelakantan Krishnaswami) Date: Mon, 1 Sep 2003 15:58:22 +0000 (UTC) Subject: Language categories References: <Ivw2b.1305$Ce2.314@clmboh1-nws5.columbus.rr.com> <rqy2b.1796$_F1.202013@news20.bellglobal.com> <tyfsmno989n.fsf@pcepsft001.cern.ch> <sDJ2b.1909$_F1.271943@news20.bellglobal.com> <vl63bokhnobnee@corp.supernews.com> <bivkor$m70$1@terabinaries.xmission.com> Message-ID: <slrnbl6r4u.vld.neelk@gs3106.sp.cs.cmu.edu> In article <bivkor$m70$1 at terabinaries.xmission.com>, Thant Tessman wrote: > Cameron Laird wrote: >> In article <sDJ2b.1909$_F1.271943 at news20.bellglobal.com>, >> Sean Ross <sross at connectmail.carleton.ca> wrote: >> >>>>"Sean Ross" <sross at connectmail.carleton.ca> writes: >>>> >>>> >>>>>(Lisp, Dylan, Haskell, ocaml, or some other functional programming >>>>>language). >> >> Someone needs to talk with the googlers; REBOL and Dylan >> are not functional languages. And Lisp ... well, Lisp is >> universal, so let's let that pass. > > Not to re-open that can o' worms, but last time I looked, Dylan > supported functional programming style just fine. If memory serves, its > word for 'lambda' is 'method.' I've never heard of REBOL. Yeah, Dylan is basically Scheme + CLOS, with a Modula-style syntax. So it's a functional language. REBOL is more interesting. The original interpreter was written by Joe Marshall, and he wrote it so that it supported lexically-scoped closures (and maybe tail-recursion too?). This makes it count as an fpl, in my book. However, the second version was a rewrite that lost those features, and as a result it's not an fpl anymore. -- Neel Krishnaswami neelk at cs.cmu.edu From dave at boost-consulting.com Fri Sep 26 20:41:08 2003 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 26 Sep 2003 20:41:08 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <wCGcb.3064$yU5.2141@nwrdny01.gnilink.net> <8RScb.169633$R32.5449258@news2.tin.it> <uk77vhagj.fsf@boost-consulting.com> <JH_cb.174346$R32.5548036@news2.tin.it> <u7k3ve63q.fsf@boost-consulting.com> <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> Message-ID: <ur8239i6z.fsf@boost-consulting.com> Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: > On Fri, 26 Sep 2003 14:51:05 -0400, David Abrahams > <dave at boost-consulting.com> wrote: > >>Alex Martelli <aleax at aleax.it> writes: >> >>> David Abrahams wrote: >>> ... >>>> Also, the idea of denying tuples the ability to reverse iterate seems >>>> arbitrary and capricious. >>> >>> Sure, but so is denying them, e.g., non-mutating methods such as >>> .index() and .count(). >> >>Not IMO. Immutability is a very useful trait. > > Yes - and perfectly consistent with having *NON*-mutating methods such > as .index() and .count() ;-) Right. Oops, I misread. > I always assumed that these were considered inconsistent with normal > use of tuples (which certainly I rarely need to get 'index' or > 'count'-like results from). I don't see why not. > Actually, they even seem a little odd in list, to be honest. I'd have > functions, not necessarily even in __builtins__, which work on any > sequence. They just don't seem like everyday operations that should be > built into the object. It's probably just for optimization purposes. -- Dave Abrahams Boost Consulting www.boost-consulting.com From reply.in.the.newsgroup at my.address.is.invalid Wed Sep 24 05:20:00 2003 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Wed, 24 Sep 2003 11:20:00 +0200 Subject: Python <-> C via sockets References: <8ad2cfb3.0309240113.19d9198a@posting.google.com> Message-ID: <rbo2nv0k4q5ctfa12q2rd6bi6guoa5igi9@4ax.com> Nick Keighley: >is there a known problem with getting a Python based socket program to >communicate with a C based socket program? No. Client and server are completely independent and can be implemented in any language. They must speak the same application level protocol of course, on top of TCP/IP. -- Ren? Pijlman From skip at pobox.com Fri Sep 19 11:23:54 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Sep 2003 10:23:54 -0500 Subject: Webware and memory problem! In-Reply-To: <tf1mmv019lp8cucqvcgtf5v9qi2svv4n36@4ax.com> References: <tf1mmv019lp8cucqvcgtf5v9qi2svv4n36@4ax.com> Message-ID: <16235.8074.974349.489833@montanaro.dyndns.org> jz> How much memory WebKit should normally take??? As I can see, every jz> WebKit daemon takes over 40MB (sic!) of RAM. WebKit lauches 10 jz> daemons during startup, so I need over 400MB for WebKit alone! Is it jz> normal or I have something wrong configured? (used RedHat7 and jz> Webware CVS 2003-09-12) Most of that 40MB is probably shared between all processes (C libraries, etc). On the other hand, the Python bytecode, which should be sharable, is almost certainly loaded into the interpreter's data space, so isn't shared. I'd be surprised if it was very much of the total memory usage, however. Skip From jjl at pobox.com Fri Sep 5 10:25:18 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Sep 2003 15:25:18 +0100 Subject: in Ram database? References: <mailman.1062728122.8678.python-list@python.org> Message-ID: <87ekyvcnxt.fsf@pobox.com> "John D." <lists at webcrunchers.com> writes: [...] > Is such a database available? If so, who is working on it, > or where is it? Gadfly, PySQLite. > I've heard that Python supports a stand-alone database. I looked > for it in the Docs, and see the "dbm" module. I haven't found > any examples of code, so don't know how to use them. I'm one > of those guys that learn through examples, and have very little > luck in figuring out how to use anything unless I can see examples > of their use. These sorts of dbs aren't in-memory. Still, if you want to find some simple examples, I'm sure a few queries like 'group:comp.lang.python bsddb example' in Google Groups will find something. > My idea is that ALL datums would be Python Dictionary objects, so > not only can you store data, but python objects as well. Sounds like you might want ZODB (again, not in-memory). It's more of an object persistence system + BTrees than it is a DBMS, since there's no query system. IndexedCatalog is a query system built on top of ZODB, but it's quite feasible to roll your own simple application-specific queries with BTrees (and the other data structures it provides). BTrees are rather like dictionaries, but they support on-demand loading of data, so not everything has to be in memory at once. > I kinda like the idea of being able to define smaller tables as > "in-memory" types, and the really large massive ones in other forms > managed by mySQL, PostGres, or bsddb3 databases. That sounds like a recipe for extra work to me. If you need a big DBMS, use that for everything. John From tzot at sil-tec.gr Wed Sep 24 12:26:41 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 24 Sep 2003 19:26:41 +0300 Subject: why the inconsistency? References: <fbf22ff1.0309231704.3f324abf@posting.google.com> Message-ID: <4bh3nv0esljf8pkegog0lc4lmg87siv1oc@4ax.com> On 23 Sep 2003 18:04:33 -0700, rumours say that mensanator at aol.com (mensanator) might have written: [snipped] >But if I want to know how many digits 2**64 has, I can't >just do If only math.log(2**64)/math.log(10) worked with longs without converting them into floats first... :( -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From __peter__ at web.de Fri Sep 12 03:48:28 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 Sep 2003 09:48:28 +0200 Subject: [newbie] File handle destroyed before pending write is executed? References: <3f6172be.1493111@news.tijd.com> Message-ID: <bjrtos$brd$03$1@news.t-online.com> Pieter Lust wrote: > # main module > import logmodule > > mylog = logmodule.logfile() > mylog.enter('something') > # pass > # end main module > > # logmodule > class logfile: > def __init__(self): > self.fh = file('log.txt', 'w') > def __del__(self): > self.fh.close() > def enter(self, text): > self.fh.write('%s\n' % text) > # end logmodule > > After running the main module, log.txt was empty, though no exceptions > were raised. To get the text into the file, I had to add the pass > statement that's commented out above. > > In debug mode, the line cursor jumps from the last line of the main > module into the __del__() method of the logmodule, but not into the > enter() method. > Your code works here. I wuuld delete all logmodule.pyc files in your path and restart the IDE. Maybe there is something out of sync. (By the way, I think the __del__() method is superfluous) Peter From fuerte at sci.fi Tue Sep 16 13:06:00 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Tue, 16 Sep 2003 20:06:00 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <mailman.1063659502.2922.python-list@python.org> References: <mailman.1063659502.2922.python-list@python.org> Message-ID: <tmH9b.79$2k.36@reader1.news.jippii.net> Brian Quinlan wrote: >>The point I was trying to make (not in this message but in general) is >>that it would be simple (trivial but tedious) to create a version of >>Python that is thread-safe, and the only reason it is not done is >>because it would break old code. > > Actually, it would be reasonably difficult. If you don't agree why not > spend a weekend implementing it and see how robust your implementation > is? Also, adding object-level locking would involve a huge performance > penalty. There is no object-level locking in my proposal. Just independent free-threaded interpreters, which don't see the objects of other interpreters at all. There could be an extra global interpreter state for shared-memory object access. Accessing this would always be synchronized, but only this. Python would automatically copy data from this state to thread-local state and back when needed. This would require a special syntax for variables in global state: synchronize a = "asdf" >>Only one global variable left (in fact there is Py_None as well). Why >>not get rid of it, then?? > > I think that you must be missing something... There is nothing special > about Py_None. The number 5 is globally shared just like Py_None is. > This is a performance optimization used to prevent lots of small numbers > from being allocated and destroyed all the time. Py_None is special because it is shared between all interpreters, it is global. Py_None is defined as: #define Py_None (&_Py_NoneStruct) PyObject _Py_NoneStruct = { PyObject_HEAD_INIT(&PyNone_Type) }; static PyTypeObject PyNone_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, "NoneType", 0, 0, (destructor)none_dealloc, /*tp_dealloc*/ /*never called*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)none_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ }; From the above we see that when Py_None reference count reaches zero, a destructor none_dealloc is called. static void none_dealloc(PyObject* ignore) { /* This should never get called, but we also don't want to SEGV if * we accidently decref None out of existance. */ Py_FatalError("deallocating None"); } This makes no sense at all. Why Py_FatalError? It would be better to have static void none_dealloc(PyObject* ignore) { } so that it is not necessary to call Py_INCREF(Py_None) Py_DECREF(Py_None) at all. Guess how many times these are called in Python C API? Py_INCREF is called 2001 times and Py_DECREF two times. OK, Python also calls _Py_ForgetReference on the object when it is freed, so that something else should be changed here as well. _Py_ForgetReference unlinks the object from double linked list. By changing the way how Py_None is freed (by doing nothing) Python would get simpler and faster. And of course you could give Py_None a large reference count on startup, so that the deallocator is never actually called (even if it does nothing). If there are more of these static objects, like number 5 as you said, then the destructor for these should be changed as well, so that they are never freed. This way the independent free-threaded interpreters don't have to worry about these objects. Harri From geoff at gerrietts.net Thu Sep 11 20:25:33 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 11 Sep 2003 17:25:33 -0700 Subject: Web server with Python In-Reply-To: <3f60fa3d-a26c0463-9b36-4152-a986-61060ca18017@news.szn.dk> References: <tnr1mvgnt45urvu6n4q6dso3eto73hfr1m@4ax.com> <sx68b.29387$Hb.450091@news4.e.nsc.no> <3f60fa3d-a26c0463-9b36-4152-a986-61060ca18017@news.szn.dk> Message-ID: <20030912002532.GG2085@thoth.homegain.com> Quoting Klaus Alexander Seistrup (spam at magnetic-ink.dk): > Thomas Weholt wrote: > > >> - must be able to use Python 2.3 to create dynamic pages > > > > If you can use anything found on www.zope.org under resource and > > like to do everything in a webpage, not doing much programming > > yourself, then Zope might be the thing. > > However, Zope still doesn't run on Python 2.3, does it? Also true! Beta versions recommend/require 2.2.3, and current production last time I checked (last week? week before?) requires 2.1.3 instead. --G. -- Geoff Gerrietts "Overspecialize and you breed in weakness. <geoff at gerrietts net> It's slow death." -- Maj. Motoko Kusanagi http://www.gerrietts.net (Ghost in the Shell) From p.useldinger at myrealbox.com Thu Sep 11 15:58:50 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Thu, 11 Sep 2003 21:58:50 +0200 Subject: mod_python installation References: <kue1mv4fer2lncl8r17q2vmhi30drvme2k@4ax.com> <ss38b.700$8g2.400@news1.central.cox.net> Message-ID: <7hk1mv4jd83ie754rgfrk8pf5u9tchiknn@4ax.com> On Thu, 11 Sep 2003 18:48:56 GMT, "Dave Benjamin" <dave at 3dex.com> wrote: >This might be a dumb question, but did you check the error log or the access >log? What happens when you try to start apache from the command line? (is >that possible in Windows? I've never tried...) I looked at the error log. In the Windows Event Log, I found the following: ======================================= Application log: The Apache service named reported the following error: Cannot load C:/Programs/Apache/Apache2/modules/mod_python.so into server: The specified module could not be found. . The Apache service named reported the following error: Syntax error on line 173 of C:/Programs/Apache/Apache2/conf/httpd.conf: [Line 173 is "LoadModule python_module modules/mod_python.so"] ======================================== System log:. The Apache2 service terminated with service-specific error 1 (0x1). ======================================== My modules folder looks like this: Directory of C:\Programs\Apache\Apache2\modules 11/09/2003 21:48 <DIR> . 11/09/2003 21:48 <DIR> .. 08/07/2003 22:02 24?653 mod_access.so 08/07/2003 22:02 24?658 mod_actions.so 08/07/2003 22:02 24?656 mod_alias.so 08/07/2003 22:02 24?658 mod_asis.so 08/07/2003 22:02 24?651 mod_auth.so 08/07/2003 22:02 24?656 mod_auth_anon.so 08/07/2003 22:02 24?655 mod_auth_dbm.so 08/07/2003 22:02 32?850 mod_auth_digest.so 08/07/2003 22:02 32?857 mod_auth_ldap.so 08/07/2003 22:02 32?855 mod_autoindex.so 08/07/2003 22:02 28?757 mod_cache.so 08/07/2003 22:02 24?661 mod_cern_meta.so 08/07/2003 22:02 28?753 mod_cgi.so 08/07/2003 22:02 24?668 mod_charset_lite.so 08/07/2003 22:02 77?903 mod_dav.so 08/07/2003 22:02 45?136 mod_dav_fs.so 08/07/2003 22:02 57?426 mod_deflate.so 08/07/2003 22:02 24?654 mod_dir.so 08/07/2003 22:02 24?666 mod_disk_cache.so 08/07/2003 22:02 24?655 mod_env.so 08/07/2003 22:02 24?659 mod_expires.so 08/07/2003 22:02 28?757 mod_ext_filter.so 08/07/2003 22:02 24?659 mod_file_cache.so 08/07/2003 22:02 24?659 mod_headers.so 08/07/2003 22:02 28?751 mod_imap.so 08/07/2003 22:02 41?042 mod_include.so 08/07/2003 22:02 24?658 mod_info.so 08/07/2003 22:02 32?851 mod_isapi.so 08/07/2003 22:02 24?656 mod_logio.so 08/07/2003 22:02 28?757 mod_log_config.so 08/07/2003 22:02 24?665 mod_mem_cache.so 08/07/2003 22:02 28?748 mod_mime.so 08/07/2003 22:02 32?854 mod_mime_magic.so 08/07/2003 22:02 36?950 mod_negotiation.so 08/07/2003 22:02 41?038 mod_proxy.so 08/07/2003 22:02 20?566 mod_proxy_connect.so 08/07/2003 22:02 28?754 mod_proxy_ftp.so 08/07/2003 22:02 24?659 mod_proxy_http.so 14/03/2003 13:06 110?592 mod_python.so 08/07/2003 22:02 57?426 mod_rewrite.so 08/07/2003 22:02 24?660 mod_setenvif.so 08/07/2003 22:02 24?658 mod_speling.so 08/07/2003 22:02 28?756 mod_status.so 08/07/2003 22:02 24?661 mod_unique_id.so 08/07/2003 22:02 24?658 mod_userdir.so 08/07/2003 22:02 24?661 mod_usertrack.so 08/07/2003 22:02 24?662 mod_vhost_alias.so 08/07/2003 22:02 36?949 util_ldap.so 48 File(s) 1?535?794 bytes 2 Dir(s) 38?969?270?272 bytes free Regards, -PU From knightsofspamalot-factotum at gvdnet.dk Fri Sep 5 12:59:30 2003 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Fri, 05 Sep 2003 18:59:30 +0200 Subject: Selecting elements from a list References: <87y8x4w6ym.fsf@gvdnet.dk> <bj8f4v$8kl$1@newsg1.svr.pol.co.uk> <87brtzu5ak.fsf@gvdnet.dk> <bjabc7$mbm$1@newsg2.svr.pol.co.uk> Message-ID: <87znhjw4r1.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Duncan" == Duncan Smith <buzzard at urubu.freeserve.co.uk> writes: Duncan> Computer Science at Aalborg I see. A Bayes net man perchance? Duncan> I hope Uffe, Kristian et al are well. :-) Haha! If you're talking about the guys I'm thinking of, I just came home from a lovely Friday afternoon beer with them. :-) And yes, I happen to be doing a project involving Bayesian networks, but I'm originally a database guy. To keep it relevant, I did my masters thesis implementation stuff in Python and am very happy I did. Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) Comment: Using Mailcrypt+GnuPG <http://www.gnupg.org> iEYEARECAAYFAj9YwPIACgkQYu1fMmOQldWiCwCgr0YsGdB929LnDvpivNI3C6U/ KG0AoOeVKunYa0Ud/9UI/C99JaihY9bM =252w -----END PGP SIGNATURE----- From pweldon at mindspring.com Sat Sep 20 00:10:08 2003 From: pweldon at mindspring.com (Phil Weldon) Date: Sat, 20 Sep 2003 04:10:08 GMT Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> Message-ID: <AqQab.40174$NM1.1797@newsread2.news.atl.earthlink.net> Even faster is a look-up table with what, seventy entries? That would go up to an integer with 100 digits, probably more than any application would need, and certainly the fastest possible method. Phil Weldon, pweldon at minspring.com "Andrew Wilkinson" <ajw126 at NOSPAMyork.ac.uk> wrote in message news:3ee1fa98$0$45181$65c69314 at mercury.nildram.net... > Rogue9 wrote: > > > Pardon me but could anyone enlighten me if python2.2 has a math function > > to call to do factorials of integers?If not then is there a code snippet > > for doing such a thing available?I tried to write some code for this > > myself but with little success. > > Thanks > > Lol > > Hi, > > The other replies give a much more readable way of getting the factorial, > but if you're looking for the ultimate in speed then... > > def fac(n): > return reduce(long.__mul__, range(1,n+1), 1L) > > ..would probably be a bit quicker. I'm not sure how much quicker though. > > Anyway, hope this is of some use, > Regards, > Andrew Wilkinson From tzot at sil-tec.gr Tue Sep 16 18:24:20 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 17 Sep 2003 01:24:20 +0300 Subject: Tkinter: tooltips (Windows) References: <mailman.1063741374.30034.python-list@python.org> <%PK9b.13530$x21.9926@twister.southeast.rr.com> Message-ID: <js2fmv4a19aajopm5ph0he94uqj8btd5c7@4ax.com> On Tue, 16 Sep 2003 20:58:35 GMT, rumours say that "M-a-S" <NO-MAIL at hotmail.com> might have written: >I thought somebody might have already done it w/o Pwm, with Tkinter only. >Bad luck. Idle has tooltips, and it's Tkinter only. You already have the code; maybe ToolTip.py would be a good start :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From afriere at yahoo.co.uk Thu Sep 18 02:22:17 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 17 Sep 2003 23:22:17 -0700 Subject: Money data type References: <mailman.1063823424.16083.python-list@python.org> <38ec68a6.0309171738.3b3becda@posting.google.com> Message-ID: <38ec68a6.0309172222.689f0c7d@posting.google.com> afriere at yahoo.co.uk (Asun Friere) wrote in message news:<38ec68a6.0309171738.3b3becda at posting.google.com>... > > def __repr__ (self) : > return "$%.2f" % self Umm ...you might want to do the same to __str__ if you want to print ... :/ From ray at rays-web.com Thu Sep 18 05:43:57 2003 From: ray at rays-web.com (Ray Smith) Date: Thu, 18 Sep 2003 09:43:57 GMT Subject: DLL info In-Reply-To: <b03da24326888105a23a49b85f0660bb@news.meganetnews.com> References: <b03da24326888105a23a49b85f0660bb@news.meganetnews.com> Message-ID: <3f697e27@news.syd.ip.net.au> Ladv?nszky K?roly wrote: > Could someone suggest me how to gather various information (version number > etc.) from a Windows DLL? > Thanks for any help, > > K?roly Find the DLL in Windows Explorer, right click on the dll, and select properties. There should be a Version tab (I think ... haven't booted my Windows PC in awhile). For a utility to give you lots more info see: http://www.dependencywalker.com/ Ray Smith From bgporter at artlogic.com Thu Sep 11 20:40:07 2003 From: bgporter at artlogic.com (Brett g Porter) Date: Thu, 11 Sep 2003 20:40:07 -0400 Subject: Flash Remoting in Python? In-Reply-To: <2E78b.1002$8g2.829@news1.central.cox.net> References: <7712111.0309111357.3be3b591@posting.google.com> <2E78b.1002$8g2.829@news1.central.cox.net> Message-ID: <E5WcnXLOoPRMiPyiXTWJiQ@comcast.com> Dave Benjamin wrote: > > Another way to set up an RPC interface between Flash and Python would be to > use plain old HTTP GET/POST, with either urlencoded key-value pairs or WDDX > as a serialization format. (PyXML supports WDDX, as does PHP, as does Flash > if you Google around for the wddx.as script). > We've been using this XML-RPC library for Flash http://members.netmadeira.com/killer/xmlrpc/ ...and have found that it serves our needs just fine. From maxm at mxm.dk Wed Sep 24 02:14:05 2003 From: maxm at mxm.dk (Max M) Date: Wed, 24 Sep 2003 08:14:05 +0200 Subject: Fastest way to get thousands of db records to client in 3 tier? In-Reply-To: <Zr7cb.30579$uJ2.4877@fe3.columbus.rr.com> References: <Zr7cb.30579$uJ2.4877@fe3.columbus.rr.com> Message-ID: <3f71361f$0$97182$edfadb0f@dread12.news.tele.dk> R. Alan Monroe wrote: > I intend to write both client and server in Python, and my main goal > in the first cut is speed. Suggestions? Why do you need thousand of rows at the client? Normally you would get the results in batches, so that you only transfer at most a few hundred at a time to the client. I am not saying that you never need to do it. It's just rare. So perhaps all you need is a change in user-interface? Anyhoo you can reduce the number of queries/connections to get better speed. It is easy to inadvertently make queries like: for i in range(1000): "select * from table1 where some_number=i;" Instead of: "select * from table1 where some_number=<1000;" Normally it is not as simple as this, but the basic problem is the same. But if your problem is that you transfer the data over the wire in xml format and that is too slow, you need to use another format. XML conversion can have a lot of overhead. Especially if it is many thousand rows. Why not let the client ask directly if it is faster? But if you can bring down the number of rows, using xml might not be a problem at all. regards Max M From afriere at yahoo.co.uk Wed Sep 17 21:38:55 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 17 Sep 2003 18:38:55 -0700 Subject: Money data type References: <mailman.1063823424.16083.python-list@python.org> Message-ID: <38ec68a6.0309171738.3b3becda@posting.google.com> "Batista, Facundo" <FBatista at uniFON.com.ar> wrote in message news:<mailman.1063823424.16083.python-list at python.org>... > Can't find it. > > I mean something like: > > >> m1 = Money(decimal=2) > >> m2 = Money(decimal=2) > >> m1.value = 3.20 > >> m2.value = 2.15 > >> print m1 + m2 > 5.35 > > 5.35! Not 5.3500000000000001 neither 5.34999999999999999999. > > I think this is not a rare thing, but I can't find it in the standar library > neither the package index. > > Thanks! > > . Facundo If it's merely a matter of representing itself you could do something blindingly simple like: class Dollars (float) : def __repr__ (self) : return "$%.2f" % self def __add__ (self, other) : return Dollars(float.__add__(self, other)) #and so on for the other mathematical operators ... >>> a = Dollars(125.45) >>> a $125.45 >>> a + 25.6667 $151.12 >>> Note this is _not_ to your spec (ie output includes a currency symbol and input is simply a float). From javier_ruere at HotPOP.com Mon Sep 1 02:47:05 2003 From: javier_ruere at HotPOP.com (Javier Ruere) Date: Mon, 01 Sep 2003 03:47:05 -0300 Subject: My script is taking 12 hours+ any suggestions? In-Reply-To: <20030831220923.337050a0.jiba@tuxfamily.org> References: <3f4ff9f8$0$23588$5a62ac22@freenews.iinet.net.au> <20030831220923.337050a0.jiba@tuxfamily.org> Message-ID: <3F52EB69.1050708@HotPOP.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Jiba wrote: > If not, the solution is to use a rounded normal as key. E.g. use 'round(x * 100.0) / 100.0' instead of x for an (approximative) 0.01 precision, and proceed similarly with y and z. round can round to a given precition using the second optional argument so this two expressions would be equivalent: round(x*100)/100.0 == round(x, 2) Javier -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQE/Uuto8XQC840MeeoRAuLiAKCBBAAO4Q071hvfpa/m7NOi2Vq7AgCeOkLU 07hZL8F2ZzF2lyyZDRLHcZE= =upl+ -----END PGP SIGNATURE----- From bkc at Murkworks.com Fri Sep 26 14:33:33 2003 From: bkc at Murkworks.com (Brad Clements) Date: Fri, 26 Sep 2003 14:33:33 -0400 Subject: py2exe, 2.3 and services (raising flag again) Message-ID: <bl20pu$mt2$1@sea.gmane.org> Now that Thomas is back from vacation ;-) I cannot get the example service to work using Python 2.3 and the latest released py2exe (or the cvs version) on Win2k SP3. I can run the sample service .py file ok, but once it's inside a py2exe generated exe.. no working. The error in the event log is: The description for Event ID ( 240 ) in Source ( MyService ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. The following information is part of the event: 1063, The service process could not connect to the service controller.. I'm looking for a suggestion or two on how I can start debugging this problem. How do you debug py2exe generated .exe's? I have VC++ 6.0 -- Novell DeveloperNet Sysop #5 _ From max at fr.fm Wed Sep 17 04:32:02 2003 From: max at fr.fm (Maxime Biais) Date: Wed, 17 Sep 2003 10:32:02 +0200 Subject: replace %(word) in a string Message-ID: <20030917103202.0d90966a.max@fr.fm> Hello, I heard that is possible to replace %(word) in a string with a dictionary containing { "word" : "replaced word" } with a function or a builtin from the python library. For example with the string: "hello, %(word1) %(word2) !" and the dictionary: {"word1" : "python", "word2" : "lovers"} the final string would be: "hello python lovers" For the moment i use this code but i want something more pythonic: str: var_dic: for i in var_dic: myre = re.compile("(.*)(\%\(%s\))(.*)" % i, re.IGNORECASE) re_res = myre.match(str) if re_res: str = re_res.group(1) + var_dic[i] + re_res.group(3) -- Maxime Biais From p.useldinger at myrealbox.com Thu Sep 4 14:16:59 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Thu, 04 Sep 2003 20:16:59 +0200 Subject: OT: best book in years Message-ID: <opruzmelopdd8opo@news.vo.lu> Hi All, I am going to stay in hospital for a week or so (nothing serious), and am trying to find a book or two to read there. As I have not come across anything spectacular recently (except Python in a Nutshell), I would like to know what *you* consider to be the best book you have read in the last few years, about Python or IT in general. -Patrick From bgailer at alum.rpi.edu Mon Sep 8 10:13:06 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 08 Sep 2003 08:13:06 -0600 Subject: Read file that starts with '\xff\xfe' In-Reply-To: <Xns93F093815E0CDduncanrcpcouk@127.0.0.1> References: <bjgf10$d5s$0@216.39.172.122> <3F5BD4DD.57D90AF5@alcyone.com> <bjgs8l$6d0$0@216.39.172.122> <3F5BFC19.D098115B@alcyone.com> <6.0.0.22.0.20030908054530.03c42dd8@66.28.54.253> <3F5C7270.1020001@ghaering.de> <mailman.1063025195.15280.python-list@python.org> <Xns93F093815E0CDduncanrcpcouk@127.0.0.1> Message-ID: <6.0.0.22.0.20030908080938.03c3f110@66.28.54.253> At 07:31 AM 9/8/2003, Duncan Booth wrote: >Bob Gailer <bgailer at alum.rpi.edu> wrote in >news:mailman.1063025195.15280.python-list at python.org: > > > That's a good start. I presume I need to use codecs.open(filename, > > mode[, encoding[, errors[, buffering]]]) to read the file. What is the > > actual value of the "encoding[" parameter for "Little-endian UTF-16 > > Unicode character data, with CR line terminators" > >Try: > > myFile = codecs.open(filename, "r", "utf16") > >If the file starts with a UTF-16 marker (either little or big endian) it >will be read correctly. If it doesn't start with either marker reading from >it will throw a UnicodeError. Interesting error: UniCodeError: UTF-16 decoding error: truncated data Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From http Mon Sep 29 00:00:41 2003 From: http (Paul Rubin) Date: 28 Sep 2003 21:00:41 -0700 Subject: sendmsg operation on unix socket? Message-ID: <7xbrt41bx2.fsf@ruckus.brouhaha.com> I don't see the sendmsg operation in socket.py. Is it missing? I need to find the uid of a process sending messages to a unix domain socket. Is there another way to do that? Thanks. From peter at engcorp.com Thu Sep 4 17:09:09 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Sep 2003 17:09:09 -0400 Subject: OT: best book in years References: <opruzmelopdd8opo@news.vo.lu> <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> Message-ID: <3F57A9F5.F579219D@engcorp.com> "John J. Lee" wrote: > > Peter Hansen <peter at engcorp.com> writes: > [...] > > This sounds like a good opportunity to read "Zen and the Art of Motorcycle > > Maintenance" (by Robert Pirsig) if you have not already. It's certainly > > about IT, and ties into "The Zen of Python" (by Tim Peters) nicely, too. :-) > > Don't read it, it's a pile of junk. :-) IMNSHO. Are you trying to start the book-burning thread again? :-) -Peter From blunck at gst.com Wed Sep 17 00:33:21 2003 From: blunck at gst.com (Christopher Blunck) Date: Wed, 17 Sep 2003 00:33:21 -0400 Subject: Hurricane Isabel Message-ID: <pan.2003.09.17.04.33.20.657937@gst.com> This is shameless self promotion, so please discard it if you're offended. But if you're a geek maybe you'll read on . . . My family owns a house on the Outer Banks of North Carolina. On top of our house is a Davis Vantage Pro weather station. I have a daemon running every minute capturing weather data into a MySQL database. The data is exported to the world via a SOAP interface. I'm posting this because Hurricane Isabel is expected to make landfall within a day or two, and I thought there might be folks out there that would be interested in taking a look at up-to-the-minute weather conditions (well, at least until the power fails :)) The URL for my project page is: http://meta-tools.sf.net/wxnet There are installation instructions and screenshots available. It should be noted that the client I've written can also display buoy data from the National Weather Service. If you look cruise over to http://www.ndbc.noaa.gov/ you'll find the buoys current served. When launching the WeatherNet client, use a URL of the format: http://wxnet.dnsalias.com/buoys/number/number.wsdl For example, to look at buoy 41002 (250 NM east of Charleston SC), use: http://wxnet.dnsalias.com/buoys/41002/41002.wsdl It should be noted that this code is based off of ZSI and wouldn't be possible without Rich's code. Thanks Rich! :) -c From peter at engcorp.com Mon Sep 15 09:20:42 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Sep 2003 09:20:42 -0400 Subject: No "side effect" assignment! References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> <bk2okk$nrhg9$1@ID-139865.news.uni-berlin.de> <38ec68a6.0309142310.30c09f9f@posting.google.com> Message-ID: <3F65BCAA.EE8E2A45@engcorp.com> Asun Friere wrote: > > Dave Kuhlman wrote: > > while 1: > > foo = getmore() > > if not foo: > > break > > process(foo) > > I am alone in feeling some slight unease at the sight of "while 1: ... > break"? I know this is considered somewhat pythonic, but apart from > the fact that there is only a single assignment statement is there > really any advantage to be gained by doing it this way? It seems to > be trading one aesthetic disadvantage for another, and imho, a > marginally less legible one. There is a distinct advantage in the above, over the form with a duplicated line, and it's nothing to do with aesthetics. Sure, they both may be ugly to you (but they feel quite simple and thus elegant to some experienced Python programmers), but the real issue is that the one has the duplicated assignment and is therefore prone to maintenance problems. This fact alone far outweighs any aesthetic consideration, and wholly justifies the above form. If you are really offended, use a wrapper of some kind as others have shown. -Peter From __peter__ at web.de Mon Sep 22 04:49:33 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Sep 2003 10:49:33 +0200 Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale related?)) References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> <bkk4h1$9ke$06$1@news.t-online.com> <mailman.1064154389.29357.python-list@python.org> Message-ID: <bkmd4q$t13$05$1@news.t-online.com> Jeff Epler wrote: > If this did work, then you can use the DSU pattern like so: > > decorated_wordlist = [(locale.strxfrm(w), w) for w in wordlist] > decorated_wordlist.sort() > wordlist[:] = [i[1] for i in decorated_wordlist] Everytime that someone posts a naive list.sort(compare), the DSU pattern is proposed to improve execution speed. So maybe it's about time to change the sort() method to support a second argument list.sort(compare=None, mapping=None) that, if provided, would perform the DSU magic. Or was that already proposed and rejected? Peter From skip at pobox.com Mon Sep 1 12:33:18 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 1 Sep 2003 11:33:18 -0500 Subject: bsddb read-only requires rw access to close? In-Reply-To: <70df36e9.0308291220.527fcdfc@posting.google.com> References: <70df36e9.0308291220.527fcdfc@posting.google.com> Message-ID: <16211.29902.304243.811806@montanaro.dyndns.org> Harry> ... but if I change to read-only access (as in permissions on file): >>>> a = bsddb.btopen("c:/sharedrw/db/npanxx2pseudo.db", "r") >>>> a.close() Harry> Traceback (most recent call last): Harry> File "<pyshell#30>", line 1, in -toplevel- Harry> a.close() Harry> File "C:\Python23\lib\bsddb\__init__.py", line 101, in close Harry> v = self.db.close() Harry> DBPermissionsError: (1, 'Operation not permitted') Harry> Performing a close() with read/write access with file opened "r" does Harry> not change the last-modified time/date. Harry> Is this a bug? Dunno. Works for me on Mac OS X: % python Python 2.4a0 (#77, Aug 11 2003, 11:19:14) [GCC 3.1 20020420 (prerelease)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import bsddb >>> db = bsddb.btopen("foo.bt", "c") >>> db['1'] = '1' >>> db.close() >>> % chmod 444 foo.bt % python Python 2.4a0 (#77, Aug 11 2003, 11:19:14) [GCC 3.1 20020420 (prerelease)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import bsddb >>> db = bsddb.btopen("foo.bt", "r") >>> db.close() >>> Skip From jblazi at hotmail.com Tue Sep 30 01:49:43 2003 From: jblazi at hotmail.com (jblazi) Date: Tue, 30 Sep 2003 07:49:43 +0200 Subject: Using TCP/IP References: <pan.2003.09.29.19.19.26.610000@hotmail.com> <bmehnv49l8tm3qhtjjj3pe53q0ovd5t9kv@4ax.com> Message-ID: <pan.2003.09.30.05.49.41.657000@hotmail.com> On Tue, 30 Sep 2003 02:09:15 +0300, Christos "TZOTZIOY" Georgiou wrote: > import socket > socket.gethostbyname(socket.gethostname()) Thx. But this does not seem to work correctly. When I start the program and print the result, I get an IP-address but it is not the correct one i.e. not the one I am currently using. JB ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From jacek.generowicz at cern.ch Wed Sep 17 07:09:15 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Sep 2003 13:09:15 +0200 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> <mailman.1063223955.7295.python-list@python.org> Message-ID: <tyfhe3bllic.fsf@pcepsft001.cern.ch> Bob Gailer <bgailer at alum.rpi.edu> writes: > Also reminiscent (a long time ago) someone proposed a COME FROM > statement for FORTRAN to be the inverse of GO TO. http://c2.com/cgi/wiki?ComeFrom From python at sarcastic-horse.com Wed Sep 17 12:04:19 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Wed, 17 Sep 2003 12:04:19 -0400 (EDT) Subject: mx.DateTime bogus warning: "float where int expected" Message-ID: <33436.199.169.240.132.1063814659.squirrel@svr1.turboweb.net> Hi- I'm getting a "DeprecationWarning: integer argument expected, got float" warning with mx.DateTime and I can't figure out why. Can anyone help me out? This code: import mx.DateTime class xLabeller: def __init__(self, firstdate,fmt='%B, %Y'): self.firstdate = firstdate self.fmt = fmt self.mm = mx.DateTime.RelativeDateTime(months=1) def __call__(self, i): dt = self.firstdate + self.mm * int(i) return dt.Format(self.fmt) nov99 = mx.DateTime.Date(int(1999), int(11)) xl = xLabeller(nov99) print "xl2:" print xl(int(3)) Produces this warning: >>> ================================ RESTART =========== >>> xl2: C:\Python23\lib\site-packages\mx\DateTime\DateTime.py:585: DeprecationWarning: integer argument expected, got float return DateTime(year, month, 1) + \ February, 2000 What is the story? I've wrapped every number in my program with int(). I can't figure out what's triggering the warning. And, even stranger, the whole thing works fine at the python shell: >>> import mx.DateTime >>> mm = mx.DateTime.RelativeDateTime(months=1) >>> nov99 <DateTime object for '1999-11-01 00:00:00.00' at 98dc20> >>> dt = nov99 + mm * 3 >>> dt.Format('%b, %y') 'Feb, 00' >>> What am I doing wrong? Thanks for the help. From mark at hahnca.com Mon Sep 15 19:12:36 2003 From: mark at hahnca.com (Mark Hahn) Date: Mon, 15 Sep 2003 16:12:36 -0700 Subject: wanted($): mac and linux python gui coders for porting Message-ID: <EHr9b.36540$n94.18214@fed1read04> (I apologize in advance if this is not an appropriate posting) I have written a simple windows shareware app, EzPicMailer, in Python 2.3, wxPython 2.4.1, and PIL 1.1.4 that lets computer novices find photo files, edit them, and mail them, all in one simple app. Everyone is encouraged to check out my beta version at http://EzPicMailer.com. I wrote it to be cross-platform except for a small amout of windows code to do the system beep and to find the desktop and home folders. Now I need a Mac programmer and a Linux programmer to port to these environments for me. I'm new to shareware but I'm guessing that paying 10% of gross license receipts would be fair. I put in close to 200 hours into the app and I'm assuming that 20 hours to do a decent looking port would be about right, which gives 10% of the effort. Let me know if I'm off-base here. You will also be responsible for a second line of support for your platform. In other words you will need to fix problems particular to your platform to keep your royalty flow. You will not have to talk to customers though. That is what I mean by second-line. If you are interested, please tell me about yourself and point me to some of your existing work with GUI's. From fuerte at sci.fi Tue Sep 2 13:22:23 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Tue, 02 Sep 2003 20:22:23 +0300 Subject: Simple question: How to pass a C++ class reference to a callback? In-Reply-To: <aB-dnSBw_cewCsmiXTWJiw@comcast.com> References: <17fbc98a.0309020423.11ac7b8d@posting.google.com> <aB-dnSBw_cewCsmiXTWJiw@comcast.com> Message-ID: <lj45b.2298$ZB4.1613@reader1.news.jippii.net> I read it twice, but I'm not sure that I got it. You mean that I add something like: static PyObject* emb_Set(PyObject *self, PyObject *args) { char *key, *value; if(!PyArg_ParseTuple(args, "ss", &key, &value)) return NULL; // how the get the class instance pointer: PyObject *c_api_object = PyObject_GetAttrString(self, "_C_API"); if (c_api_object) { if (PyCObject_Check(c_api_object)) { myClass *p = (myClass *)PyCObject_AsVoidPtr(c_api_object); // do something with the C++ class here } Py_DECREF(c_api_object); } Py_INCREF(Py_None); return Py_None; } And in C++ class: Py_Initialize(); PyObject *m = Py_InitModule("test", EmbMethods); // ?? PyObject *c_api_object = PyCObject_FromVoidPtr((void *)this, NULL); if (c_api_object) { PyModule_AddObject(m, "_C_API", c_api_object); PyRun_SimpleString(script); } Py_Finalize(); T. Panbru wrote: > Try encapsulating your C++ class reference in a CObject, using: > > PyObject* PyCObject_FromVoidPtr( void* cobj, void (*destr)(void *)) > void* PyCObject_AsVoidPtr( PyObject* self) > > and so forth, to go back and forth between the C++ and Python realms. > > Check out the Python docs at: > > http://www.python.org/doc/2.3/api/cObjects.html > > Tim > > > Harri Pesonen wrote: > >> How do I pass the calling C++ class reference (or anything) to a >> callback? >> My code is: >> >> static PyObject* >> emb_Set(PyObject *self, PyObject *args) >> { >> char *key, *value; >> if(!PyArg_ParseTuple(args, "ss", &key, &value)) >> return NULL; >> // do something with the C++ class here >> // how the get the class instance pointer? >> Py_INCREF(Py_None); >> return Py_None; >> } >> >> static PyMethodDef EmbMethods[] = { >> {"Set", emb_Set, METH_VARARGS, "Sets the given variable."}, >> {NULL, NULL, 0, NULL} >> }; >> >> in C++ class: >> >> Py_Initialize(); >> Py_InitModule("test", EmbMethods); >> PyRun_SimpleString(script); >> Py_Finalize(); >> >> Harri > > From tjreedy at udel.edu Fri Sep 19 15:37:44 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Sep 2003 15:37:44 -0400 Subject: [OT] New Play: SPAMELOT References: <dnfmmv0n8evvu238thm96t3k2iff7dm33d@4ax.com> <mailman.1063997966.12324.python-list@python.org> Message-ID: <lOqdnaG8ttWUxvaiU-KYvQ@comcast.com> "Skip Montanaro" <skip at pobox.com> wrote in message news:mailman.1063997966.12324.python-list at python.org... > > Daniel> http://www.dailyllama.com/news/2003/llama206.html > > I particularly liked the last sentence: > > Casting for SPAMELOT will begin shortly. Run away. I nominate whoever sent me over a thousand fake MS Update + attachment spams in the last 24 hours. TJR From ods at strana.ru Tue Sep 30 12:15:10 2003 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 30 Sep 2003 20:15:10 +0400 (MSD) Subject: Inconsistent behavior of descriptors Message-ID: <Pine.LNX.4.44L.0309302000230.20282-100000@localhost.localdomain> I've noticed that the order of attribute lookup is inconsistent when descriptor is used. property instance takes precedence of instance attributes: >>> class A(object): ... def _get_attr(self): ... return self._attr ... attr = property(_get_attr) ... >>> a=A() >>> a.__dict__ {} >>> a.__dict__['attr']=1 >>> a.__dict__ {'attr': 1} >>> a.attr Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in _get_attr AttributeError: 'A' object has no attribute '_attr' But it doesn't when I use custom class of descriptor: >>> class descr(object): ... def __get__(self, inst, cls): ... return inst._attr ... >>> class B(object): ... attr = descr() ... >>> b=B() >>> b.__dict__ {} >>> b.__dict__['attr']=1 >>> b.__dict__ {'attr': 1} >>> b.attr 1 Subclasses of property behave like property itself: >>> class descr2(property): ... def __get__(self, inst, cls): ... return inst._attr ... >>> class C(object): ... attr = descr2() ... >>> c=C() >>> c.__dict__ {} >>> c.__dict__['attr']=1 >>> c.__dict__ {'attr': 1} >>> c.attr Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in __get__ AttributeError: 'C' object has no attribute '_attr' Is it an undocumented feature or I have to submit a bug report? -- Denis S. Otkidach http://www.python.ru/ [ru] From jallan at smrtytrek.com Fri Sep 26 17:01:31 2003 From: jallan at smrtytrek.com (jallan) Date: 26 Sep 2003 14:01:31 -0700 Subject: convert Unicode to lower/uppercase? References: <HBF.20030919jmx2@bombur.uio.no> <bkepb9$6a4$01$1@news.t-online.com> <299f1138.0309210940.32e9acfe@posting.google.com> <bkkusk$pvi$05$1@news.t-online.com> <bkm919$ast$01$1@news.t-online.com> <m3smmo5zx6.fsf@mira.informatik.hu-berlin.de> <299f1138.0309230818.22bc9bf6@posting.google.com> <m3fzinp4k0.fsf@mira.informatik.hu-berlin.de> <299f1138.0309251050.77c86735@posting.google.com> <JMIcb.122892$bo1.24537@news-server.bigpond.net.au> <wmJcb.122907$bo1.8337@news-server.bigpond.net.au> Message-ID: <299f1138.0309261301.3648c2f7@posting.google.com> "Neil Hodgson" <nhodgson at bigpond.net.au> wrote in message news:<wmJcb.122907$bo1.8337 at news-server.bigpond.net.au>... > Me: > > > for an illustrative but incorrect example > > "ca~non".upper() -> {'portugal':'CANON','spain':'CA~NON'}), > > For a real example from the Microsoft web site, uppercasing "indigo" > (u'\u0069\u006e\u0064\u0069\u0067\u006f') gives "INDIGO" > (u'\u0049\u004e\u0044\u0049\u0047\u004f') for English-US and similar but > with dots above the 'I's for Turkish: > (u'\u0130\u004e\u0044\u0130\u0047\u004f'). > The file http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt purportedly contains *all* casings for all scripts for all languages where the casings are not one-to-one or are otherwise not straightforward. The *only* locale oddities there are for Lithuanian and the two languages Turkish and Azeri and concern only dot/no-dot variants of the letters _i_, _I_, _j_, _J_ and no others. There are *no* other locale-based oddities. The mess is thankfully *very* limited in scope. In my opinion, if the full Unicode casing specification is to be followed, the most useful solution would be a parameter allowing the user to choose among (1) normal Latin casing, (2) Turkish/Azeri or (2) Lithuanian as the casing model for treatment of these letters. The default for the parameter would either be based on current locale or be normal Latin casing. I think the latter far better as it is dangerous to have functions in a language differ from machine to machine according to the current locale. Also, in case someone brings it up, it was formerly standard to generally omit diacritics on capital letters in Portuguese and in French (in France but not in Quebec!) This is no longer the norm for either language. See http://www.academie-francaise.fr/langue/questions.html#accentuation and http://www.press.uchicago.edu/Misc/Chicago/cmosfaq/cmosfaq.SpecialCharacters.html. I have seen academic style sheets with a silly rule that diacritics should be placed on capital letters as on lowercase letters except for the word "A". See http://www.alphaacademic.co.uk/fcs.htm and http://www.sagepub.com/journalManuscript.aspx?pid=9669&sc=1: << We use accents on capital letters, but capital A does not take a grave accent. >> It would not hurt to make a casing table customizable for such unusual styles. But that is beyond Unicode's specifications. A programmer who wishes odd customization beyond the norms of a language and Unicode specifications can do it through transformations outside of normal casing. Jim Allan From tjreedy at udel.edu Sat Sep 27 13:15:34 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2003 13:15:34 -0400 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> <IKScnUNBOsX4MumiU-KYgA@comcast.com> <bqeanvgel9ra3va44j090bmn2l126t340g@4ax.com> <10c662fe.0309270545.1fd5d839@posting.google.com> Message-ID: <7tidnd_LS5ElWOiiU-KYvQ@comcast.com> "Roberto A. F. De Almeida" <roberto at dealmeida.net> wrote in message news:10c662fe.0309270545.1fd5d839 at posting.google.com... > Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:<bqeanvgel9ra3va44j090bmn2l126t340g at 4ax.com>... > > That is, whether the single or multiple notation is used, and whether > > the slice objects are placed in a tuple or not, they are constructed > > from the tuple notation - the translation from notation to slice > > object should be done consistently. > > Yes, I believe I was not very clear. This is the inconsistency I was > talking about. (And this is with Python 2.3.1) As I pointed out in response to the same message, there is no inconsistency because the premise behind that conclusion is wrong. I also pointed out that you can make the premise true and get the consistency you expect by adding a comma after single slice expressions so that you do always use tuple notation. [me]> > >What you probably want is b[:-1][:-1], etc. Each index must be > > >separately bracketed to access items in list of lists (etc). > The problem with b[:-1][:-1] is that it will return b[:-1], and then > slice the result again. It's ok if you're working with lists, but not > for what I'm doing. ... > and request from the server only the data that will be used, and > return it as a Numeric array. Then you should, of course, use N.P.'s extended slicing syntax and I would expect all to work well. If you are doing something just similar, then you will have to do similar custom interpretation of slice tuples. Terry J. Reedy From skip at pobox.com Tue Sep 16 16:14:09 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 16 Sep 2003 15:14:09 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <3F67677E.9030408@sci.fi> References: <mailman.1063659502.2922.python-list@python.org> <tmH9b.79$2k.36@reader1.news.jippii.net> <16231.25317.741455.556170@montanaro.dyndns.org> <3F67677E.9030408@sci.fi> Message-ID: <16231.28433.221154.160576@montanaro.dyndns.org> >> Actually, it makes perfect sense. The reference count of Py_None is >> never supposed to reach zero. If that happens it's because you have >> a bug (too many Py_DECREFs or not enouch Py_INCREFs). Your version >> of none_dealloc silently masks the error. Harri> Yes, and there is no error if the reference count of Py_None Harri> reaches zero. The Py_None reference count has no meaning. Yes it does. If it goes to zero it means you have a bug in your code. Note that there are plenty of situations where you INCREF or DECREF objects not knowing (or caring) that the actual object you are messing with might be Py_None. If I happen to incompletely test a function defined (in C) something like: def myfunc(arg1, arg2, arg3=None): blah blah blah and have a reference count error in my code related to arg3 such that I erroneously DECREF it, but never test the three arg case, your version of none_dealloc() will silently miss the problem. The current none_dealloc() will rightfully complain if myfunc() is called enough times, because Py_None's reference count will go to zero. Harri> By changing the way how Py_None is freed (by doing nothing) Harri> Python would get simpler and faster. I think you're wrong. There are lots of places in the current code base where the INCREFs and DECREFs happen without concern for the actual object passed. There are at least some places where a check for Py_None would probably be warranted. In any case, I suspect that most INCREFs and DECREFs of Py_None actually happen when the interpreter doesn't realize that Py_None is being manipulated. By eliminating the few cases where you do know you're messing with Py_None you probably won't reduce the number of Py_INCREF and Py_DECREF calls substantially. Harri> How can you have negative reference counts? Answer: You Harri> can't. Yes you can. From Include/object.h: /* PyObject_HEAD defines the initial segment of every PyObject. */ #define PyObject_HEAD \ _PyObject_HEAD_EXTRA \ int ob_refcnt; \ struct _typeobject *ob_type; Note that ob_refcnt is defined as an int, not an unsigned int. I'm not sure if there are any ramifications to changing the type of that field. I don't have time to inspect the code at the level necessary to answer authoritatively. Harri> I think that you are completely missing the point of Python's Harri> reference counting. :-) The idea is that when the count reaches Harri> zero, then the object is deallocated. But if the object was never Harri> allocated in the first place, why deallocate it then? That's why Harri> having empty none_dealloc is beautiful. Except for the case where the reference counting has an error. Let me restate it this way: The C implementation of Python operationally defines a reference count of zero for a statically allocated object (not just Py_None) as a fatal error. That's as it should be, because any statically allocated object should have a reference count of at least one. Harri> I think that PyINCREF(Py_None) is ugly, and at least it is Harri> completely unnecessary. You're the person who keeps asking for it. Perhaps you should perform the tests. If it works, submit a patch to SF. If not, dig deeper and figure out why. Skip From claird at lairds.com Mon Sep 1 08:08:54 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 01 Sep 2003 12:08:54 -0000 Subject: Python Documentation? References: <LQydncwLlNp2UM-iXTWJkA@comcast.com> <3f530ea6$0$32489$edfadb0f@dread16.news.tele.dk> <Xns93E975FCE1E58godlarz@62.243.74.162> Message-ID: <vl6dmm8jutl140@corp.supernews.com> In article <Xns93E975FCE1E58godlarz at 62.243.74.162>, Larz <lp at your-pants-coder.dk> wrote: . . . >Dan and I are long time php programmers. One thing that is superb about >php, is it's online documentation that everyone in the community can >contribute to (not the actual documentation, just comments with >examples). > >Every since I first started using python, I've truly missed a >documentation source similar to that of PHP's. So Dan and I have started >our little project to make a documentation site in the spirit of that >documentation. . . . PHP's documentation has indeed been a great success as a collaborative adventure. Python already has a structure--and much content!--for comparable collaboration in <URL: http:// www.python.org/cgi-bin/moinmoin/ >. Moreover, as several follow-ups have explained, Python developers have differ- ent work practices than PHPers, and a different relation to documentation. In particular, it's hard to overempha- size how much working Python programmers depend on interactive introspection: use of the interpreter's built-in help, pydoc, and related facilities to discover and confirm details that, in PHPonia, are regarded as matters for online documentation. -- Cameron Laird <Cameron at Lairds.com> Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From alan.gauld at btinternet.com Thu Sep 4 16:53:49 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Sep 2003 20:53:49 GMT Subject: OT: best book in years References: <opruzmelopdd8opo@news.vo.lu> Message-ID: <3f57a537.423720477@news.blueyonder.co.uk> On Thu, 04 Sep 2003 20:16:59 +0200, Patrick Useldinger <p.useldinger at myrealbox.com> wrote: > to know what *you* consider to be the best book you have read in the last > few years, about Python or IT in general. IT Architectures and Middleware by Chris Broitton was a good read - but probably only if you are involvced in building big enterprise wide systems. I'm currently reading Robert Glass's book "Facts and Fallacies of Software Engineering" which is thought provoking and reminds us how little real progress we've made inthe last 30 years. And if you haven't already read it you owe it to yourself to read the "Structure & Interpretation of Computer Programs" (aka SICP and available online if you want a sample). Warning: It could change how you think about programming! And finally, I keep going back to Jon Bentley's "Programming Pearls" - I believe now available in a single volume. Words of wisdom on every page there. HTH, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Sep 25 13:40:25 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 25 Sep 2003 18:40:25 +0100 Subject: Pre-PEP: reverse iteration methods References: <HA5cb.185$kD3.168@nwrdny03.gnilink.net> <f4b2nv8vs81v6egonckq7935jmh6a8gku6@4ax.com> <2Udcb.1997$541.708@nwrdny02.gnilink.net> Message-ID: <he76nvoejeqqfs962cevspg9iafdv20e51@4ax.com> On Wed, 24 Sep 2003 09:57:18 GMT, "Raymond Hettinger" <vze4rx4y at verizon.net> wrote: >> Second, I'm not quite ready to drop my property idea ;-) >> >> An advantage is that the object returned by the property can sensibly >> support more than just iteration - e.g. slicing (as touched on in the >> PEP284 thread). So for instance... >> >> >>> x = range(10) >> >>> list(x.backward) >> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] > >I'm not clear on the details of what you're proposing. What is >type(x.backward)? Some made-up proxy class that understands that certain operations will work as if the list was reversed. For integer lists, I'd use much the same thing but on the set-of-all-integers object I proposed in the earlier thread. So I could write... for i in integers.backwards [:10] : print i ...to do the same as your... for i in xrange (10).iter_backwards () : print i ...though I'm also having this idea about using the 'int' type object to implement these again. It makes a certain sense for type names to also act as abstract sets of possible values. For typechecking purposes, for instance, it might be nice to be able to write... if x in float : do stuff with float value Of course that's a long way from compelling given that we already have the isinstance function, but what is attracting me is that these two ideas... 1. Provide objects (or extend the type name objects) to provide the abstraction of a set of values of that type, implementing whatever operations are practical and useful for that abstraction. 2. Provide properties of objects (including that abstract set of integers) which act as proxies for the object, but providing an modified view of that object (including a backward view of a sequence object, but possibly other things too). ...seem to provide, either alone or in combination, natural solutions to several problems. For instance, you don't just get the ability to loop through a range of integers backwards... for i in integers.ibackwards [:50] : But equally the ability to iterate through a sequence backwards... for i in x.ibackwards [:50] : And basically you are doing the same thing in each case - its just that the first example slices an abstract sequence as opposed to one that is physically held in memory. >Please show what a pure python version would look like >(taking UserList as an example). I didn't use UserList, but I did post example code in the "Comment on PEP-0322: Reverse Iteration Methods" thread. I wasn't so keen in that post, but I seem to like the idea again now. >> >* Should enumerate() be included? It would only provide reverse iteration >> > whenever the underlying sequence supported it. >> >> Why not... >> >> for i, j in enumerate (listname.iter_backwards ()) : >> >> in other words, as enumerate can handle the already-reversed >> sequence/iteration, I don't see the point. > >The point is that enumerate will starting numbering from zero >for the last item: Yes - I wasn't thinking straight, sorry about that. Just to put a thought in based on those two ideas above, though, how about... >>> x=["a", "b", "c"] >>> print x.enumerated [(0, "a"), (1, "b"), (2, "c")] >>> print x.backwards.enumerated [(0, "c"), (1, "b"), (2, "c")] >>> print x.enumerated.backwards [(2, "c"), (1, "b"), (0, "c")] 'enumerated' need not create the list or iterator immediately - again, it returns a proxy which implements the modified behaviour. Having a proxy to a proxy gives IMO quite a neat solution. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From Vincent.Raaijmakers at ge.com Thu Sep 18 08:24:52 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Thu, 18 Sep 2003 07:24:52 -0500 Subject: needs help in how to translate ≴ and ≵ Message-ID: <971323274247EB44B9A01D0A3B424C8501038028@FTWMLVEM02.e2k.ad.ge.com> Thanks! Vincent -----Original Message----- From: Jeff Epler [mailto:jepler at unpythonic.net] Sent: Wednesday, September 17, 2003 5:49 PM To: Raaijmakers, Vincent (IndSys, GE Interlogix) Cc: python-list at python.org Subject: Re: needs help in how to translate ≴ and ≵ &#NNNN; is an HTML "numeric character reference". See http://www.w3.org/TR/html4/charset.html#h-5.3.1 You can use Python to find the name of a particular Unicode character: >>> import unicodedata >>> unicodedata.name(unichr(8820)) 'NEITHER LESS-THAN NOR EQUIVALENT TO' On my terminal, I can display that character this way: >>> print unichr(8820).encode("utf-8") ? (I think that's a less-than symbol, "<" above an equivalent symbol (~) with a vertical bar through it, but I really can't tell in this font...) Jeff From gstaniak at inka.zagiel.pl Thu Sep 11 03:27:10 2003 From: gstaniak at inka.zagiel.pl (Grzegorz Staniak) Date: Thu, 11 Sep 2003 07:27:10 +0000 (UTC) Subject: OT: Americans love their guns References: <vkm8j0a086acd0@corp.supernews.com> <mailman.1061927168.7845.python-list@python.org> <c60rkvkpog2jabqkvbiaqnjm35vuf0iabk@4ax.com> <mailman.1062051665.5511.python-list@python.org> <l0nskvk7d2uptngokjl4al0bjqueielk2g@4ax.com> <mailman.1062103458.11215.python-list@python.org> <slrnblj40a.vc8.grey@dmiyu.org> <bjd8ov$93g$0@216.39.172.122> <slrnbllgu3.di8.grey@dmiyu.org> <m3k78j6v5e.fsf@tanelorn.bandersnatch.org> <vCu7b.201587$2x.57934@rwcrnsc52.ops.asp.att.net> <16223.15950.299463.959577@montanaro.dyndns.org> <mailman.1063251143.12678.python-list@python.org> Message-ID: <slrnbm08ud.d9.gstaniak@inka.zagiel.pl> Al Kirke writes: >> This sort of thing still happens (it hits the news whenever such a > shooting >> occurs), > > You're correct in that this sort of thing hits the news. What doesn't > hit the news are the instances when handguns are used for personal > defense. John Lott wrote a whole book about liberal news bias > aganst those instances. > > http://www.wmsa.net/people/john_lott/030822_bias_star.htm I think it's a mistake to cite Lott here. As an extreme libertarian he has shown his own bias a couple of times. His famous "More guns, less crime" findings has been challenged recently (see e.g. http://www.jointogether.org/gv/news/alerts/reader/0,2061,562387,00.html), and he could not produce any evidence whatsoever that his telephone survey on the crime-repelling effects of gun carrying has been actually conducted. [---] > But the biggest difference that household firearms make in > society is in the hot burglary statistics. Another one is that half of the burglars serving time in US prisons admit to have stolen a gun at least once. That means a lot of guns in the hands of criminals. [---] > A current judicial move concerns the 2nd Amendment. 5th > Circuit in New Orleans says its an individual right to keep > and bear arms, 9th Circuit in San Francisco (where else?) > says the right belongs to the national guard. This conflict > will reach the SCOTUS in the next year or so. It is a myth that the 2nd Amendment warrants "an individual right to keep and bear arms": http://www.bradycampaign.org/facts/issuebriefs/second.asp A well-regulated Militia being necessary to the security of a free State, the right of the people to keep and bear Arms, shall not be infringed." Pro-gun activists have made it a habit to omit the first, crucial part of the above sentence. Nonetheless, it is one of the well-established facts od the US constitutional law that gun-restricting laws are NOT in conflict with the 2nd Amendment. Actually, AFAIR no such law has ever been overturned on constitutional grounds. > Al -- Grzegorz Staniak <gstaniak at zagiel.com.pl> From bgailer at alum.rpi.edu Wed Sep 3 13:38:19 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 03 Sep 2003 11:38:19 -0600 Subject: Polymorphism the Python way In-Reply-To: <bj56nu$f3gk1$1@ID-130333.news.uni-berlin.de> References: <smr2lvop984g1k1q30iidmm0lg8uecolqa@4ax.com> <bis8k4$sjv$00$1@news.t-online.com> <m349lvgot9ghsmii9b85uoq34qfhbho8jq@4ax.com> <js99lvguv5vdvmmjfpdmgmo5dnq5akttfb@news.stofanet.dk> <3f550e2f.254030105@news.blueyonder.co.uk> <tyfbru1swzd.fsf@pcepsft001.cern.ch> Message-ID: <5.2.1.1.0.20030903113537.02fbfad0@66.28.54.253> At 10:04 AM 9/3/2003 -0700, Cousin Stanley wrote: >| ... >} I don't think that it has changed its meaning; >| most people just use the term incorrectly. >| ... > > Add to these the OFTEN confused terms > accuracy and precision ... Precisely what I was thinking. I looked at a digital thermometer in Radio Shack. It had been in the store long enough to stabilize. It showed indoor and outdoor temperatures to a precision of 0.1 degree. The indoor and outdoor readings differed by about a degree. So now we know the accuracy, and the precision was therefore worthless. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From tim.one at comcast.net Fri Sep 19 18:39:52 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 19 Sep 2003 18:39:52 -0400 Subject: [OT] New Play: SPAMELOT In-Reply-To: <3F6B7FE7.445FB3BF@alcyone.com> Message-ID: <LNBBLJKPBEHFEDALKOLCIECEGAAB.tim.one@comcast.net> [Erik Max Francis] > ... > The problem with this latest round of worm spam isn't that it's > bypassing filters (I just have some reasonably sane filtering > rules in my system, certainly nothing customized to this latest worm > attack -- I don't even really know which rules are stopping it), it's > putting significant loads on mail servers. Unfortunately, running an > intensive, per-user customized spam filtering solution like Spambayes > _increases_ that load. SpamBayes was designed to run client-side, although a few people have made it part of server-side systems. Most users' PCs sit idle most of the time. Greg Ward made the most impressive server-side use of SpamBayes that I know of to date, to filter the Python and Zope mailing lists run via python.org. There's no per-user customization in those, and it isn't needed because a tech mailing list has a natural shared focus. Greg did set up several distinct classifiers for different groups of mailing lists. SpamBayes isn't notably intensive, either. One of the reasons Greg moved the python.org mailing lists to SpamBayes filtering is that it runs much faster than SpamAssassin (which python.org used to use). The biggest drains caused by worm spew are on bandwidth and disk space. Filters don't add to the former unless they do lookups over the net (SpamBayes does not), and a very effective SpamBayes classifier can fit entirely in a small corner of a typical server's RAM. not-bothering-to-refute-that-the-sky-is-pink<wink>-ly y'rs - tim From exarkun at intarweb.us Mon Sep 1 16:42:23 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 1 Sep 2003 16:42:23 -0400 Subject: TKinter is driving me crazy! In-Reply-To: <3285.208.224.10.29.1062445601.squirrel@webmail.iserv.net> References: <3285.208.224.10.29.1062445601.squirrel@webmail.iserv.net> Message-ID: <20030901204223.GB10824@intarweb.us> On Mon, Sep 01, 2003 at 03:46:41PM -0400, tjland at iserv.net wrote: > Okay now im pretty sure this is really easy and pretty stupid but i need > to create this. To make it simple ill use another program as an example. A > guessing game that has an input field and button and an output field that > can display w/e. I know this is really easy in c++ but it needs ot be done > in python. Can anyone start me off here or give me a skeleton structure on > this is supposed to be arranged. Thanx in advance. > Just off the top of my head... import Tkinter as tk class GuessWidget(tk.Frame): def __init__(self, value, *args, **kw): tk.Frame.__init__(self, *args, **kw) input = tk.Frame(self) tk.Label(input, text="Guess").pack(anchor=tk.W) self.input = tk.Entry(input) self.input.bind('<Return>', self.got_input) self.input.pack(anchor=tk.W) input.pack(anchor=tk.N) self.output = tk.Label(self) self.output.pack(anchor=tk.N) self.pack() self.value = value def got_input(self, event): v = int(self.input.get()) if v < self.value: self.output.config(text="Too low!") elif v > self.value: self.output.config(text="Too high!") else: self.output.config(text="You got it!") if __name__ == '__main__': GuessWidget(random.randrange(100)).mainloop() Jp -- "I quite agree with you," said the Duchess; "and the moral of that is -- Be what you would seem to be' -- or, if you'd like it put more simply -- Never imagine yourself not to be otherwise than what it might appear to others that what you were or might have been was not otherwise than what you had been would have appeared to them to be otherwise.'" -- Lewis Carrol, "Alice in Wonderland" From dave at boost-consulting.com Fri Sep 26 20:46:17 2003 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 26 Sep 2003 20:46:17 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <wCGcb.3064$yU5.2141@nwrdny01.gnilink.net> <8RScb.169633$R32.5449258@news2.tin.it> <uk77vhagj.fsf@boost-consulting.com> <WNYcb.12686$yD1.1505440@news20.bellglobal.com> <eppstein-B529F3.09181826092003@news.service.uci.edu> <dJ_cb.13620$yD1.1517951@news20.bellglobal.com> <eppstein-AF4213.10592426092003@news.service.uci.edu> <5L%cb.13662$yD1.1524835@news20.bellglobal.com> Message-ID: <ullsb9hye.fsf@boost-consulting.com> "Sean Ross" <sross at connectmail.carleton.ca> writes: > "David Eppstein" <eppstein at ics.uci.edu> wrote in message > news:eppstein-AF4213.10592426092003 at news.service.uci.edu... >> Your proposed name has an implication for the semantics. > > Do the implied semantics of ireverse() differ from those implied by the > names iter_backwards(), reverse_view(), riter(), etc.? > Because, to me, they' re just different words for the same idea. Well, the only other place we have an 'i' prefix on a function name, AFAIK, it means "inplace". I don't mind riter(); it has a nice resonance with rbegin() in C++. -- Dave Abrahams Boost Consulting www.boost-consulting.com From http Wed Sep 10 15:54:47 2003 From: http (Paul Rubin) Date: 10 Sep 2003 12:54:47 -0700 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> Message-ID: <7xad9cwha0.fsf@ruckus.brouhaha.com> achrist at easystreet.com writes: > The yield statement looks to be a big step toward some kind of > lightweight concurrency-oriented programming in python. Is there > any similarly nice way to do the opposite of yield, just sit around > (perhaps in the middle of a loop) and wait until some other routine > (unknown to the waiting module) hurls a value in? > > If this is not implemented now, is there any chance that it's on the > list of things to come? Not much chance. Even Stackless can't do that any more, if I understand correctly. From peter at engcorp.com Thu Sep 4 16:21:02 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Sep 2003 16:21:02 -0400 Subject: Open Source leader? (was Re: Celebrity advice) References: <mailman.1062702112.16151.python-list@python.org> Message-ID: <3F579EAE.4CC9D5EC@engcorp.com> Arthur wrote: > > > aahz at pythoncraft.com (Aahz) writes: > > > > > In article <Kv-cnVDMbb1qmdOiRTvUqg at speakeasy.net>, > > [...] > > > OTOH, Perens is also (like me ;-) a self-described asshole. When I saw > > > him at the Waterside Conference earlier this year, he basically claimed > > > that only assholes could make significant progress in the Open Source > > > community. > > [...] > > > > ahaz, is of course, being an opportunist. > > The record will show that I am the first here to have made claim - in just > those words - of being a self-described asshole. > > And heard no objection to the categorization. > > which, it now seems, puts me in charge ; Come on guys, no fighting! Would it help if we all just agreed that you're both a couple of assholes and get it over with? ;-) -Peter From jblazi at hotmail.com Sun Sep 21 02:55:08 2003 From: jblazi at hotmail.com (jblazi) Date: Sun, 21 Sep 2003 08:55:08 +0200 Subject: Problems with string and lists (searching and replaceing) References: <pan.2003.09.20.10.51.37.875000@hotmail.com> <bkhnpn$hgc$1@news.hccnet.nl> <bki8jq$269us$1@ID-167393.news.uni-berlin.de> <bkigtt$9jr$0@216.39.172.122> <bkim08$f8i$1@news.hccnet.nl> Message-ID: <pan.2003.09.21.06.55.07.16000@hotmail.com> I shall have a computer science class this year and I decided to use Python. It is my favourite language and I have used it for many years. Now I thought, one of our first "real" programs, in our pre-graphical and pre-class state, would be to write simple program that works like this: One of the pupils enters a word. It should be a valid German word consisting of five letters, for example 'abcde' (which is not a German word by the way). The the other player may enter a guess which must be a five letter word as well, for example 'xbxxx'. Then the system answers with the string '-*---' as the 'b' in 'xbxxx' was correct and at the right place as well. Had the second player entered 'xxxbx', the system had responded with '---.-', as the 'b' is correct but not correctly positioned. The second player must find out the original word. Now I did not see how to do it as simply as posible, that was the problem. JB ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From adalke at mindspring.com Fri Sep 26 22:24:30 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 27 Sep 2003 02:24:30 GMT Subject: [2.2.1]How To Gracefully Shutdown an XML-RPC Server References: <a38d43b0.0309261712.540f96da@posting.google.com> Message-ID: <yx6db.4829$RW4.3093@newsread4.news.pas.earthlink.net> The Jetman: > I'm reading source code, but I haven't found any examples of > how to simply shutdown my XML-RPC server. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114579 Or you can ungracefully use os._exit, like pulling the emergency brake on a train. Andrew dalke at dalkescientific.com From grante at visi.com Fri Sep 5 17:34:05 2003 From: grante at visi.com (Grant Edwards) Date: 05 Sep 2003 21:34:05 GMT Subject: Why the 'self' argument? References: <slrnblh5ru.nd5.gstaniak@inka.zagiel.pl> <vlh7otscuo8gb1@news.supernews.com> <3f58a2bd$0$156$a1866201@newsreader.visi.com> <vlhba85atlte07@news.supernews.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <vlhidvcpq9a980@news.supernews.com> <qpOW/ks/KnRV089yn@the-wire.com> <vlhtm1bmc7m295@news.supernews.com> Message-ID: <3f59014d$0$152$a1866201@newsreader.visi.com> In article <vlhtm1bmc7m295 at news.supernews.com>, John Roth wrote: >> There's no difference in the sense that a method is simply a >> function whose first parameter refers to the class instance to >> be worked on. No magic words, no "undeclared" parameters. It >> means that in my demo code in limitcases.py (somewhere in the >> newsgroup lately) I can say >> >> limitcases.Lowest.__str__ = lambda x: "-Infinity" >> >> to give the Lowest class a new method sans ennuis. > > But why do it that way? So that there's no difference between a function and a method. Simplicity and orthogonality are good things -- despite what C++ proponents thing. > Neither Java nor Ruby require giving the instance a name. So? Personally I don't like invisible, implied, automatic stuff like that. Can't stand automatic transmissions either -- the damn things have no idea what's ahead, and always seem to be in the wrong gear at critical moments. > Hence my comment that requiring it is more complex than not > requiring it. No, it's more complex the Java/Ruby way, since you have to have two sets of rules for what a name means depending on whether you're inside a "normal" function or a method. In Python there's just one set of rules -- mostly. I have enough trouble remembering how the stuff I design works. ;) I don't want to have to keep track of more scoping/name-space rules than absolutely necessary. -- Grant Edwards grante Yow! Intra-mural sports at results are filtering visi.com through th' plumbing... From FBatista at uniFON.com.ar Mon Sep 22 14:46:41 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 22 Sep 2003 15:46:41 -0300 Subject: Memory allocation Message-ID: <A128D751272CD411BC9200508BC2194D03382FD2@escpl.tcp.com.ar> #- Can you provide more background on the specific problem you need #- to solve, or are you looking for a very general solution? In #- other words, do you just need to know how much memory a list, or #- an integer uses up, or do you think you need a general-purpose #- function which works with any object of any type. It's a very general question for a very particular problem, :) My particular problem is that I want to store in memory a pickled object, and then want to know if that object changed. For example (code untested): class ObjectControl: """ Class to control if an object changed. """ def __init__(self, object): objectPickled = cPickle.dumps(object) return def objectChanged(self, newObject): newObjectPickled = cPickle.dumps(newObject) if newObjectPickled == self.objectPickled: return False else: return True so.... object1 = pickle.load(myfile) control1 = ObjectControl(object1) ... #lot of stuff that could change my object ... #write to disk only if necessary if control1.objectChanged(object1): pickle.dump(myfile, object1) Don't know if there's a better solution for this particular problem (suggestions welcomed), but it still remains a general question: the other day I wanted to know "how much more expensive in memory is a list than a tuple for a given content". Get my idea? Thanks for all! . Facundo From nav+posts at bandersnatch.org Thu Sep 11 14:57:28 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 11 Sep 2003 14:57:28 -0400 Subject: OT: Americans love their guns References: <vkm8j0a086acd0@corp.supernews.com> <mailman.1061927168.7845.python-list@python.org> <c60rkvkpog2jabqkvbiaqnjm35vuf0iabk@4ax.com> <mailman.1062051665.5511.python-list@python.org> <l0nskvk7d2uptngokjl4al0bjqueielk2g@4ax.com> <mailman.1062103458.11215.python-list@python.org> <slrnblj40a.vc8.grey@dmiyu.org> <bjd8ov$93g$0@216.39.172.122> <slrnbllgu3.di8.grey@dmiyu.org> <m3k78j6v5e.fsf@tanelorn.bandersnatch.org> <vCu7b.201587$2x.57934@rwcrnsc52.ops.asp.att.net> <16223.15950.299463.959577@montanaro.dyndns.org> <000b01c37824$c972de10$3a0ff10c@teaset> <mailman.1063290822.30564.python-list@python.org> <bjq4hq$3or$1@news1.wdf.sap-ag.de> Message-ID: <m3znhb40h3.fsf@tanelorn.bandersnatch.org> Skip Montanaro wrote: > > Why is this on c.l.py anyway? "Daniel Dittmar" <daniel.dittmar at sap.com> writes: > Wasn't 'gun' just an allegory for using Perl? +1 QOTW. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From tzot at sil-tec.gr Wed Sep 24 13:22:44 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 24 Sep 2003 20:22:44 +0300 Subject: 64-bit EPIC and some modules References: <nsd3nv40ifcur0clp7ful66qohveos0o9r@4ax.com> <7h3smmm2m0w.fsf@pc150.maths.bris.ac.uk> Message-ID: <0ck3nvoicm45kb0oon2etsucttatc3aob7@4ax.com> On Wed, 24 Sep 2003 16:28:25 GMT, rumours say that Michael Hudson <mwh at python.net> might have written: >I may be wrong, but I thought that audioop and imageop only work in a >32 bit environment. I found an old post by Guido (1998) asking for testers in 64-bit environments; it seems that the work he did then (and perhaps some later work by him or others) gave fruit. I checked the source (of audioop at least), and there are some #ifdef code at the start of it, assuring the type used in calculations is 4 bytes long. The tests ran fine! :) Guido's post: http://groups.google.com/groups?selm=199804232038.QAA05368%40eric.CNRI.Reston.Va.US -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From P at draigBrady.com Tue Sep 9 05:22:11 2003 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 09 Sep 2003 10:22:11 +0100 Subject: PyGTK and fonts In-Reply-To: <f5c5dc88.0309081934.76f17ec2@posting.google.com> References: <f5c5dc88.0309081934.76f17ec2@posting.google.com> Message-ID: <3F5D9BC3.2040101@draigBrady.com> Tad Marko wrote: > Howdy! > > I'm pretty new to both Python and PyGTK (about 10 hours at this > point), so please forgive me if this question has already been > answered somewhere. Basically, I've got a small program with a > GtkTextView and I'd like to change the font to a monospaced font. > Preferably the default monspace font for Gnome 2. Can anyone show me > the steps necessary to programatically change the font on the text > view? > > Thanks for any help! Hi, I found these were required reading for using pygtk FAQ: http://www.async.com.br/faq/pygtk/index.py?req=all Tut: http://www.moeraki.com/pygtktutorial/pygtk2tutorial/index.html Ref: http://www.moeraki.com/pygtkreference/pygtk2reference/ Note pygtk has just in the last few days reached version 2. Also note that mandrake 9.2 will include it by default Here is a useful search for existing mandrake and suse users: http://rpm.pbone.net/index.php3?stat=3&srodzaj=1&search=pygtk2%2A&dl=40&dist[]=13&dist[]=19&field[]=1&field[]=2 P?draig. From henk at entree.nl Mon Sep 22 11:42:45 2003 From: henk at entree.nl (Henk Punt) Date: 22 Sep 2003 08:42:45 -0700 Subject: Access to Win API References: <d541d61d12758a2b45ea1de78809beac@news.meganetnews.com> <mailman.1063964485.26108.python-list@python.org> <0c58d500ac94b27d7f8ff87a2a59f6e1@news.meganetnews.com> <mailman.1063973126.25678.python-list@python.org> Message-ID: <5a6dd3ff.0309220742.402b7a07@posting.google.com> And if you are going to write a GUI app for windows with ctypes, you might want to check out: http://venster.sourceforge.net/ It already contains a lot of usefull stuff for windows GUI programming. Henk. Gerhard H?ring <gh at ghaering.de> wrote in message news:<mailman.1063973126.25678.python-list at python.org>... > Ladv nszky K roly wrote: > > Thanks for your help. I remember once I tried a Python cookbook sample > code > > that included ctypes but now 'import ctypes' does not work. > > Should ctypes come together with the 2.3 installation? > > It's available here: http://sourceforge.net/projects/ctypes > > -- Gerhard From CousinStanley at hotmail.com Wed Sep 3 10:51:57 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 3 Sep 2003 07:51:57 -0700 Subject: wxGrid? References: <3f55f478$1@news.comindico.com.au> Message-ID: <bj4uur$f9lej$1@ID-130333.news.uni-berlin.de> Tom ... I was able to run your script by adding two lines ... from wxPython.grid import * and grid.CreateGrid( 3 , 2 ) Cousin Stanley ----------------------------------------------------------- ''' NewsGroup .... comp.lang.python Date ......... 2003-09-03 Posted_By .... Tom Lee Edited_By .... Stanley C. Kitching ''' from wxPython.wx import * from wxPython.grid import * class TestFrame( wxFrame ) : def __init__( self ) : wxFrame.__init__( self , None, -1 , 'TestGrid' , size = ( 430 , 185 ) ) grid = wxGrid( self, -1 ) grid.CreateGrid( 3 , 2 ) grid.AppendCols( 2 ) grid.AppendRows( 3 ) grid.SetCellValue( 0 , 0 , 'Testing' ) self.Show( True ) class TestApp( wxApp ) : def OnInit( self ) : frame = TestFrame() self.SetTopWindow( frame ) return True if __name__ == '__main__' : app = TestApp( 0 ) app.MainLoop() From claird at lairds.com Thu Sep 4 13:37:55 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 04 Sep 2003 17:37:55 -0000 Subject: Drag and drop in Tkinter. How difficult is it? References: <ApGdnUgAC6p1AMuiU-KYuA@comcast.com> <vle0j01npmca27@corp.supernews.com> <qeselv8j6tgsg151ig4v55jdq5pmvbvfmk@4ax.com> Message-ID: <vleu3j62pt564e@corp.supernews.com> In article <qeselv8j6tgsg151ig4v55jdq5pmvbvfmk at 4ax.com>, Christos "TZOTZIOY" Georgiou <tzot at sil-tec.gr> wrote: . . . >I should add that drag and drop in the same application can be done >easily, but it's hard to do it between your application and others (too >much window manager dependencies...) . . . Absolutely. My guess is that the original questioner did *not* have inter-application drag-and-drop in mind, at least not ini- tially. Those who want to pursue the subject might find the references at <URL: http://wiki.tcl.tk/DragAndDrop > helpful. -- Cameron Laird <Cameron at Lairds.com> Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From andymac at bullseye.apana.org.au Sat Sep 20 06:51:14 2003 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 20 Sep 2003 20:51:14 +1000 (EST) Subject: "tuple index out of range" side effect of C extension?? In-Reply-To: <LNBBLJKPBEHFEDALKOLCAEJBFPAB.tim.one@comcast.net> References: <LNBBLJKPBEHFEDALKOLCAEJBFPAB.tim.one@comcast.net> Message-ID: <20030920204751.P33392@bullseye.apana.org.au> [I replied to Tim privately; this response for the archives] On Thu, 18 Sep 2003, Tim Peters wrote: > [Andrew MacIntyre] > > I'm seeing a bizarre situation where IndexErrors are being thrown with > > "tuple index out of range" error strings. > > > > The scenario is something like: > > > > l = [(v1a, v1b), (v2a, v2b), ..., (vna, vnb)] > > > > for a, b in l: > > ... > > > > > > > > with the IndexError being thrown on the "for..." line after the last > > element of l has been through the for loop. > > > > I've also seen the same exception thrown on first access to an > > attribute of a simple class. > > > > The exception being thrown is not consistent, > > It's probably the case then that C code is setting an exception in a > function F but neglecting to make F return its "there's an error" return > value. The most common way this happens is for an extension module to call > a Python C API function and neglect to check *it* for an error return value. > In general, every Python C API function call must be checked for an error > return, and, when one occurs, the calling function must either return an > error code itself, or explicitly clear the error. > > If an error return isn't made, ceval.c (the interpreter's main loop) doesn't > know an exception is pending, and not all bytecodes check for a pending > exception. The exception doesn't get triggered then until the interpreter > happens to execute a bytecode that does check for a pending exception. The > original C code that set the exception is long gone at that point, and the > reported exception doesn't appear to make sense. Tim's diagnosis was accurate - many thanks! Regards, Andrew. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From anthony at interlink.com.au Thu Sep 11 01:44:49 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 11 Sep 2003 15:44:49 +1000 Subject: TTF fonts rendered in Python In-Reply-To: <pan.2003.09.10.22.42.45.569436@webone.com.au> References: <pan.2003.09.10.22.42.45.569436@webone.com.au> <mailman.1063224795.24414.python-list@python.org> Message-ID: <200309110544.h8B5inYu010107@localhost.localdomain> >>> Simon Burton wrote > > One idea: > pygame can render with TTF fonts, > it can also save surfaces in tga format. > Then use PIL to convert to gif. The only > question is, can pygame do this without displaying > a window etc. Absolutely - I have code here that generates animated gifs doing just this sort of thing. Anthony -- Anthony Baxter <anthony at interlink.com.au> It's never too late to have a happy childhood. From martin at v.loewis.de Wed Sep 3 01:12:07 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 03 Sep 2003 07:12:07 +0200 Subject: Location of bytecode files (pyc) References: <6f03c4a5.0309021745.3a79d951@posting.google.com> Message-ID: <m3ekyyjw0o.fsf@mira.informatik.hu-berlin.de> rimbalaya at yahoo.com (Rim) writes: > How can I control the location of the bytecode files? You currently can't. See PEP 304, though, at http://www.python.org/peps/pep-0304.html Comments on the PEP are encouraged: If you won't comment now on whether the proposed change would solve your problem, it might be that you find something useless got implemented later. Regards, Martin From duncan at NOSPAMrcp.co.uk Tue Sep 30 04:46:15 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 30 Sep 2003 08:46:15 +0000 (UTC) Subject: Question: Inheritance from a buil-in type References: <3F7848C6.8070306@snafu.de> <Xns9405A01F17467duncanrcpcouk@127.0.0.1> <38ec68a6.0309300022.3c8e3304@posting.google.com> Message-ID: <Xns940661D24ABC2duncanrcpcouk@127.0.0.1> afriere at yahoo.co.uk (Asun Friere) wrote in news:38ec68a6.0309300022.3c8e3304 at posting.google.com: > Duncan Booth <duncan at NOSPAMrcp.co.uk> wrote in message > news:<Xns9405A01F17467duncanrcpcouk at 127.0.0.1>... > >> >> There are two rules. Generally, immutable objects get their initial >> values from the constructor (__new__) while mutable objects are >> constructed with a default value (e.g. empty list or dict) and are >> then set by the initialiser (__init__) method. A few types which you >> might expect to be immutable are actually mutable (e.g. property). >> > > What is the thinking behind that? I mean you /can/ pass initial values > to a mutable using __new__, eg > > class MyList (list) : > def __new__(cls, *args, **kwargs) : > return list.__new__(cls, *args, **kwargs) > > or __init__ to pass values to a newly created immutable, eg > > class MyTuple (tuple) : > def __init__(self, *args, **kwargs) : > return super(tuple, self).__init__(*args, **kwargs) > > can't you? What's the pitfall? > The pitfall is that these aren't doing what you think. In both cases you just passed the original arguments straight through, so the list also got the arguments it expected in its __init__ method, and the tuple got its expected arguments in __new__. If you modify the arguments in any way you'll find that your code still only sees the original arguments. list.__init__ and tuple.__new__ act on their arguments. list.__new__ and tuple.__init__ ignore their arguments. Take the tuple example. tuple() takes 0 or 1 arguments, so you can't write: tuple(1, 2, 3) So define a class to do this: >>> class MyTuple(tuple): def __new__(cls, *args): return tuple.__new__(cls, args) >>> MyTuple(1, 2, 3) (1, 2, 3) Now try this with __init__ and the default __new__ will complain: >>> class MyTuple(tuple): def __init__(self, *args): tuple.__init__(self, args) >>> MyTuple(1, 2, 3) Traceback (most recent call last): File "<pyshell#73>", line 1, in ? MyTuple(1, 2, 3) TypeError: tuple() takes at most 1 argument (3 given) If you try subclassing list, then this example shows clearly that the arguments to __new__ are actually ignored: >>> class MyList (list) : def __new__(cls, *args, **kwargs) : return list.__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): print "list before init",self list.__init__(self, *args, **kwargs) >>> print MyList([1, 2, 3]) list before init [] [1, 2, 3] -- 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 samschul at pacbell.net Sat Sep 27 17:41:46 2003 From: samschul at pacbell.net (Samuel Schulenburg) Date: 27 Sep 2003 14:41:46 -0700 Subject: FTP access to starship.python.net? Message-ID: <d7fcf8b4.0309271341.72304331@posting.google.com> Who should I contact about accessing my account on Starship. I need to obtain a new password and access process. I think i am having a memory lapse as it has been over a year sense I have had a need to access my files. Sam Schulenburg From sholden at holdenweb.com Mon Sep 15 19:12:14 2003 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 15 Sep 2003 23:12:14 GMT Subject: compound conditional statements References: <3064b51d.0309151331.76f1d658@posting.google.com> Message-ID: <iHr9b.7534$3Y2.5410@news2.central.cox.net> <beliavsky at aol.com> wrote ... > If I have code > > if (aa or bb): print "true", > > does Python evaluate aa and bb in any particular order? Can I assume that if > aa is true, bb will not be evaluated? Yes. Both "and" and "or" are specifcally short-circuiting. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From peterm at resmed.com.au Mon Sep 29 00:07:14 2003 From: peterm at resmed.com.au (Peter Milliken) Date: Mon, 29 Sep 2003 14:07:14 +1000 Subject: IDE with a specific feature References: <j7ocnvshp0jar2duskdgpd92qc7blvf8t0@4ax.com> Message-ID: <UdOdb.52$t44.3099@nnrp1.ozemail.com.au> Emacs - allows screen splitting vertically and horizontally into as many sections as you can handle on your monitor i.e. I have a 17" monitor and find 4 buffers visible at any time to be about right for comfort, but occassionally I'll split even one of these into two (horizontally of course - at this point you can't read much if you split vertically :-)). Quite often one of them is the Python interpretor session in which I am debugging source I am looking at in another screen buffer....... Emacs also has a supports package/mode available called escreen - this is a "duplication" (for Emacs) of the Unix screen utility - it basically allows multiple screens (the screen utility on Unix allowed multiple virtual terminals on a character based terminal), each of which you can then split as you like. So you can get some quite complicated combinations all within the same edit session (of course multiple "screens" like this aren't visible at once). Peter "Daniel Klein" <danielk at aracnet.com> wrote in message news:j7ocnvshp0jar2duskdgpd92qc7blvf8t0 at 4ax.com... > I don't want to get into a 'which IDE is the best' conversation. I'm > looking for an IDE that has the ability to view 2 (or more) > methods/functions within the same module simultaneously. > > I've looked at the screen shots for Komodo, Wing, BlackAdder, etc and > it is not obvious that any of them have this feature. > > This is something I got use to in Smalltalk and have found it quite > useful when working on several methods that work closely together. > > Daniel Klein From jjl at pobox.com Wed Sep 10 09:13:32 2003 From: jjl at pobox.com (John J. Lee) Date: 10 Sep 2003 14:13:32 +0100 Subject: My future Python IDE article References: <mailman.1061920192.21278.python-list@python.org> <becf4072.0309082111.4ef1783f@posting.google.com> <3f5dec0d@news.comindico.com.au> <3F5E053D.743DA13A@easystreet.com> Message-ID: <87k78gbxc3.fsf@pobox.com> achrist at easystreet.com writes: > Tom Lee wrote: > > JEdit is fantastic. [...] > a bad crash -- I don't recall exactly what -- maybe a BSOD or a > JVM crash. That's not the kind of thing I enjoy, so I haven't > used it since. What platform was that (JVM, OS)? John From kodambal at imec.be Tue Sep 2 05:47:17 2003 From: kodambal at imec.be (K.C. Shashidhar) Date: Tue, 02 Sep 2003 11:47:17 +0200 Subject: printer friendly python tutorial In-Reply-To: <mailman.1062488944.11530.python-list@python.org> References: <jRb4b.231609$cF.75639@rwcrnsc53> <jRb4b.231609$cF.75639@rwcrnsc53> <YTb4b.235097$It4.112333@rwcrnsc51.ops.asp.att.net> <5.2.1.1.0.20030901234513.02e92120@66.28.54.253> <mailman.1062488944.11530.python-list@python.org> Message-ID: <1062496037.923678@dmz2.imec.be> Fredrik Lundh wrote: > http://www.python.org => Documentation => Download > Current Documentation (first link on page) => > > http://www.python.org/doc/current/download.html > > where the table on the top of the page contains download > links for HTML, PDF, Postscript, GNU info, iSilo, and LaTeX > versions of the docs, in ZIP, GZip, and BZip2 archives. I wonder why someone wanting to print only the tutorial has to download the whole archive and unzip. Wouldn't it be helpful to keep them separately available, like the HTML versions are? MHTP, Shashi From google at hanger.snowbird.net Fri Sep 5 20:11:41 2003 From: google at hanger.snowbird.net (Kris Caselden) Date: 5 Sep 2003 17:11:41 -0700 Subject: Packaging? Message-ID: <abc3fdd3.0309051611.6dd16bf7@posting.google.com> Particularly in Windows, how do create installation packages for python scripts? I've noticed that PyOpenGL and PyGame use a pretty nice installer, and some games I've seen install and run without even needing python installed. How is this done? From stefan.fleiter at web.de Tue Sep 2 14:36:21 2003 From: stefan.fleiter at web.de (Stefan Fleiter) Date: Tue, 02 Sep 2003 20:36:21 +0200 Subject: Difference of hash and __hash__() Message-ID: <bj2nv5$hna$1@news.web.de> Hi, under Python 2.2.2: >>> s = slice(None,5,None) >>> hash(s) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unhashable type >>> s.__hash__() 136775584 Can anybody explain this? Greets, Stefan From mensanator at aol.com Sun Sep 28 22:18:32 2003 From: mensanator at aol.com (Mensanator) Date: 29 Sep 2003 02:18:32 GMT Subject: Recursion References: <xjLdb.565$Vb3.450032@news1.news.adelphia.net> Message-ID: <20030928221832.08626.00000320@mb-m05.aol.com> >Subject: Recursion >From: "Jakle" jakle1 at hotmail.com >Date: 9/28/2003 7:48 PM Central Standard Time >Message-id: <xjLdb.565$Vb3.450032 at news1.news.adelphia.net> > >Hi all. Need alittle help here. This is an example from "How to Think Like a >Computer Scientist: Learning with Python, Chapter 5". It's an open source >ebook, so if you feel like it you can find it here: >http://www.ibiblio.org/obp/thinkCSpy/ > >The example uses factorials to explain more complex recursion. > >"Explanation From the Book Begins Here"++++++++++++++++++ > >>def factorial(n): >> if n == 0: >> return 1 >> else: >> recurse = factorial(n-1) >> result = n * recurse >> return result >> >> The flow of execution is as follows. >> If we call "factorial" with the value 3: >> >> Since 3 is not 0, we take the second branch and calculate the factorial >of n-1... >> Since 2 is not 0, we take the second branch and calculate the >factorial of n-1... >> Since 1 is not 0, we take the second branch and calculate the >factorial of n-1... >> Since 0 is 0, we take the first branch and return 1 without >making any more recusive calls. >> The return value (1) is multiplied by n, which is 1, and the >result is returned. >> The return value (1) is multiplied by n, which is 2, and the result >is returned. >> The return value (2) is multiplied by n, which is 3, and the result, 6, >becomes the return value of the function that started the whole process. > >"Example Ends Here"++++++++++++++++++++++++++++++++ > >I thought I understood what was going on untill "Since 0 is 0...", but after >that I get lost. Where are the variables being stored. >And how does 1*1=2 ---> The return value (1) is multiplied by n, which is 1, You've made a mistake here. 1*1=1, not 2. You can always modify the program to add some debugging aids. Here, I added a second parameter to the function so we can track the level of recursion via indenting: # start def factorial(n,t): print '\t'*t,'factorial of',n if n == 0: print "\t"*t,'result =',1 return 1 else: recurse = factorial(n-1,t+1) result = n * recurse print "\t"*t,'result =',n,' * ',recurse,' = ',result return result # always make the intial call with the second parameter = 1 print factorial(3,1) # end The sample run produced is factorial of 3 factorial of 2 factorial of 1 factorial of 0 result = 1 result = 1 * 1 = 1 result = 2 * 1 = 2 result = 3 * 2 = 6 6 There are four variables named 'n', one at each level of recursion, that's why the 'result = ' formula keeps changing. The first parameter is 'n' (from the line 'factorial of' at the same level of indentation) and the second parameter is the result of the lower level of recursion. Note that at no point are we getting 1*1=2. Once you understand how it works, restore the function to its original form. >and the result is returned. The return value (1) is multiplied by n, which >is 2, and the result is returned. >Sorry if I explained my problem oddly. You can see the example in the above >link, under chapter 5. -- Mensanator 2 of Clubs http://members.aol.com/mensanator666/2ofclubs/2ofclubs.htm From tjreedy at udel.edu Wed Sep 3 12:25:50 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 3 Sep 2003 12:25:50 -0400 Subject: Invisible function attributes References: <51809ae4.0309030715.7706cadb@posting.google.com> Message-ID: <Z6ucnedZ-vGJi8uiXTWJhw@comcast.com> "Olivier Lefevre" <lefevrol at yahoo.com> wrote in message news:51809ae4.0309030715.7706cadb at posting.google.com... > Python 2.3 > >>> def foo(): > ... foo.a = 1 If you want foo to be attributed before it is called, move the setter outside the function. >>> def foo(): pass ... >>> foo.a = 1 >>> vars(foo) {'a': 1} Terry J Reedy From gh at ghaering.de Tue Sep 16 05:23:59 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 16 Sep 2003 11:23:59 +0200 Subject: getch() in Python In-Reply-To: <001b01c37c33$37081a00$3aa2e7c1@integrasoft.ro> References: <001b01c37c33$37081a00$3aa2e7c1@integrasoft.ro> Message-ID: <3F66D6AF.7050703@ghaering.de> Jozsa Boti wrote: > Hi! > > Is there a getch()-like function in Python that is OS independent? > I understand that msvcrt.getch() is available only under Windows. The first Google hit leads to http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 which is probably as cross-platform as you can get. Oh, and please use plain text in your messages, not HTML. -- Gerhard From pfleonard at hotmail.com Mon Sep 22 17:50:28 2003 From: pfleonard at hotmail.com (peter leonard) Date: Mon, 22 Sep 2003 14:50:28 -0700 Subject: Begineer Question : Global string substitution with re Message-ID: <Law11-F62bRFtSoJpnL00016df6@hotmail.com> Thank you the prompt reply. It works now.... a definite begineer question. Peter >From: Gary Herron <gherron at islandtraining.com> >Reply-To: gherron at islandtraining.com >To: "peter leonard" <pfleonard at hotmail.com>, python-list at python.org >Subject: Re: Begineer Question : Global string substitution with re >Date: Mon, 22 Sep 2003 02:40:06 -0700 > >On Monday 22 September 2003 02:22 am, peter leonard wrote: > > Hi, > > This is a basic question but I can't figure out what is wron - even >after > > reading the documentation. I have a script that normalizes strings. One >of > > the steps is to convert all fractions too the tag 'fraction'. For >example : > > > > import re > > line = "This is the first ratio, 170/37, and this is the second 170/37 >" > > > > > > def normalise(text): > > > > #Tag fractions > > fraction = r'(\s+\d+\/\d+\s+)' > > regfr = re.compile(fraction) > > text = regfr.sub(" |fraction| ",text) > > > > #Remove punctuation > > punc = r'\,' > > regpunc = re.compile(punc) > > text = regpunc.sub("",text) > > > > return text > > > > print line,"\n" > > print normalise(line),"\n" > > > > > > The output from this script is : > > > > This is the first ratio, 170/37, and this is the second 170/37 > > > > This is the first ratio 170/37 and this is the second |fraction| > > > > > > I can't understand why only one of the fractions gets substituted. The > > documentation for sub states that the default argument for sub is 0 >which > > means replace all occurences. The output of my script should be : > > > > This is the first ratio |fraction| and this is the second |fraction| > >The problem is that your regular expression ends with "\s+". This means >the digits of the fraction *must* be followed by at least one space, >and the digits of your first fraction are followed by a comma and not >a space. > >Your re is matching spaces--fraction--spaces. I'd guess that you >don't really want to match spaces on either side of the fraction. > >Gary Herron > > _________________________________________________________________ Instant message with integrated webcam using MSN Messenger 6.0. Try it now FREE! http://msnmessenger-download.com From Spam.Buster at web.de Fri Sep 5 22:06:52 2003 From: Spam.Buster at web.de (Lars Behrens) Date: Sat, 06 Sep 2003 04:06:52 +0200 Subject: list to string Message-ID: <bjbfdu$hjsrl$1@ID-95936.news.uni-berlin.de> Hi there! I need help for cgi-script. I've been fiddling around for quite a while, searched through lots of doc. But I didn't get it: Can someone point me a way to change a list with arbitrary number of items to a string : vals = ['aaa', 'bbb', 'ccc'] valstring = 'aaa, bbb, ccc' Seems easy at the first glance, but... Tia Lars From piet at cs.uu.nl Wed Sep 3 09:43:47 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 03 Sep 2003 15:43:47 +0200 Subject: Arguments of function as out References: <bj499r$cio$02$1@news.t-online.com> Message-ID: <wzoey20yy4.fsf@nono.cs.uu.nl> >>>>> "Birgit Rahm" <br_y at yahoo.de> (BR) wrote: BR> Hallo Newsgroup, BR> I have the following problem: BR> I work with Python 2.2 and invoke functions via CORBA ( I use BR> onmiORB/omniORBpy) on a server. BR> The server provides me a function, where the 3 arguments are out-arguments BR> and the return is void / None. BR> How can I get these out arguments? BR> I have read that every argument is seen as local to the function and BR> can not be used as return value. BR> (I can't redesign the server function.) BR> Can I make the 3 arguments global before they were used in the function? BR> Does this help me? BR> Or what can I do? This is described in the Python language binding: Operations of an interface map to methods available on the object references. Parameters with a parameter attribute of in or inout are passed from left to right to the method, skipping out parameters. The return value of a method depends on the number of out parameters and the return type. If the operation returns a value, this value forms the first result value. All inout or out parameters form consecutive result values. The method result depends then on the number of result values: * If there is no result value, the method returns None. * If there is exactly one result value, it is returned as a single value. * If there is more than one result value, all of them are packed into a tuple, and this tuple is returned. -- Piet van Oostrum <piet at cs.uu.nl> URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From tzot at sil-tec.gr Wed Sep 17 08:58:38 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 17 Sep 2003 15:58:38 +0300 Subject: scp in python References: <bk9ho8$hau$1@reader1.tiscali.nl> Message-ID: <q8mgmv89ldtk7b6e2fkcvir0se10rr2o8l@4ax.com> On Wed, 17 Sep 2003 13:49:36 +0200, rumours say that "Michael" <qwerty at tiscalimail.nl> might have written: >Is there a scp (ssh) written in Python ? import google google.search("python ssh") -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From nospam at here.com Mon Sep 1 13:20:30 2003 From: nospam at here.com (Richard Townsend) Date: Mon, 1 Sep 2003 18:20:30 +0100 Subject: Image on disabled button Message-ID: <1062436629.69505.0@dyke.uk.clara.net> Is there a known problem with images on disabled buttons on Tk8.4.4 ? If I create a button widget using a bitmap as the image and make the button disabled, not all of the image becomes stippled. The 3 left hand columns of pixels and the bottom 3 rows of pixels are left unchanged. This is most obvious if you use a black square as the bitmap. If I run the same application using Tk8.3.4 this doesn't happen - the stipple is applied to the whole image. I am using Python2.3 + Tkinter to test this. RT From steve at ferg.org Mon Sep 29 10:17:19 2003 From: steve at ferg.org (Stephen Ferg) Date: 29 Sep 2003 07:17:19 -0700 Subject: Google newsgroup "Unable to find thread" message? Message-ID: <b16e4ef7.0309290617.799b800d@posting.google.com> I use the newsgroup mainly via my Web browser and Google. Over the last few days, when I click on a link to a thread, I've been frequently getting the message "Unable to find thread." Does anybody know what's going on? From newsgroups at jhrothjr.com Mon Sep 22 06:55:20 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 22 Sep 2003 06:55:20 -0400 Subject: Money data type References: <mailman.1063894475.13047.python-list@python.org> <q8Sdna1v7JgzKfOiXTWJkw@august.net> Message-ID: <vmtl8cjg9jo9ac@news.supernews.com> "Terry Hancock" <hancock at anansispaceworks.com> wrote in message news:q8Sdna1v7JgzKfOiXTWJkw at august.net... > Batista, Facundo wrote: > > Are you trying to tell me that if I work always with float, and in the > > final step (reaching the user's eyes or check in the printer) I > > "represent" it with str (for example) or with "%.5f", I get no rounding > > errors? > > > > If you are, I will believe you! (even "feeling" other way, but can not > > prove it). > > Nope, you will indeed get small errors if you do this -- at least you will > if you work with very large amounts of money in the calculations. The > only way to "not drop pennies" is to represent them with integers. > > Specifically, Python long integers have arbitrary size (they are limited > by memory, not any fixed upper limit as are normal ints in python and > integer types in languages like C). > > I'm pretty sure that the fixed point library that was mentioned does > exactly this -- it represents the numbers in the same way as the Python > long, but with the decimal point moved to a certain place. > > People who are used to scientific and engineering computations don't > worry about this -- there are well-defined ways to avoid trouble from > rounding errors in those fields, and the need for numbers that can > represent arbitrarily large and small values in a compact way far outweighs > the precision advantage of integer or fixed-point representations. > > I say this after having had this point proved to me, since I tended to > be from the "why not use floats" school, myself. Whether in some > moral sense we *should* be concerned about pennies in a number like > the US national debt, is a philosophical issue I don't think we can > do justice to here. ;-) There's actually a rather simple conceptual difference. Scientific and engineering computation deals with continuous quantities, financial calculations deal with discrete quantities. Floats are an adequate appromimation to continuous quantities (at least, if you pay careful attention to precision and error bounds) while integers are correct for discrete quantities. It's not a matter of "better" or "worse." It's a matter of the correct tool for the job. John Roth > > Cheers, > Terry > From ville.spammehardvainio at spamtut.fi Thu Sep 11 12:30:47 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 11 Sep 2003 19:30:47 +0300 Subject: Cool & Useful EmPy project, prior art? References: <du71xunfweg.fsf@mozart.cc.tut.fi> Message-ID: <du7y8wvcmo8.fsf@amadeus.cc.tut.fi> Ville Vainio <ville.spammehardvainio at spamtut.fi> writes: > ('gclip' of win32 unxutils should work, how can I do it in python BTW?) Obviously I *could* have checked google first, but what the heck... -- Ville Vainio http://www.students.tut.fi/~vainio24 From tim.parkin at pollenationinternet.com Mon Sep 8 16:44:22 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Mon, 8 Sep 2003 21:44:22 +0100 Subject: "Python Redesign" (fwd) In-Reply-To: <5XmdnSsEgZVGSsGiU-KYvw@comcast.com> Message-ID: <003a01c3764a$022a7420$0a00a8c0@JASPER> Terry: >In any case, Parkin also used (and today defended) the word himself in >his subsequent posts. Leaving dictionaries aside, the use of the >disputable word 'mockup' instead of the accurate word 'image' lead to >unfulfilled expectations and criticisms based thereon. Indeed, Parkin >himself deflected such criticisms several times by saying 'its just an >image' [and not the html mockup some thought it was]. > >Do you really think inexact words that lead to misunderstanding are as >useful as exact words that do not? Do you really think the >distinction between object and image is useless? These are the >questions I raised and gave my answer to. Please look up 'web design mockup' in Google and check how it is used. Furthermore if I were to create a mockup that was built using HTML, what would it be a mockup of? Please can we leave this tautological farce at this point. If you need to reply further please do it to me directly, otherwise I will presume you are carrying on for the sake of everyone else on comp.lang.python and I have a feeling that isn't really what they want. Tim Ps I presume you meant "exact words that lead to misunderstanding" and "inexact words that do not" Pps Are the words object and image really clearer than the word. The word object means a a material thing. Material can mean information. So we get an information thing. Image means the optical appearance of something. So a HTML page creates an Image. As Does a jpg. An object means a thing. Are we really getting clarity. My word "mockup" did not cause the unfulfilled expectations, it was the jumping to conclusions that a .html page meant it must be a finished item. From p.useldinger at myrealbox.com Fri Sep 12 14:05:59 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Fri, 12 Sep 2003 20:05:59 +0200 Subject: Web server with Python References: <tnr1mvgnt45urvu6n4q6dso3eto73hfr1m@4ax.com> <sx68b.29387$Hb.450091@news4.e.nsc.no> <bjr3ea$m5rr9$1@ID-139865.news.uni-berlin.de> <gvs2mvcgmji0s536475c14oa5tm7cigk13@4ax.com> <mailman.1063352060.32640.python-list@python.org> Message-ID: <6o24mvcmksid33t4s9b8cbsrnctl5n2o6m@4ax.com> On Fri, 12 Sep 2003 17:33:34 +1000, Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote: >> Does Twisted work well with Python 2.3? > >Yes, current versions support 2.3 without any problems. Version 1.0.6 refuses to install, though, complaining it requires Python 2.2. -PU From mfranklin1 at gatwick.westerngeco.slb.com Fri Sep 19 10:07:43 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 19 Sep 2003 15:07:43 +0100 Subject: Webware and memory problem! In-Reply-To: <tf1mmv019lp8cucqvcgtf5v9qi2svv4n36@4ax.com> References: <tf1mmv019lp8cucqvcgtf5v9qi2svv4n36@4ax.com> Message-ID: <1063980462.1068.3.camel@m-franklin> On Fri, 2003-09-19 at 14:35, JZ wrote: > How much memory WebKit should normally take??? As I can see, every > WebKit daemon takes over 40MB (sic!) of RAM. WebKit lauches 10 daemons > during startup, so I need over 400MB for WebKit alone! Is it normal or > I have something wrong configured? (used RedHat7 and Webware CVS > 2003-09-12) > > I compared the same with Windows XP Pro workstation. It takes only > 10MB and uses only one process! Top ammount of used memory is 17MB... > > -- > JZ I think you may be counting all the threads that WebKit starts. On an older version of Linux like yours each thread shows up as it's own process. So I suspect WebKit is really using 40B total on Linux. not 10 x 40M Regards Martin -- Martin Franklin <mfranklin1 at gatwick.westerngeco.slb.com> From fredrik at pythonware.com Sun Sep 21 03:22:40 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2003 09:22:40 +0200 Subject: Scaling Tk scrollbar handles References: <K96dnU3ln-RTefSiU-KYvg@comcast.com> Message-ID: <bkjjk2$28k$1@sea.gmane.org> Gordon Airport wrote: > None of the online references that I'm using or can find tell you if > this can be done. It's standard practice in GUI's to have the handle of > a scrollbar sized to be the proportion of total ammount of viewable data > to the ammount you can see in the current view region. (I think that > explains it, you know what I mean.) I have a scrollbar attached to a > canvas, and it scrolls properly, but it always has a tiny little handle. by default, the canvas tells the scrollbars that the canvas surface is unbounded (-maxfloat to +maxfloat); no matter how you scroll around, you're only seeing a very small portion of the available coordinate space. to get the behaviour you're after, set the "scrollregion" option. for some more background and code samples, see: http://www.effbot.org/zone/tkinter-scrollbar-patterns.htm#canvas http://www.effbot.org/zone/tkinter-scrollbar-patterns.htm#canvas </F> From joshway_without_spam at myway.com Tue Sep 30 12:09:58 2003 From: joshway_without_spam at myway.com (JCM) Date: Tue, 30 Sep 2003 16:09:58 +0000 (UTC) Subject: can i implement virtual functions in python ? References: <e73c30c6.0309300653.24456567@posting.google.com> Message-ID: <blc9sm$ckc$1@fred.mathworks.com> Prabu <prabua at hotmail.com> wrote: ... > I'm new to python, so excuse me if i'm asking something dumb. > Does python provide a mechanism to implement virtual functions? Others have given good responses, but I'll jump in anyway. Virtual functions (using C++ terminology) are something limited to statically-typed languages. A virtual function call will be resolved dynamically, based on the runtime type of the object. A non-virtual call will be resolved at compile-time, based on the declared type of the object. Since Python is dynamically typed, the only possibility is for all methods to be "virtual". From __peter__ at web.de Fri Sep 26 10:33:25 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Sep 2003 16:33:25 +0200 Subject: Reduce need of backslash References: <h4Ycb.75236$PD3.4793080@nnrp1.uunet.ca> Message-ID: <bl1iq3$ss$01$1@news.t-online.com> Nicolas Fleury wrote: > I was wondering if the need for \ could be reduce in the language. For > example, could a line ending with = or + could be automaticly considered > incomplete? Did you know about (...)? >>> ("alpha" ... + "beta" ... + "gamma" ... ... ) 'alphabetagamma' >>> Peter From mirandacascade at yahoo.com Tue Sep 23 12:24:16 2003 From: mirandacascade at yahoo.com (Miranda Evans) Date: 23 Sep 2003 09:24:16 -0700 Subject: pymqi sample code Message-ID: <59e5b87.0309230824.2357f717@posting.google.com> I am attempting to locate code fragments from python scripts that illustrate how to accomplish 2 different tasks using pymqi 1) when making a call to MQPUT, want to set 2 different message descriptor values: - want to set MsgId to MQMI_NONE - want to set ReplyToQ to a string the contents of which is the name of the queue in which a subsequent MQGET will retrieve the message, e.g. "QL.MYREPLY" It appears as though this would be accomplished in the constructor of the md() class, but I'm unsure of what the code would look like to instantiate an instance of the class with those 2 message descriptor values. 2) according to IBM documentation, when MsgId is MQMI_NONE on an MQPUT, a unique message identifier is created and put in the message descriptor; how can the python script obtain the unique message identifier that got created? thank you. From pweldon at mindspring.com Sun Sep 21 21:51:15 2003 From: pweldon at mindspring.com (Phil Weldon) Date: Mon, 22 Sep 2003 01:51:15 GMT Subject: python script as an emergency mailbox cleaner References: <mailman.1064181868.1628.python-list@python.org> Message-ID: <nAsbb.50573$Aq2.40370@newsread1.news.atl.earthlink.net> It'd be easier to follow this thread if you trimed past content more and if your newsreader properly indented. A thread becomes loggy with top posting constantly interrupting the flow of the discussion. Phil Weldon, pweldon at mindspring.com "Tim Peters" <tim.one at comcast.net> wrote in message news:mailman.1064181868.1628.python-list at python.org... > [Phil Weldon] > > Phil, top-posting makes it very hard to follow a discussion. I'll reply > briefly here, but if you want to continue it, please move it to the > spambayes list and interleave your comments with the text of the msg you're > reply to . . . . From sheu at bu.edu Mon Sep 22 11:17:53 2003 From: sheu at bu.edu (Shu-Hsien Sheu) Date: Mon, 22 Sep 2003 11:17:53 -0400 Subject: Slicing vs .startswith In-Reply-To: <DUCbb.100826$hE5.3550910@news1.tin.it> References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> <bkk4h1$9ke$06$1@news.t-online.com> <mailman.1064154389.29357.python-list@python.org> <bkmd4q$t13$05$1@news.t-online.com> <DUCbb.100826$hE5.3550910@news1.tin.it> Message-ID: <3F6F12A1.3010702@bu.edu> Hi, I have a question about the comparison of efficiency of string slicing and using string.startswith. For example, which one of the following would be more efficient, or , moreover, more pythonic? if aa[:3] == 'abc': vs if aa.startswith('abc'): Thanks! -shuhsien From rr84 at cornell.edu Fri Sep 19 18:10:30 2003 From: rr84 at cornell.edu (RR) Date: Fri, 19 Sep 2003 18:10:30 -0400 Subject: Python API Message-ID: <pan.2003.09.19.22.10.30.395537@cornell.edu> Hello, where is nice site that would have python API documentation? In particular I am trying to find documentation on the function string.find -RR From ny_r_marquez at yahoo.com Wed Sep 10 10:00:37 2003 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 10 Sep 2003 07:00:37 -0700 Subject: I need to make Excel/Powerpoint-style charts. References: <mailman.1063120814.8263.python-list@python.org> Message-ID: <8a27e309.0309100600.345e1ea2@posting.google.com> Have you looked here? http://www.python.org/topics/scicomp/plotting.html -Ruben python at sarcastic-horse.com wrote in message news:<mailman.1063120814.8263.python-list at python.org>... > I hope to find some sort of python graphics library that can make charts > similar to Excel and Powerpoint, and then I can start automating these > tasks. From dave at boost-consulting.com Sun Sep 28 11:22:11 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 28 Sep 2003 11:22:11 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <uk77vhagj.fsf@boost-consulting.com> <JH_cb.174346$R32.5548036@news2.tin.it> <u7k3ve63q.fsf@boost-consulting.com> <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> <ur8239i6z.fsf@boost-consulting.com> <0acdb.128801$hE5.4391247@news1.tin.it> <u4qyy8mfk.fsf@boost-consulting.com> <1Xhdb.130593$hE5.4445587@news1.tin.it> <9tabnvgbc4etnpp1hm3oh5dkffkru9pv0d@4ax.com> <ufzii5hou.fsf@boost-consulting.com> <2tsbnvob1k6tt6bkb29cfc69a4ji0q4giv@4ax.com> <uy8w94wtz.fsf@boost-consulting.com> <lhacnvksb6ppje2lfogrqhv30rbcahgil2@4ax.com> Message-ID: <ulls92b18.fsf@boost-consulting.com> Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: >>Sorry, what specialization? > > Presumably template specialisation - such that the special case of > std::pair<T,T> picks up the iterating functionality that > std::pair<T,U> lacks (begin, end etc). That is what I thought you were > saying. > > Or am I still getting this wrong? Yeah, slightly. You don't need a begin() member function in order to make an iterator. The interface might look like: std::for_each(pair_iterator<T>(my_pair), pair_iterator<T>(), f); Decoupling is the way to go, man! :^) -- Dave Abrahams Boost Consulting www.boost-consulting.com From mpeuser at web.de Fri Sep 5 15:43:59 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 21:43:59 +0200 Subject: Drag and drop in Tkinter. How difficult is it? References: <ApGdnUgAC6p1AMuiU-KYuA@comcast.com> <vle0j01npmca27@corp.supernews.com> <4378fa6f.0309041125.49b13fc7@posting.google.com> Message-ID: <bjap35$odj$03$1@news.t-online.com> "Marc" <mnations at airmail.net> schrieb im Newsbeitrag news:4378fa6f.0309041125.49b13fc7 at posting.google.com... > Excellent. Thanks for the head start. > > A couple of questions. I think they will be answered when you look at the link (Tree.py) I posted yesterday ;-) Kindly Michael P From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Sep 26 10:48:29 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 15:48:29 +0100 Subject: When did Windows start accepting forward slash as a path separator? References: <b16e4ef7.0309251550.724a57f@posting.google.com> <mailman.1064540736.16016.python-list@python.org> <2aNcb.3620$RW4.1866@newsread4.news.pas.earthlink.net> Message-ID: <78k8nv85du9pivltsjvqu82nhv50ie2mu1@4ax.com> On Fri, 26 Sep 2003 02:05:50 GMT, "Andrew Dalke" <adalke at mindspring.com> wrote: >Bob Gailer: >> Good question. Certainly later than: >> >> Microsoft Windows 2000 [Version 5.00.2195] >> (C) Copyright 1985-2000 Microsoft Corp. >> >> C:\>cd /samis >> The syntax of the command is incorrect. > >The shell is parsing the line and interprets the "/" as a >command-line flag, Try a relative path, like > > cd ./samis Nope... F:\>cd ./dev F:\>cd .\dev F:\Dev> Notice how the forward slash version doesn't change directories, but the back slash version does. My guess is that it is being taken as... cd . /<unknown option> The big question being why the unknown option doesn't get an error message, as it normally does. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From bokr at oz.net Sat Sep 27 11:57:45 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Sep 2003 15:57:45 GMT Subject: Reduce need of backslash References: <h4Ycb.75236$PD3.4793080@nnrp1.uunet.ca> <bl1iq3$ss$01$1@news.t-online.com> Message-ID: <bl4c1p$c2p$0@216.39.172.122> On Fri, 26 Sep 2003 16:33:25 +0200, Peter Otten <__peter__ at web.de> wrote: >Nicolas Fleury wrote: > >> I was wondering if the need for \ could be reduce in the language. For >> example, could a line ending with = or + could be automaticly considered >> incomplete? > >Did you know about (...)? > >>>> ("alpha" >... + "beta" >... + "gamma" >... >... ) >'alphabetagamma' >>>> > Did you know the tokenizer concatenates white-space-separated string literals into a single literal? ;-) >>> ("alpha" ... "beta" ... "gamma" ... ) 'alphabetagamma' Note the effect in code: >>> import dis >>> f1 = lambda: ("alpha" ... + "beta" ... + "gamma" ... ) >>> f2 = lambda: ("alpha" ... "beta" ... "gamma" ... ) >>> dis.dis(f1) 1 0 LOAD_CONST 1 ('alpha') 3 LOAD_CONST 2 ('beta') 6 BINARY_ADD 7 LOAD_CONST 3 ('gamma') 10 BINARY_ADD 11 RETURN_VALUE >>> dis.dis(f2) 1 0 LOAD_CONST 1 ('alphabetagamma') 3 RETURN_VALUE Regards, Bengt Richter From max at alcyone.com Mon Sep 8 03:04:10 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Sep 2003 00:04:10 -0700 Subject: Ternary operator (Re: Ternery operator) References: <doJ6b.1999$Ft.737@newssvr22.news.prodigy.com> <3F5B6404.BD1A9709@engcorp.com> <vlo9699d77sj3e@corp.supernews.com> Message-ID: <3F5C29EA.86D2D0EB@alcyone.com> Michael Geary wrote: > I suppose this is all water under the bridge now, since the PEP stated > that > this was the community's one and only chance. I just can't help but > think > that the voting system guaranteed the outcome--but it's Guido's > language and > it was certainly his call to make. I'm not sure any form of voting system would have changed the outcome. The wording of the introduction to the PEP suggested that the BDFL did not want the language feature, and put it to the community to prove to him unequivocally that a very large majority of people wanted the feature and wanted the same form of the feature, leaving him no choice but to admit that the desire for it was too strong to ignore. I'm sure he was well aware of the fact that that wasn't the case, but just wanted to (in his mind) put the issue to bed. As you say, it's his language, and it's most assuredly within his power to do that. I personally wanted a conditional operator, and I'm disappointed that the PEP was rejected, but I'm not surprised. (My only specific complaint is that the decision came so many months after the discussion and vote, and indirectly via a presentation at EuroPython, but that's a separate issue.) All I'll say beyond that is, if the goal of forcing a vote via a PEP with the intent of closing the issue in the community, I think that's wishful thinking. People will still ask for conditional operators, people will still resort to unreadable, broken compromises like `C and x or y' and there will still be discussion on it in the future. Mind you, despite my favoring the PEP, I'm not suggesting that _that_ is a reason to accept it; just that if one thinks that the issue won't come up over and over again from the community in the future. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ There's this perfect girl / Living inside the shell \__/ Lamya From batraraj at hotmail.com Tue Sep 16 20:04:04 2003 From: batraraj at hotmail.com (Raj Batra) Date: 16 Sep 2003 17:04:04 -0700 Subject: Streams causing heap crash using Python C-Extensions Message-ID: <ee04f1ee.0309161604.2f13c59b@posting.google.com> Hi, I've created a dll that you can import into python. The function calls an ostringstream class. Calling this function repeatedly in python will cause a Microsoft Visual C++ Debug Library error: Debug Assertion Failed! Program: C:\Program Files\Python22\python.exe File: dbgheap.c Line: 346 Expression: _CrtCheckMemory() Here are snippets of the code: // Method called by python via a PySwitchObject static PyObject * pyCircuit(PySwitchObject * self, PyObject * args) { int circuit; if (!PyArg_ParseTuple(args, "i", &circuit)) { // Error handling... } self->_switch->circuit((U8) circuit); Py_INCREF(Py_None); return(Py_None); } // Called by pyCircuit method above. Multiple calls to this method // yield a heap assertion. void Switch::circuit(U8 c) { std::ostringstream close; close << "Some formating..."; // Use the close method - doesn't really matter. } The error is always within the constructor or destructor of ostringstream and in the file called xmutex.cpp (implements mutex lock for iostreams) which calls the malloc/dealloc functions. I have tried other streams such as fstream, and get similar behavior. Switching to a char buffer[] and sprintf is my current work around the ostringstream issue. Any thoughts about what is going on? I'm using Python2.2.2, with Visual C++ 7 (.NET). The error occurs using both pythonwin and the standard command line python. Thanks, Raj From mwh at python.net Tue Sep 30 10:30:56 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 30 Sep 2003 14:30:56 GMT Subject: FTP access to starship.python.net? References: <d7fcf8b4.0309271341.72304331@posting.google.com> <7h3fzif1yi8.fsf@pc150.maths.bris.ac.uk> <bla9fc$v3$1@panix3.panix.com> Message-ID: <7h3r81yz73b.fsf@pc150.maths.bris.ac.uk> aahz at pythoncraft.com (Aahz) writes: > In article <7h3fzif1yi8.fsf at pc150.maths.bris.ac.uk>, > Michael Hudson <mwh at python.net> wrote: > >samschul at pacbell.net (Samuel Schulenburg) writes: > >> > >> Who should I contact about accessing my account on Starship. I need to > >> obtain a new password and access process. > >> > >> I think i am having a memory lapse as it has been over a year sense I > >> have had a need to access my files. > > > >I think emailing <your username>-starship at python.net will lead to > >enlightenment. > > Hmmmm. I tried that, and I haven't been enlightened. well, then crew@ or webmaster@, I guess. Cheers, mwh -- Sufficiently advanced political correctness is indistinguishable from irony. -- Erik Naggum From jwdillworth at yahoo.com Wed Sep 3 08:52:21 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Wed, 3 Sep 2003 05:52:21 -0700 (PDT) Subject: Code complete electronic version ? Message-ID: <20030903125221.67155.qmail@web41102.mail.yahoo.com> I had it, but got rid of it (gave to co-worker). After reading the _The Pragmatic Programmer_, the "software development as construction" metaphor seemed slightly broken IMHO and I couldn't get excited about reading it. The authors of the latter explain software development like gardening, there being an element of unpredictability or at least hard-to-predictability. I think this explains software development nicely. Sometimes what you planted doesn't grow like you expected. Sometimes some weeding is necessary. It's an ongoing thing, more so than construction where once a building is built, it's built, maybe needing the occasional paint job or a new roof but those chores don't seem to make good software development metaphors. Construction is also highly predictable. If you throw N workers at building of X size the job will be done in Z weeks. Expecting such predictability from software development will lead to disappointment, tension, and possibly job loss. Anyway, I highly recommend _The Pragmatic Programmer_. Some bits of _Code Complete_ are also good, the "don't flip the bozo bit" (IIRC) section contains some good advice. And it does encourage one to take pride in their coding. --- post400 <post400 at prontomail.com> wrote: > Hi, > > apparently there is a very famous book that every developer should > read: Code complete by Steve McConnell ! > > Is there an electronic version freely downloadable ? After all, the > book was released in 1993 , it should have been public domain by now ! > It would be nice to have a try before ! 50? is not exactly cheap ! > What do you think ? Is it worth the money or not ? > > Thanks ! > post400 > -- > http://mail.python.org/mailman/listinfo/python-list From kevin at cazabon.com Fri Sep 19 12:37:52 2003 From: kevin at cazabon.com (Kevin Cazabon) Date: 19 Sep 2003 09:37:52 -0700 Subject: Exception in Threading References: <e956b5f1.0309182327.4c633cf5@posting.google.com> Message-ID: <5a4226f0.0309190837.48f32cad@posting.google.com> If that's the entire error message, I'd suspect that you're not supplying the correct arguments when creating the thread object. It looks like when you call myThread.start(), the threaded class you created is balking at the argument list passed to it. But, that doesn't look like a complete traceback error stack either... Kevin. meinmailfilter at gmx.de (HHaegele) wrote in message news:<e956b5f1.0309182327.4c633cf5 at posting.google.com>... > Hello, > what does this exception mean. I don?t have any idea where to start > searching for the mistake, can you give me some hints , please. > > Exception in thread Thread-1: > Traceback (innermost last): > File "E:\dSPACE\ControlDesk\Python\Lib\threading.py", line 376, in > __bootstrap > self.run() > File "E:\dSPACE\ControlDesk\Python\Lib\threading.py", line 364, in > run > apply(self.__target, self.__args, self.__kwargs) > > Thank you > Haegges From jhibschman at yahoo.com Sat Sep 6 23:00:34 2003 From: jhibschman at yahoo.com (Johann Hibschman) Date: Sun, 07 Sep 2003 03:00:34 GMT Subject: Why python??? In-Reply-To: <3335321.1062775466@dbforums.com> References: <3335321.1062775466@dbforums.com> Message-ID: <mbx6b.1996$Yt.953@newsread4.news.pas.earthlink.net> yeung_too wrote: > I think many people spend time on Java and university uses > Java because Sun Microsystem spends much money to promote and > develop the Java language. Actually, in my experience, students will complain endlessly if they have to use a language that they don't think will immediately get them a job. So, usage of C, C++, and Java is probably student-driven, not faculty-driven. I was a grad student at UC Berkeley for years, and I remember horror stories from the CS grad students about undergrads bitching endlessly about having to use Scheme, because "no one uses Scheme in the real world." Personally, I think this reveals that people are thinking of university more as a trade school, at least in CS, rather than a "mind-broadening" education. The humanities people never worry that Chaucer isn't used in "the real world." I mean, people major in "computer science" not "computer programming." Computer science is, well, complexity, algorithms, design interactions, and so on; things independent of brute coding. This doesn't really help you, but I am guessing that it's your fellow students who demand Java. Cheers, -Johann From FBatista at uniFON.com.ar Thu Sep 18 12:15:26 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 18 Sep 2003 13:15:26 -0300 Subject: Money data type Message-ID: <A128D751272CD411BC9200508BC2194D03382FA3@escpl.tcp.com.ar> #- See #- <http://www.brunningonline.net/simon/blog/archives/000710.html> and #- <http://www.brunningonline.net/simon/blog/archives/000911.html>. #- #- Basically, if you use floats, you'll get rounding errors. That?s my whole point, but I just can't find a good example. Anyway, all roads leads to FixedPoint (all roads leads to Trantor, :)) . Facundo From essai1 at mci.local Tue Sep 30 15:16:15 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Tue, 30 Sep 2003 21:16:15 +0200 Subject: Win32 Screensaver library References: <Xns94051AB966225cliechtigmxnet@62.2.16.82> Message-ID: <blckn3$9r7$1@news-reader3.wanadoo.fr> Super-M?ga-G?nial ! Merci ! Thanks ! From grante at visi.com Wed Sep 17 16:07:55 2003 From: grante at visi.com (Grant Edwards) Date: 17 Sep 2003 20:07:55 GMT Subject: New style classes Message-ID: <3f68bf1b$0$42051$a1866201@newsreader.visi.com> Is it just me, or does the "new style american girlfriend" line from "Sixteen Candles" pop into anybody else's head when the see the phrase "new style classes" mentioned on a subject line? Ah. Just me? I was afraid of that. -- Grant Edwards grante Yow! .. My pants just went at on a wild rampage through a visi.com Long Island Bowling Alley!! From ta-meyer at ihug.co.nz Mon Sep 29 20:13:57 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 30 Sep 2003 12:13:57 +1200 Subject: isNumber? check In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1303744E32@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F2974@its-xchg4.massey.ac.nz> Rob> I don't like that solution for this particular project because, as Rob> you say yourself, if it says yes to the second question, it only Rob> *may* be a number. I want to know for sure. This also works, although it may not be best for your situation (only does int and float for brevity): """ def isInt(s): try: i = int(s) except ValueError: i = None return i def isFloat(s): try: i = float(s) except ValueError: i = None return i def isNumber(s): return isInt(s) or isFloat(s) """ One advantage is that it returns the number (as an int (preferable) or float) rather than just True/False (None is returned if it is not able to be turned into a number). You're probably going to want to turn it into a number at some point anyway, right?, so why not do it in one step. Note that "0" will come back as 0.0, though, because it evaluates as False. It would be easy enough to special case that, if necessary. =Tony Meyer From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Sep 26 15:42:00 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 20:42:00 +0100 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <wCGcb.3064$yU5.2141@nwrdny01.gnilink.net> <8RScb.169633$R32.5449258@news2.tin.it> <uk77vhagj.fsf@boost-consulting.com> <JH_cb.174346$R32.5548036@news2.tin.it> <u7k3ve63q.fsf@boost-consulting.com> Message-ID: <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> On Fri, 26 Sep 2003 14:51:05 -0400, David Abrahams <dave at boost-consulting.com> wrote: >Alex Martelli <aleax at aleax.it> writes: > >> David Abrahams wrote: >> ... >>> Also, the idea of denying tuples the ability to reverse iterate seems >>> arbitrary and capricious. >> >> Sure, but so is denying them, e.g., non-mutating methods such as >> .index() and .count(). > >Not IMO. Immutability is a very useful trait. Yes - and perfectly consistent with having *NON*-mutating methods such as .index() and .count() ;-) I always assumed that these were considered inconsistent with normal use of tuples (which certainly I rarely need to get 'index' or 'count'-like results from). Actually, they even seem a little odd in list, to be honest. I'd have functions, not necessarily even in __builtins__, which work on any sequence. They just don't seem like everyday operations that should be built into the object. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From NO-MAIL at hotmail.com Tue Sep 9 23:05:51 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Wed, 10 Sep 2003 03:05:51 GMT Subject: CGI -- generating images -- \x0A always added! Message-ID: <jyw7b.16997$ip5.1259550@twister.southeast.rr.com> Hi All, I'm trying to use Python for generating (or copying) images. The environment is Python 2.3/Apache 2.0.43/Windows XP. I couldn't make Apache use mod_python (anybody can help? Apache complains "The requested operation has failed" if I add LoadModule python_module modules/mod_python.so) so I use the CGI mechanism. This is the sample: #!C:\Apps\Python\python.exe -u img = open( 'a.gif', 'rb' ) # OK, don't make the image, just use the file if img: data = img.read() img.close() print "Content-type: image/gif" print print data, # EOF Everything's good, and '-u' helps not to add '\x0D' for each '\x0A' inside the data. BUT it seems that the last print ALWAYS adds LF '\x0A' in spite of the final comma. How can I fix that? Thank you. M-a-S From fawcett at teksavvy.com Mon Sep 15 23:20:22 2003 From: fawcett at teksavvy.com (Graham Fawcett) Date: Mon, 15 Sep 2003 23:20:22 -0400 Subject: from clipper move to python In-Reply-To: <801542245.20030916095806@chead.org> References: <3812075547.20030915130057@chead.org> <6.0.0.22.0.20030915085400.041dd200@66.28.54.253> <801542245.20030916095806@chead.org> Message-ID: <3F668176.2020502@teksavvy.com> ads wrote: >Thank you for the respon, > >But right now I'm still not ready using linux, a lot of my client were >using windows. Is someone know what should I use to create text >console application like clipper using python in (stupid) windows? > >Thanks >:) > > Stupid Windows? Now, now, let's not start a flamewar. ;-) I've never used it, but I do see that there is a "Curses for Windows for Python" project at http://flangy.com/dev/python/curses/ though it's an "alpha" stage project. There's also "public domain curses" or pdcurses, available for Win32, http://gnuwin32.sourceforge.net/packages/pdcurses.htm Presumably it would work with the Python curses module. But again, I've not used it. In my opinion, you would probably have more success writing a GUI application using one of the "easy" app builders like PythonCard. It may be a new experience for you, but there will be more people who would be able to support you and answer your questions. -- Graham From xach at xach.com Mon Sep 15 10:35:18 2003 From: xach at xach.com (Zachary Beane) Date: Mon, 15 Sep 2003 09:35:18 -0500 Subject: list of lists References: <bk4grj$me3$1@news.uni-kl.de> Message-ID: <slrnbmbjl5.fvv.xach@unnamed.xach.com> In article <bk4grj$me3$1 at news.uni-kl.de>, Tom wrote: > Hi, > > I have a list that consists of lists. > E.g. T=[[1, 2, 3], [4, 5], [6]] > Is there a way to address the a specific component in the "inner" list > directly? > E.g. right now I want to get the second value of the first list. > Unfortunately I have to save it to a variable first and then read it. > a = T[0] > print a[1] > > That kind of sucks, becaus I have to read a lot of values from a lot of > lists! :-( > Is there a faster way than my saving it to a "help variable" first? To use your example: T=[[1, 2, 3], [4, 5], [6]] print T[0][1] Zach From tjreedy at udel.edu Tue Sep 2 15:42:34 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 2 Sep 2003 15:42:34 -0400 Subject: Which is the better way to parse this file? References: <10c662fe.0309020436.559d513d@posting.google.com> <au2dnSnl__hyPMmiU-KYgw@comcast.com> <10c662fe.0309020909.57817c13@posting.google.com> Message-ID: <t2ydnZkmJ80sb8miXTWJig@comcast.com> "Roberto A. F. De Almeida" <roberto at dealmeida.net> wrote in message news:10c662fe.0309020909.57817c13 at posting.google.com... > This is a Dataset Descriptor for the Data Access Protocol > (http://www.unidata.ucar.edu/packages/dods/design/dap-rfc-html/), an > API to access remote datasets. DAP servers describe their datasets > using this grammar, and I'm developing a module to access DAP servers. OK. The grammar is externally fixed and, I presume, constant across DAP servers. Even so, if the three collection types are functionally the same for *your* purpose, you can parse according to a simplified grammar. For recursive descent, you only two parse functions: one (recursive) for collections and one (terminal) for types. And the latter can be inlined in the former since only called at one place. Start with a generator function (or iterator class) 'worderator' initialized with a filename or input string that returns words/tokens one at a time. Main problem is getting rid of ;s. Also separating obrack or cbrack ({}) from words if not alway blank-separated as in your example. Code that works on your sample data: input= """dataset { int catalog_number; sequence { string experimenter; int32 time; structure { float64 latitude; float64 longitude; } location; sequence { float depth; float temperature; } xbt; } casts; } data;""" def worderator(inp): # generator, need 2.2&future or 2.3 for tok in inp.split(): yield tok[-1] != ';' and tok or tok[:-1] # check with: for i in worderator(input): print i, obrack,cbrack = '{', '}' toktype = {'string':str, 'int': int, 'int32': int, 'float': float, 'float64': float} def collection(): # call after seeing collection keyword d = {} tok = word.next() if tok != obrack: raise ValueError("Expected %s, got %s" % (obrack,tok) ) while 1: tok = word.next(); if tok == cbrack: break elif tok in toktype: d[word.next()] = toktype[tok] elif tok == 'sequence' or tok == 'structure': nam,dic = collection() d[nam] = dic else: raise ValueError("Unexpected token: %s" % tok) return word.next(), d word = worderator(input) tok = word.next() if tok == 'dataset': data = collection()[1] # assume always want collection called 'data' regardless of input else: raise ValueError("Started with %s instead of 'database'" % tok) >>> pprint.pprint(data) {'casts': {'experimenter': <type 'str'>, 'location': {'latitude': <type 'float'>, 'longitude': <type 'float'>}, 'time': <type 'int'>, 'xbt': {'depth': <type 'float'>, 'temperature': <type 'float'>}}, 'catalog_number': <type 'int'>} Terry J. Reedy From bgailer at alum.rpi.edu Thu Sep 4 07:33:36 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 04 Sep 2003 05:33:36 -0600 Subject: Writing solid code book In-Reply-To: <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> References: <b15d2792.0309030339.3ac939e7@posting.google.com> <87wucqni5j.fsf@pobox.com> Message-ID: <5.2.1.1.0.20030904052221.02fccdf8@66.28.54.253> At 10:00 PM 9/3/2003 -0600, you wrote: >[snip] >My "Software Engineering" class votes again tomorrow on the language we use >for our group project. Tuesday's vote was Java (8 votes), Python (5), C++ >(3), and Smalltalk (1); Thursday's vote will be between Java and Python. I >get the opportunity to learn one or the other in a week. Does your class want to learn Software Engineering or does it want to learn a language. If the focus is on learning Software Engineering and the learning of a language is to support that, the less effort you have to put into learning (and using) the language the more time and energy you'll have to learn and apply engineering concepts. One of the first "productivity languages" was APL. One could solve problems in a fraction of the time it took in FORTRAN etc. In the early 1970s a college class was given a term project - write a program to solve something related to the course subject. Some students wrote the APL solution and turned it in the following day. The prof was pissed that they had done it so easily, and forbade the use of APL for the assignment! So beware of choosing Python. It might make the class too easy. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From dario at fga-software.com Fri Sep 5 10:32:45 2003 From: dario at fga-software.com (ProgDario) Date: 5 Sep 2003 07:32:45 -0700 Subject: Creating a PyFunction References: <67a857cc.0309050211.add7137@posting.google.com> Message-ID: <67a857cc.0309050632.1b00bdbe@posting.google.com> dario at fga-software.com (ProgDario) wrote in message news:<67a857cc.0309050211.add7137 at posting.google.com>... > Hello, > > I have a simple question I can't find on the FAQ. > > I want to instantiate a PyFunction from a Java class, but the function > is on a jython file (script1.py). > > How can I get a PyFunction object referencing the function in the > external file? > > Then, how can I call the function (__exec__ method ?) passing in an > argument? > > Thanks in advance > > Dario I found the solution, it's been emailed me from Jeff Emanuel The complete code follows: import java.io.*; import java.util.*; import java.text.*; import org.python.util.PythonInterpreter; import org.python.core.*; public class Calculate { public static void main(String[] args){ PythonInterpreter interp = new PythonInterpreter(); interp.execfile("script1.py"); PyFunction func = (PyFunction)interp.get("calculate",PyFunction.class); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh.mm.ss"); System.out.println("======[" + sdf.format(new Date()) + "]==========="); for (int i=1 ; i<10000 ; ++i) { // Assuming calculate takes a float argument. func.__call__(new PyFloat(i)); //interp.eval("calculate(" + i + ")"); } System.out.println("======[" + sdf.format(new Date()) + "]==========="); } } From anthony at interlink.com.au Thu Sep 11 07:05:41 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 11 Sep 2003 21:05:41 +1000 Subject: TTF fonts rendered in Python In-Reply-To: <bjp95u$nn3$1@news-reader3.wanadoo.fr> References: <bjp95u$nn3$1@news-reader3.wanadoo.fr> <mailman.1063224795.24414.python-list@python.org> Message-ID: <200309111105.h8BB5fxK012483@localhost.localdomain> >>> Eric Brunel wrote > If you want something a bit lighter than PyGame or PIL, there's also gd with > gdmodule: > http://newcenturycomputers.net/projects/gdmodule.html > http://www.boutell.com/gd/ Does the gdmodule support TrueType fonts? I didn't think it did... hmm, references to FreeType in the docs, so I guess it must support them now. Anthony -- Anthony Baxter <anthony at interlink.com.au> It's never too late to have a happy childhood. From daniel.dittmar at sap.com Tue Sep 23 05:32:59 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 23 Sep 2003 11:32:59 +0200 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <SnObb.1581$PT3.257319@news20.bellglobal.com> <eppstein-E0F40C.21003222092003@news.service.uci.edu> <cthvmvk3uif5qt1hkftmp2hbdia74fjq3d@4ax.com> Message-ID: <bkp40c$j0o$1@news1.wdf.sap-ag.de> Stephen Horne wrote: > for i in int [0:10:2] : > ... > > that is, allow the 'int' type object to be sliced, and return an > iterator as the result - not just for the for loop, but generally > (though optimising the 'for' loop usage to avoid physically creating > the iterator might be a good idea). Adding operators to types is always problematic because it defeats Pythons's runtime checking. Assuming that integer slicing would be added to Python, methods that would expect a list of integers would suddenly also work with integers. In most cases, they would not work correctly, but you wouldn't get a meaningful exception. > Also, one extra feature is that the loop can be infinite (which range > and xrange cannot achieve)... > > for i in int [0:] : > ... > if condition : break > ... I'm sure that you can think of a generator function that does exactly the same. Daniel From max at alcyone.com Wed Sep 10 15:59:33 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 10 Sep 2003 12:59:33 -0700 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> Message-ID: <3F5F82A5.7DB9A717@alcyone.com> achrist at easystreet.com wrote: > The yield statement looks to be a big step toward some kind of > lightweight concurrency-oriented programming in python. Is there > any similarly nice way to do the opposite of yield, just sit around > (perhaps in the middle of a loop) and wait until some other routine > (unknown to the waiting module) hurls a value in? Yep: generator.next() -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Dead men have no victory. \__/ Euripides From bokr at oz.net Mon Sep 29 21:33:05 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Sep 2003 01:33:05 GMT Subject: Wavelet package available? References: <2ceb70f8.0309290136.118a856d@posting.google.com> <z4adnU-lwpqa1eWiU-KYjA@comcast.com> <bla6kk$mps$1@reader10.wxs.nl> Message-ID: <blamgh$n6n$0@216.39.172.122> On Mon, 29 Sep 2003 23:03:44 +0200, "gez" <gez_75 at hotmail.com> wrote: [previously top_posted text moved] >"Terry Reedy" <tjreedy at udel.edu> wrote in message >news:z4adnU-lwpqa1eWiU-KYjA at comcast.com... >> >> "Gez" <gez_75 at hotmail.com> wrote in message >> news:2ceb70f8.0309290136.118a856d at posting.google.com... >> > Does anyone know if there is a wavelet package available for Python? >> > This package should at least have the Daubechy wavelet. >> >> Before posting a question like this and waiting hours for a reply, one >> should try a search engine like Google. In this case, "Python >> wavelets" >> >> If this fails, then post question and note what you tried without >> success. This tells responders both that you made an effort and also >> what they should not waste time on in trying to help you. >> >> Teaching-you-to-fish-ly yours, >> >> Terry J. Reedy >> >> > > <previously_top_posted> >Why this stupid answer? I tried to find python in combination with wavelets, >both in the normal Google search engine and the Google groups search. Also >jpython/jython, etc. but non of the results was what I wanted to use. So, >that is why I posted it here. Think this is exacly the place to be... > Right, but the compulsively helpful probably went off duplicating your search, which you could have prevented or gotten a better refinement from, instead of this round of "oh, well in that case, ..." >Looked at wavelets.org, looked for Java implementations,etc.etc. > >Btw, I once wrote a wavelets (de)composition in Delphi and C++Builder. And >fyi, I looked up the faq. So, I am not a novice at all in this field, but I >just need a version in Python which I couldn't find. > So how different do you think the response would have been if you had started with this background info in your post? >So, please, think before you write such an answer. Not everybody is as >stupid as you think. Look in the mirror and say that, but think in terms of social stuff ;-) And please don't top-post (ok, it could have been worse, at least you didn't post HTML ;-) > >And even then. If someone doesn't know the correct search keywords for use >in Google, this place is still the place to be. Right again. So, > >So please be more kind to the next poster that (in you eyes) posts a stupid >question. > And you please be more kind to the compulsively helpful, so that they can help you and others better, not waste their time on stuff you could easily steer them away from by mentioning more context. Doing so also gives you a chance to head off replies you might take as implying you're stupid, if you're prone to reading things that way ;-) </previously_top_posted> BTW, if you find some python wavelet stuff, I'd be interested to see it too ;-) Regards, Bengt Richter From davidcfox at post.harvard.edu Tue Sep 23 17:05:29 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 23 Sep 2003 21:05:29 GMT Subject: idle import problem In-Reply-To: <mailman.1064343872.24060.python-list@python.org> References: <49799.199.169.240.132.1064335411.squirrel@svr1.turboweb.net> <200309231952.43835.andy@wild-flower.co.uk> <mailman.1064343872.24060.python-list@python.org> Message-ID: <tA2cb.560001$o%2.245217@sccrnsc02> Matthew Wilson wrote: > Thanks - > > That's really useful. I know how to set PYTHONPATH in unix, but how to in > windows? > > Depends on the version. In Win9x, you put SET PYTHONPATH=dir1;dir2;dir3 etc. in AUTOEXEC.BAT, though that won't take effect until you reboot. To get it to take effect the next time you start Python, use WINSET from a DOS window instead (which doesn't affect the current DOS shell, but does affect ones you open after you set it). Note that WINSET is only temporary (until you restart Windows) In WinXP, you can set environment variables by going to the Advanced tab of the System item in the Control Panel, and clicking the Environment Variables button. If you want to set a PYTHONPATH specific to your user, set it as a User variable. If you want it to apply to all users, set it as a system variable (you'll need Admin privileges to do so). David From nowan.noware at nohowe.net Thu Sep 4 23:41:15 2003 From: nowan.noware at nohowe.net (Nowan) Date: Fri, 05 Sep 2003 03:41:15 GMT Subject: spyce hangs on 'file not found' Message-ID: <3F5804CE.3050109@nohowe.net> Hi, I'm running Win 2K Pro Apache 1.3 (IBM version, starting manually, not a service) Spyce 1.3.11 (latest version) Python 2.2.2 (ActiveState) Everything installed as an administrator. Brand new to both Python and Spyce, got some python CGIs working, and the Spyce examples. Altered httpd.conf to so Spyce would handle entire contents of /template/ directory. (Spyce's standard config is to handle based on file extension. Want my templates to have an. html extension for ease of use with other tools.) Works fine, except when I attempt to read a nonexistent file. In other words, I go after /template/stuff.html but stuff.html doesn't exist. Ordinary CGIs work correctly, meaning Apache correctly handles a 'file not found' Spyce works differently. The browser hangs. My CPU utilization goes to 100% and I get a runaway python process I can't kill, even as administrator. Any suggestions? A python bug or a spyce bug? Reading the source for either is way beyond my level now? Known problem? Workaround? Anyone know how I can kill the runaway python process? thanks From paddy3118 at blueyonder.co.ukNOTthisBIT Mon Sep 1 03:28:36 2003 From: paddy3118 at blueyonder.co.ukNOTthisBIT (Donald 'Paddy' McCarthy) Date: Mon, 01 Sep 2003 08:28:36 +0100 Subject: PyXR 0.9.3- Cross-Referenced HTML from Python Source In-Reply-To: <mailman.1062354602.22785.python-list@python.org> References: <mailman.1062354602.22785.python-list@python.org> Message-ID: <3F52F524.1040308@blueyonder.co.ukNOTthisBIT> logistix wrote: > PyXR 0.9.3- Cross-Referenced HTML from Python Source > > PyXR generates HTML pages from python source files. It also generates > cross-referenced hyperlinks and integrates with the Python Library > Reference as well, which makes it distinctive from the 8 million other > prettyprinters out there. It's been tested on 2.3 for Windows, OpenBSD > 3.2 and RedHat 7.3. There's no reason it shouldn't work on other > platforms with minor configuration. > > 0.9.3 is a minor release. It was primarily issued as an "official" > 2.3-compatible release, although previous versions should run on 2.3 as > well. Other features include: > - Per-line-number hyperlinks, to make emailing source code > references easier and more accurate. > - Upgrade of the PyXR'ed source on my website to 2.3's standard > library. > > A PyXR'ed version of Python 2.3's source can be viewed at: > > http://www.cathoderaymission.net/~logistix/PyXR/python23/src/ > > More information about PyXR itself is available at: > > http://www.cathoderaymission.net/~logistix/python/pyxr.html > > The package is available at: > > http://www.cathoderaymission.net/~logistix/python/PyXR.zip > > Enjoy! > > This reminds me of my favourite x-to-html tool v2html: http://www.burbleland.com/v2html/v2html.html Check it out, it may give you some more ideas on navigating large programs as web pages. Cheers, Pad. From emile at fenx.com Tue Sep 30 16:11:14 2003 From: emile at fenx.com (Emile van Sebille) Date: Tue, 30 Sep 2003 13:11:14 -0700 Subject: Prime number module References: <Xns9405ABFC8A4D3dagvelvetnet@195.67.237.51> <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> <R1Je/kKkXcId092yn@gnosis.cx> <mailman.1064870619.795.python-list@python.org> <blbupn$pf6$0@216.39.172.122> <mailman.1064945567.4139.python-list@python.org> Message-ID: <blcns9$atqph$1@ID-11957.news.uni-berlin.de> "Lulu of the Lotus-Eaters" <mertz at gnosis.cx> wrote: > Along those lines, what's the quickest way to count bits in Python? > Maybe someone has a clever idea... something that would run a whole > bunch faster than my bit mask style above for counting all the "1"s in a > multibyte string. > Probably far from the fastest, but in the tradition that you'll get a better answer by posting, here's a stab at a python method for counting bits: import string,time nibbles = [(w+x+y+z, w*8+x*4+y*2+z) for w in (0,1) for x in (0,1) for y in (0,1) for z in (0,1)] bitcounts = [ (chr(hinibblevalue*16 + lonibblevalue), hibitcount+lobitcount) for hibitcount, hinibblevalue in nibbles for lobitcount, lonibblevalue in nibbles ] bytes = dict(bitcounts) xlater = "".join([chr(bitcount) for byte, bitcount in bitcounts]) def bitcount1(bytestr): return sum([bytes[ii] for ii in bytestr]) def bitcount2(bytestr): return sum(map(ord, string.translate(bytestr,xlater))) t=time.time() bitcount1('a'*100000) print time.time()-t t=time.time() bitcount2('a'*100000) print time.time()-t -- Emile van Sebille emile at fenx.com From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 03:38:08 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 08:38:08 +0100 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> <IKScnUNBOsX4MumiU-KYgA@comcast.com> Message-ID: <bqeanvgel9ra3va44j090bmn2l126t340g@4ax.com> On Fri, 26 Sep 2003 17:28:02 -0400, "Terry Reedy" <tjreedy at udel.edu> wrote: > >"Roberto A. F. De Almeida" <roberto at dealmeida.net> wrote in message >news:10c662fe.0309261245.1f35f43a at posting.google.com... >> I found that when using negative indices, the slice object passed to >> __getitem__ depends on the number of slices. An example to clarify: >> >>class a: >> def __getitem__(self, index): >> return index >> >> >>> b = a() >> >>> print b[:-1] >> Traceback (most recent call last): >> File "<stdin>", line 1, in ? >> AttributeError: a instance has no attribute '__len__' >> >> But if I pass a "multiple" slice: >> >> >>> print b[:-1,:-1] >> (slice(None, -1, None), slice(None, -1, None)) > >A square-bracketed subscript (index/key) is a *single* object, in this >case a tuple. The contents of the tuple are irrelevant (for this >code). Any tuple will be echoed: I didn't see any sign that he wasn't aware of that. I would have expected, given that the tuple contains slice objects constructed from the multiple-slice notation, that the same translations would be performed on the slices that are inserted into the tuple that are applied when the single slice is created. That is, whether the single or multiple notation is used, and whether the slice objects are placed in a tuple or not, they are constructed from the tuple notation - the translation from notation to slice object should be done consistently. Actually, the translation done in the single case worries me - an extension module I wrote a while ago should not work if this is the case (as the slice is based on associative keys, not subscripts, so the negative subscript trick doesn't apply). I'd better do some testing, I suppose :-( >What you probably want is b[:-1][:-1], etc. Each index must be >separately bracketed to access items in list of lists (etc). Maybe. Maybe not. I assumed he was doing something similar to what happens in numeric - they do some rather interesting slicing-of-multidimensional-container things over there. Of course I'm not a numeric user, so I may be misunderstanding things. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From tina_li23AThotmailDOTcom Tue Sep 23 11:40:18 2003 From: tina_li23AThotmailDOTcom (Tina Li) Date: Tue, 23 Sep 2003 11:40:18 -0400 Subject: Bottleneck? More efficient regular expression? Message-ID: <3f7069db_4@corp.newsgroups.com> Hello, I've been struggling with a regular expression for parsing XML files, which keeps giving the run time error "maximum recursion limit exceeded". Here is the pattern string: r'<code>(?P<c>.*?)</code>.*?<targetSeq name="(?P<tn>.*?)">.*?<target>(?P<t>.*?)</target>.*?<align>(?P<a>.*?)</align>.*?<template>(?P<temp>.*?)</template>.*?<an otherTag>(?P<at>.*?)</anotherTag>.*?<yetAnotherTag>(?P<yat>.*?)</yetAnotherTag>' The file format is straighforward. Here is a sample: <code>1cg2</code> <chain>a</chain> <settings>abcde</settings> <scoreInfo>12345</scoreInfo> <targetSeq name="1onc">blah </targetSeq> <alignment size="335"> <target>WLTFQKKHITNTRDVDCDNIMS</target> <align> :| ..| : . | . |. . :</align> <template>QKRDNVLFQAATDEQPAVIKTLEKL</template> <anotherTag>foobarfoobar</anotherTag> <yetAnotherTag>barfoobarfoo</yetAnotherTag> # this group of tags then repeat in the file multiple times If I search for the pattern up to "</template>" (i.e. no <anotherTag> onwards), it works fine. As soon as I added the later bits into the pattern it gives the error. I heard that non-greedy (*?) is inefficient, so I tried replacing all .*? with (?!<target>) etc. which means "if the the next piece of text doesn't match the <target> tag keep going". But it gives the same error. So my question is: what is the bottleneck in this pattern? Could someone more experienced in REs give some hints here? Your help is greatly appreciated! Tina -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From mertz at gnosis.cx Tue Sep 30 17:46:13 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 30 Sep 2003 17:46:13 -0400 Subject: Prime number module References: <Xns9405ABFC8A4D3dagvelvetnet@195.67.237.51> <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> <R1Je/kKkXcId092yn@gnosis.cx> <mailman.1064870619.795.python-list@python.org> <blbupn$pf6$0@216.39.172.122> <mailman.1064945567.4139.python-list@python.org> <5Mmeb.146562$hE5.4972915@news1.tin.it> Message-ID: <lmfe/kKkXEPd092yn@gnosis.cx> |Lulu of the Lotus-Eaters wrote: |> Along those lines, what's the quickest way to count bits in Python? Alex Martelli <aleax at aleax.it> wrote previously: |Probably gmpy's popcount function. What about fast AND portable? (I'm sure gmpy can be installed lots of places, but not necessarily by receivers of Python code). Yours, Lulu... -- _/_/_/ 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 jdhunter at ace.bsd.uchicago.edu Mon Sep 15 10:05:15 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 15 Sep 2003 09:05:15 -0500 Subject: [Python] gdmodule true type font size In-Reply-To: <000b01c37a7c$b31d96a0$1f00000a@Belkin> ("Chris Gonnerman"'s message of "Sat, 13 Sep 2003 23:57:28 -0500") References: <m2r82ky473.fsf@mother.paradise.lost> <000b01c37a7c$b31d96a0$1f00000a@Belkin> Message-ID: <m2wuca171g.fsf@mother.paradise.lost> >>>>> "Chris" == Chris Gonnerman <chris.gonnerman at newcenturycomputers.net> writes: Chris> No. The underlying GD library assumes 1 point is exactly 1 Chris> pixel. Font metrics are pretty fuzzy, so your mileage may Chris> vary slightly especially with script fonts. That helps thanks ... Chris> You've got me here. Perhaps if I knew what you were trying Chris> to accomplish at a bit higher level, I might be able to Chris> make a suggestion. That's OK, I think I have this figured out. The one point/one pixel info was enough to speed me on my way. JDH From tzot at sil-tec.gr Mon Sep 29 19:20:28 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 02:20:28 +0300 Subject: Python question References: <mailman.1064873081.7223.python-list@python.org> Message-ID: <22fhnvseimhu2hi5vu7aphhr52ee8724nc@4ax.com> On Mon, 29 Sep 2003 15:03:34 -0700, rumours say that "John D." <lists at webcrunchers.com> might have written: >#This program gives: "SyntaxError: unqualified exec is not allowed ># in function _ it contains a nested function with free variables" > >#I understand this is a scope problem(?) >#I don't understand why this fails. It should be perfectly obvious >#what z is equal to when exec sees it. Furthermore, it shouldn't care >#about any other variables since it uses no others, and writes to none. > >#What does this mean? What is "unqualified" and how do I qualify it? Use 'exec <something> in <globals_dic>, <locals_dic>' to 'qualify' the exec, otherwise it uses the locals of the function. See http://www.python.org/doc/ref/exec.html . >#Are the free variables d or z? d is the free var (it's used by the setvar nested function). It doesn't matter if you don't reference it in the exec statement, because it can be accessed by the locals() dict whose use is implied by the 'unqualified' exec statement. >Is 'free' a boolean state or are there >#other related qualities? A variable is either free or not; so you can call 'free' a boolean state, but this is an abstraction about which you shouldn't care. See http://www.python.org/doc/ref/naming.html >#What are the various work-arounds? Already answered. >#I am using d as a global dictionary to store all my variables. > >d={} #Doesn't matter if I have d here # it doesn't >def myfunc(): > z='print' > exec(z) > d={} #or here... # it does, because of the next two lines > def setvar(): > d[0]=1 > return -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From oblivious at web.de Tue Sep 23 04:55:14 2003 From: oblivious at web.de (Dominic) Date: Tue, 23 Sep 2003 10:55:14 +0200 Subject: Mailbox cleaner on an IMAP basis? In-Reply-To: <3f6f2cfb@news.swissonline.ch> References: <3f6f2cfb@news.swissonline.ch> Message-ID: <bkp25n$vg4$00$1@news.t-online.com> > server for mails having attached EXE files and delete all those mails on the > server. This would save me a lot of traffic over my phone line connection. I use a Python script which is run via cron every hour on a machine with internet connectivity. It downloads all mails, parses them and does whitelist filtering but could be easily extentend. All filtered mails are removed from the mailbox and stored locally. This mbox file can then be retrieved by scp/ftp. Cleaning only every hour has proved to be enough. Since my script has been running without any trouble for almost half a year I thought it may be a basis for ideas or customizing, so I'll append it to this posting. Ciao, Dominic P.S. You'll need the tpg-parser generator for Python. -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 5921 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20030923/25b47c93/attachment.py> From gherron at islandtraining.com Mon Sep 29 18:04:32 2003 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 29 Sep 2003 15:04:32 -0700 Subject: error explanation In-Reply-To: <13df83a2.0309291345.32db8a2b@posting.google.com> References: <13df83a2.0309291345.32db8a2b@posting.google.com> Message-ID: <200309291504.32704.gherron@islandtraining.com> On Monday 29 September 2003 02:45 pm, Mac Wood wrote: > Could someone please explain this error message: > > Traceback (most recent call last): > File "C:\Python23\time.py", line 1, in -toplevel- > time.py > NameError: name 'time' is not defined > > I tried entering the following example: > > time.py > #This programs calculates rate and distance problems > print "Input a rate and a distance" > rate = input("Rate:") > distance = input("Distance:") > print "Time:",distance/rate > > which according to the tutor should have run as this: > > python times.py > > Input a rate and a distance > Rate:5 > Distance:10 > Time: 2 > Thanks for your help The line "time.py" is not meant to be a python statement, but is the name of the file whose contents are the succeeding lines. Once you get the file named "time.py" with this contents #This programs calculates rate and distance problems print "Input a rate and a distance" rate = input("Rate:") distance = input("Distance:") print "Time:",distance/rate then you can run the file with python time.py Gary Herron From fuerte at sci.fi Tue Sep 16 13:22:41 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Tue, 16 Sep 2003 20:22:41 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <mailman.1063660337.3320.python-list@python.org> References: <5.1.1.6.0.20030911162016.02027750@telecommunity.com> <mailman.1063342640.29560.python-list@python.org> <ipicnag7OpxdLfyiRTvUpQ@speakeasy.net> <Hqk8b.382$BS5.239@newsread4.news.pas.earthlink.net> <V_mdnZ3eKoGjif6iRTvUpQ@speakeasy.net> <3F632226.2010607@earthlink.net> <lcydnasf88GLyP6iRTvUrg@speakeasy.net> <EIL8b.6564$ZB4.1083@reader1.news.jippii.net> <f575e202.0309151024.2b7981ea@posting.google.com> <mwo9b.242$B13.103@reader1.news.jippii.net> <mailman.1063660337.3320.python-list@python.org> Message-ID: <5CH9b.81$2k.16@reader1.news.jippii.net> Jeff Epler wrote: > Harri, > I don't understand how your suggested changes, even once carried out, > will let me use threads to increase the speed of a CPU-intensive Python > program. For instance, consider the following code: > > solutions = [] > > def is_solution(l): > # CPU-intensive code here. Let's say it runs for 1 second per call > > def consider_solution(l): > if is_solution(l): > solutions.append(l) > > def problem_space(l): > # A generator of items in the problem space > # pretty fast! > ... > yield l > > def all_solutions(): > for l in problem_space: > consider_solution(l) > > > I could thread it, so that N threads each run is_solution on a different > candidate: > def all_solutions(): > queue = worker_tasks(consider_solution, N) > for l in problem_space: > queue.add(l) > queue.shutdown() > > But with your proposed changes, it sounds like each thread becomes an > island, with no access to common objects (like the list "solutions" or > the queue connecting the main thread with the worker threads). > If threading truly worked, then I'd be able to run efficiently on n*1 > CPUs, where n is the ratio of the speed of one iteration of is_solution > compared to one iteration of problem_space. > > On the other hand, I can make the above work quickly today by using > processes and pipes. I can do this only because I've identified the > parts that need to be shared (the queue of candidate solutions, and the > list of confirmed solutions). I think that's the same level of effort > required under the "thread is an island" approach you're suggesting, but > the processes&pipes code will likely be easier to write. I mostly agree with what you said. Another approach to shared memory access is to have a special syntax or functions that do it. These functions could do internally just what you said, use pipes, or whatever. Each thread could have a name, a string, and then we could have a couple of simple built-in functions to send messages (strings) from thread to thread, peek messages, and wait for messages. One message would have a special meaning of Quit, so that the thread knows when to stop. Bascially this is all that is needed for these independent threads. Another approach would be the separate shared interpreter state, access to which would be synchronized. This is probably much harder to implement, but it would be more beautiful, you could have there all different objects like in normal non-threaded Python. So if you have two threads, you would have three independent interpreter states (one shared). It is more efficient to have one process and several threads, than several processes each having one thread. Harri From oblivious at web.de Sat Sep 27 04:57:53 2003 From: oblivious at web.de (Dominic) Date: Sat, 27 Sep 2003 10:57:53 +0200 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) In-Reply-To: <3F74A1E7.5040102@web.de> References: <mailman.1064390741.20344.python-list@python.org> <3F71B857.2D1E3268@engcorp.com> <Xns9400E70CB6F9Fcliechtigmxnet@62.2.16.82> <3F720759.34D7BD3E@engcorp.com> <3F720D28.83C3E99@engcorp.com> <noCcb.119695$hE5.4100692@news1.tin.it> <3F731B17.61C17B3A@engcorp.com> <bkvbb5$6mi$00$1@news.t-online.com> <TXTcb.124120$hE5.4241274@news1.tin.it> <3F74A1E7.5040102@web.de> Message-ID: <bl3jdk$1ui$00$1@news.t-online.com> I have used Python 2.3 which is probably the reason. I'll try it with 2.3.1 again. Ciao, Dominic From peter at engcorp.com Fri Sep 19 13:41:51 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Sep 2003 13:41:51 -0400 Subject: \r for newline in readlines function References: <C497480353EF904FBF7A8B0851E5422CCB570A@MAIL002.AD.MLP.COM> <mailman.1063990288.1776.python-list@python.org> Message-ID: <3F6B3FDF.C1BA47A4@engcorp.com> Bob Gailer wrote: > > At 10:37 AM 9/19/2003, Leeds, Mark wrote: > > > I did more investigation into my previous problem > > and what happens is that my text file has \r for representing > > a new line instead > > of a \n. is there a way to tell the readlines > > function that the symbol for a newline is \r rather > > than \n ? right now the readlines function reads > > the\r as another item in the list and just puts > > everything into one big list because it > > doesn't find any new line characters. > > thanks. i'm really stuck because > > i can't read my data right now. > > bigList = foo.readlines() > niceList = bigList.split('\r') I think Bob means foo.read() instead, since otherwise the result is a list which won't respond to the .split() call well. -Peter From simonb at webone.com.au Thu Sep 11 00:48:48 2003 From: simonb at webone.com.au (Simon Burton) Date: Thu, 11 Sep 2003 14:48:48 +1000 Subject: metaclasses for type comparison References: <pan.2003.09.11.01.50.58.897682@webone.com.au> <GBR7b.415613$uu5.75083@sccrnsc04> Message-ID: <pan.2003.09.11.04.48.46.966122@webone.com.au> On Thu, 11 Sep 2003 03:03:02 +0000, David C. Fox wrote: ... >> B < A # should be True > > Is this an exercise to help you learn about metaclasses, or do you > actually want to be able to check whether B is a subclass of A. If the > latter, then try issubclass(B, A). Otherwise, ignore this comment > > David Both. Well, aha, "issubclass" makes my implementation of ge/le and friends a bit silly. Actually i was annoyed with "isinstance", it seems like it should be part of the syntax (eg."<="). Look at this: "issubclass". It has 10 chars!! Lazy when i can be, Simon Burton. From newsgroups at jhrothjr.com Tue Sep 23 12:38:45 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 23 Sep 2003 12:38:45 -0400 Subject: Thoughts on PEP315 References: <oalumvopu9afuhno85tbp2erl52rk9hht1@4ax.com> <vmv9hsp53qfi18@news.supernews.com> <medvmv0af0nsr2pkgm2fhtaq5iphtthamo@4ax.com> <t2l0nv8914nfnmbtl65265sfut8dujt40f@4ax.com> Message-ID: <vn0tpei7t9vjd8@news.supernews.com> "Tim Rowe" <tim at remove_if_not_spam.digitig.co.uk> wrote in message news:t2l0nv8914nfnmbtl65265sfut8dujt40f at 4ax.com... > On Tue, 23 Sep 2003 04:39:14 +0100, Stephen Horne > <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: > > >On Mon, 22 Sep 2003 21:47:05 -0400, "John Roth" > ><newsgroups at jhrothjr.com> wrote: > > >>do: > >> bibbity > >> bobbity > >> boo > >> while condition # note the lack of a colon! > > > >Yuck!!! > > > >This is really no different to the following, which is quoted in the > >PEP as something to move away from... > > > > while True : > > ... > > if condition : break > > ... > > > >The fundamental problem is that the exit point is not obvious because > >it is 'hidden' in the detail of the loop - it is a statement within > >the loop body instead of being lexically a part of the loop. > > It is very different indeed. In the second case stuff can go after > the "if condition: break", so the terminating condition is potentially > buried in the surrounding code. On my reading of John's proposal > nothing can go after the "while condition", so the end is clearly > marked in the Python way by the indentation dropping back a level. Thanks, Terry. That's exactly what I meant to convey. > What I /don't/ like about it is the overloading of the "while" > keyword. I would much sooner reverse the condition and use "until", > though I realise the back-compatibility issues of introducing new > keywords. That's always a problem, although my understanding of the objectives for 2.4 is that there will probably be a number of new keywords, so one more won't make a significant difference. 2.3 was supposed to avoid adding them. My major objection is that I don't think there's enough usage to justify the additional complexity, regardless of whether we can come up with a clean, Pythonic way of expressing it. John Roth > From Scott.Daniels at Acm.Org Sun Sep 21 19:01:43 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 21 Sep 2003 16:01:43 -0700 Subject: Help me choose a C++ compiler to work with Python In-Reply-To: <3F6DDFFD.4988E66A@engcorp.com> References: <616fccba.0309210907.1e35b92d@posting.google.com> <3F6DDFFD.4988E66A@engcorp.com> Message-ID: <3f6e2dd6$1@nntp0.pdx.net> Peter Hansen wrote: > rhmd wrote: >>I use Windows XP and 98. Have very little experience with C++. Am >>doing statistical and other simulations that require billions of >>calculations > > Have you considered and investigated Numeric Python or similar > products? Perhaps your assumption that you have to revert to > hand-crafted C code is premature. > > -Peter Look at the enthought Python installation (one is available for each of 2.2 and 2.3) -- they not only install a slew of the packages you might need for calculation heavy Python use, but (to support weave, I believe), they also include a mingw32 compiler (minimal gnu win32) which you can use for C++. If you get to the point where you are optimization-bound on your compiler (which you should determine by measuring, not intuiting), you could do worse than the Intel compiler. -Scott David Daniels Scott.Daniels at Acm.Org From vze4rx4y at verizon.net Tue Sep 23 01:13:11 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 23 Sep 2003 05:13:11 GMT Subject: Need arguments for "Python vs. Perl as an OOPL" References: <roy-002696.23242122092003@reader2.panix.com> Message-ID: <HDQbb.8077$hL1.2233@nwrdny01.gnilink.net> "Roy Smith" <roy at panix.com> wrote in message news:roy-002696.23242122092003 at reader2.panix.com... > I'm working on a prototype of a new application in Python. At some > point, if this ever turns into a product, the powers that be will almost > certainly demand that it be done in Perl. My job will be to convince > them otherwise. > > The basic design of the application is object oriented. I've never used > Perl's OO features, so I'm not in a good position to make a comparison > of the two languages from an OO point of view. Can somebody who's done > OOP in both Python and Perl help me out? > > I certainly know why Perl sucks in general, but for this purpose, I need > to specifically compare the OO features of the two. I'm looking for > something more fundamental than "->{} is ugly". If you're to find a major difference in OO implementations, it will likely be with Python's new style classes. So, the advantages are: * easy implementation of metaclasses through __metaclass__ * super() for cooperative superclasses * a method resolution order that supports cooperative superclasses and complex inheritance hierarchies * __slots__ for lightweight instances * o.__getattribute__ for easy intercepts of method calls and attribute lookup * descriptors which make easy work of otherwise hard tasks * the fruits of descriptors: class methods, static methods, and properties (which make it possible to avoid coding many getters and setters). Other than the new-style gizmos, it's mostly the same candy in a different wrapper. Raymond Hettinger From guettli at thomas-guettler.de Mon Sep 8 11:08:56 2003 From: guettli at thomas-guettler.de (Thomas Guetttler) Date: Mon, 08 Sep 2003 17:08:56 +0200 Subject: xml.sax: Raising Exception with line number of xml source Message-ID: <pan.2003.09.08.15.08.55.650463@thomas-guettler.de> Hi! How can I raise an exception while parsing with sax, which contains the current line in the xml-file? I want to create an message like this: test.xml: Line: 100, Col: 20: <foo> not allowed in <bar> I have the filename in my content handler. I just need the line und column number. thomas From bdesth.nospam at removeme.free.fr Tue Sep 16 17:45:21 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Tue, 16 Sep 2003 23:45:21 +0200 Subject: why pass statement? In-Reply-To: <A_J9b.13307$x21.750@twister.southeast.rr.com> References: <iRI9b.12996$x21.4462@twister.southeast.rr.com> <vmeq2go7e7fq62@news.supernews.com> <A_J9b.13307$x21.750@twister.southeast.rr.com> Message-ID: <3f6781c2$0$28881$626a54ce@news.free.fr> M-a-S wrote: > > "John Roth" <newsgroups at jhrothjr.com> wrote in message news:vmeq2go7e7fq62 at news.supernews.com... > >>You don't actally need Pass. A docstring is sufficient: >> >>class C: >> "this is a class" >> >>while True: >> "loop de loop de loop" >> > A good idea! Thanks! Not a so good idea, since the pass statement is explicit (and explicit is better than implicit). My 2 explicit eurocents Bruno From bobx at linuxmail.org Wed Sep 17 05:12:57 2003 From: bobx at linuxmail.org (Bob X) Date: Wed, 17 Sep 2003 09:12:57 GMT Subject: Computer Programming for Everybody, a Newbie Project References: <mailman.1063781063.16709.python-list@python.org> Message-ID: <tAV9b.181$qK1.218658@news2.news.adelphia.net> "Arthur" <ajsiegel at optonline.net> wrote in message news:mailman.1063781063.16709.python-list at python.org... > Ron asks - > > >Any other ideas would be appreciated. Meanwhile, I would be interested > >if anyone would offer thoughts on which of the 5 directions for future > >activity sound most interesting. > > Sorry Ron. > > Can you remind me what the connection to CP4E is, and why you are headlining > that slogan in connection with your work. > > You, as did I with my own project, with sustained effort over a three year > period - starting, let's say from scratch - produced something of which > each of us can hopefully be rightfully proud. > > Three years of sustained effort. > > But we seemed to have taken away different lessons. > > My expereince led me to look upon the CP4E slogan quite askance. Yours, > apparently, allowed you to embrace it. > > It seems to me "everybody" who's imagination is ignited by something to the > extent that it carries them through 3 years of sustained effort can expect > to be doing "computer programming" somewhere along that line. > > Not very surprising, really. > > No slogans helped me along - that I do know. > > It was three years of sustained effort. > > For everybody? > > Are we *required* to embrace that notion? > > Yes everybody - let's say - has that potential. But that was true before > Python came along. > > For some - like myself - Python was a real factor in helping realize that > potential. I am a raving fan, in fact. > > But I do not discount my 3 years of sustained effort as anything less than 3 > years of sustained effort, and seem to think that that was a bit of factor, > as well. > > And would love to see the CP4E slogan go away now, peacefully and happily. > > Art > You sir, are a rambling man. A rambler I say! From tim.parkin at pollenationinternet.com Sun Sep 7 14:50:18 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 19:50:18 +0100 Subject: Comments on Python Redesign In-Reply-To: <p3idnVDIPrJm5caiU-KYgg@comcast.com> Message-ID: <002601c37570$e815b6f0$0a00a8c0@JASPER> > To the extent that my comments were misdirected and/or unwarrented, I > retract and/or apologize. Thanks for the apology. I do appreciate it. I really want what is best for Python aswell. > Perhaps Python needs two front pages or even two sites. One for the > IT manager types that you seem to be aiming at, who would be impressed > by the corporate look that tends to depress me, and one for > programmers just looking for info. My general intention was to create a developer oriented homepage for people to bookmark in addition to the main www.python.org homepage. Whatever domain this is under (dev.python.org, home.python.org, etc) the main page really has to appeal to suits, senior software engineers, VP's if it is to increase it's serious adoption in industry. If this means a slight compromise in terms of what existing users of the site want (in this case the slight compromise is a more 'glitzy' home page and possibly alternative place to bookmark) then I personally think it's worth it. I normally bookmark the docs page and let the python blogging community/rss feeds fill me in on everything else. Also don't forget there are a lot of people coming from 'commercial' langauges. When they get to the Python site, they judge it by it's appearance. If they are used to a professional designed marketing presentation then they will react negatively to a design that clashes with this. This discussion has had many man days committed to it in marketing-python and we've generally reached a good consensus. > The comments page *is* live, not an image. It was also unusually > painful and difficult for me to read. > I usually don't care too much what people do with their pages. If I > can't read it, I move on to one of the millions of others vying for my > attention. However, python.org is one I visit a lot (top 5, surely) > and I really care about being able to continue reading it. Apologies if you had problems but, as I've said, I don't really have time to apply lots of work to my home page. It's a sign of my commitment to Python that I've been working for 8 weeks on it whilst my own site has been like you see it. Tim Parkin From tzot at sil-tec.gr Thu Sep 11 11:36:31 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 11 Sep 2003 18:36:31 +0300 Subject: Redesign of Python site References: <3F5EB3C1.6020107@teksavvy.com> <200309100540.h8A5epgD030889@localhost.localdomain> <mailman.1063208239.26081.python-list@python.org> Message-ID: <cj51mvobt5it1iq18l1hca38hhor46tbn6@4ax.com> On Wed, 10 Sep 2003 10:35:47 -0500, rumours say that Skip Montanaro <skip at pobox.com> might have written: >I think Fred Drake deserves a raise! OK, let's double his salary :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From llothar at web.de Mon Sep 1 14:31:45 2003 From: llothar at web.de (Lothar Scholz) Date: 1 Sep 2003 11:31:45 -0700 Subject: Traversing the object space. Message-ID: <6ee58e07.0309011031.5e56000b@posting.google.com> Ruby has a nice function that can traverse the complete object space of your program. Is there anything like this in python ? It seems to be not in the standart library but maybe i can find a short script somewhere else. It is a nice way for to do some memory checks to find out if a part of your app is generating too much objects. From jepler at unpythonic.net Tue Sep 2 12:14:46 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 2 Sep 2003 11:14:46 -0500 Subject: what's wrong with REBOL? In-Reply-To: <6005702b.0309020727.4ba46e78@posting.google.com> References: <6005702b.0309020727.4ba46e78@posting.google.com> Message-ID: <20030902161441.GD17554@unpythonic.net> For a language to be "right" for me, it must satisfy a lot of qualities. One of them is some notion of freedom. For instance, will I be left high and dry if I want to use this language on some new device or system architecture? (For instance, when I start buying Itanium or Opteron servers to replace my racks of decrepit Xeons..) Here are two ways I can be pretty sure this won't happen: * Can I have the source code? (C, C++, Python, Perl) I'll port it to my new platform. * Is there already a standard with multiple working implementations? (C, C++, C#, Python) This multiplies the chances that some implementation will be ported to my new platform. As far as I can tell, the Rebol folks don't include source code with any of their licensing options (SDK, etc), and it doesn't look like their documentation gives enough information for a third-party to write their own implementation either. Of course, for those who already rely on single-source software with no source-code availability (*cough*microsoft*cough*), maybe this isn't such a big deal. But having been prevented from upgrading to a modern version of a compiler by a no-source third-party C++ library recently, I don't relish the idea of being reduced to begging for a recompiled version of commercial software again. Jeff From Juha.Autero at iki.fi Wed Sep 17 02:45:05 2003 From: Juha.Autero at iki.fi (Juha Autero) Date: Wed, 17 Sep 2003 09:45:05 +0300 Subject: Can Python Module Locate Itself? References: <VYR9b.1109$c17.866@newssvr24.news.prodigy.com> Message-ID: <87isnrj4lq.fsf@jautero.no-ip.org> sj <_remove_jones57 at swbell.net> writes: > I have written several small shell utilities in Python and typically use > comments at the start of the source file as documentation. A command line > option allows the user to read this documentation. The problem is that I > have to explicitly code the source files location within the source which > is not very portable. Is there anyway for a python module to locate its > own source ? I don't know about locating source, but does the documentation have to be in comments? I think documentation strings exist for this purpose. example.py: """ This is an example file. By using command line argument '-h' user can print this documentation. """ import sys if sys.argv[1] == "-h": print __doc__ -- Juha Autero http://www.iki.fi/jautero/ Eschew obscurity! From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 01:08:06 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 06:08:06 +0100 Subject: Thoughts on PEP315 References: <oalumvopu9afuhno85tbp2erl52rk9hht1@4ax.com> <vmv9hsp53qfi18@news.supernews.com> <r2Qbb.195$eB.185@twister.southeast.rr.com> Message-ID: <18kvmvobs9jsq50o91m35cveu49heev7mh@4ax.com> On Tue, 23 Sep 2003 04:33:27 GMT, "M-a-S" <NO-MAIL at hotmail.com> wrote: >If it was up to me, I would propose > >until <condition>: > <statements> > >as an equivalent to: > ><statements> >while not <condition>: > <statements> If your reason for using 'until' is simply to test for 'while not', then this doesn't make sense. I assume you intend the 'until' to be a postcondition rather than a precondition. Writing this at the start of the loop suggests that it is a precondition (the word 'until' does not automatically imply a postcondition). I want the condition to be written at the location where it is tested - for a postcondition this means the end. Which means you still need something to mark the start of the loop, and you end up with... loop: <statements> until <condition> : Nothing wrong with that in particular of course, but it's not so different to the 'break if' I proposed. No different at all, in fact, except using a different name and... >loop: > <statements> > >for the enless loop, instead of ugly 'while True'. I have no problem with that in principle, except that adding new keywords can be a problem in itself. 'break if' avoids having a new 'until' keyword, and does not require a 'loop' keyword to replace the 'while'. Having a 'loop' keyword could be a good thing or not - it's a different issue. Of course, it might be acceptable to make the condition in the 'while' optional, so you could write... while : <statements> break if <condition> : But then there would be the whole explicit-is-better-than-implicit thing - I seriously doubt it would be accepted. Alternatively... for ever : <statements> break if <condition> : The 'ever' wouldn't need to be a keyword - the lack of the 'in' clearly differentiates it from existing 'for' loops so Python could just validate the identifier name if it finds a colon where it expects the 'in'. You're suggestion of 'loop' certainly looks better than either of these, but my suspicion is that looking good wouldn't outweigh the need to avoid adding too many new keywords ("loop" may be used a lot as an identifier name). -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From guettli at thomas-guettler.de Tue Sep 30 08:46:07 2003 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 30 Sep 2003 14:46:07 +0200 Subject: os.mkdir() not creating . and .. References: <pan.2003.09.30.12.40.50.914979@thomas-guettler.de> Message-ID: <pan.2003.09.30.12.46.07.455836@thomas-guettler.de> Am Tue, 30 Sep 2003 14:40:56 +0200 schrieb Thomas Guettler: > Hi! > > Sometimes os.mkdir() does not create . and .. > > Before the mkdir() I do shutil.rmtree() > > The filesystem is NFS, Linux 2.4.20-4GB (NFS-client) > Python: 2.2.2 > > Anyone seen something like this before? me again: It happens on the shell, too. I seems to be an NFS problem. Not python related. Sorry, Thomas From and-google at doxdesk.com Tue Sep 23 03:31:38 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 23 Sep 2003 00:31:38 -0700 Subject: <?standalone yes?> References: <3f6f32b9@post.newsfeed.com> Message-ID: <2c60a528.0309222331.3c74027@posting.google.com> Lonnie, SRC employee <lonnies at tgf.tc.faa.gov> wrote: > I can figure out how to set the standalone attribute in the <? xml > version="1.0 ?> tag eg <?xml version="1.0" standalone="yes" ?> To set this in DOM terms you would need to use the DOM Level 3 Core property 'xmlStandalone' on the Document object, see: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Document3-standalone However, DOM3 is still in Working Draft (though hopefully not for much longer), and it's not yet supported by minidom. If you don't mind trying a different DOM implementation, this one supports it: http://www.doxdesk.com/software/py/pxdom.html -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From eltronic at juno.com Thu Sep 18 22:10:02 2003 From: eltronic at juno.com (eltronic at juno.com) Date: Thu, 18 Sep 2003 22:10:02 -0400 Subject: Anybody else having problem *sending* mail to this list? Message-ID: <20030918.221008.-448501.0.eltronic@juno.com> On Fri, 5 Sep 2003 11:39:39 -0500 Skip Montanaro <skip at pobox.com> writes: > > Terry> Yes, a worldwide virus-induced mail blizzard. > > This has been my biggest gripe about the damn virus. > The virus itself was > no problem for me since I don't use Windows, [...] > Shouldn't virus scanners simply eat the virus > and not send another mail? its seems an obvious futility to send a notice from a spoofed header. it may be useful to request the steps & reg files necessary to turn off this misfeature from the various virus scanner ceo's. although I hesitate to suggest everyone bounce these notices with yet another email telling admins how to stop contributing to the problem. better idea would be to delay any bounce a few days. instant notification is no help in any case. any notice could be just sent to the postmaster. since nobodys in charge I guess its like too much water, you build a dam or live with the flooding. heres one that gets it, but no solution in sight. "Why (some) anti-virus companies are to blame for the recent e-mail flood" http://www.f-prot.com/news/gen_news/open_letter_10sept2003.html e please forward all spam to "uce at ftc.gov"<help at ftc.gov> ________________________________________________________________ The best thing to hit the internet in years - Juno SpeedBand! Surf the web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From timr at probo.com Thu Sep 11 00:35:30 2003 From: timr at probo.com (Tim Roberts) Date: Wed, 10 Sep 2003 21:35:30 -0700 Subject: datetime: .datetime-.datetime = .timedelta, .time-.time=TypeError ? References: <esuolvc6tuuhfub8jtobffv722281t7p56@4ax.com> <mailman.1063083624.8315.python-list@python.org> <fc0rlv8j6404s4k2l1f2c3ajhvnmjmodf8@4ax.com> Message-ID: <lquvlvs04c6kro7nb5doju93hvcsqhm6s6@4ax.com> Christos "TZOTZIOY" Georgiou <tzot at sil-tec.gr> wrote: >-- >TZOTZIOY, I speak England very best, >Microsoft Security Alert: the Matrix began as open source. Can you please end my suspense and explain what TZOTZIOY means? Some how, "Time Zone Out, Time Zone In, One Year" just doesn't cut it. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mertz at gnosis.cx Wed Sep 10 14:02:14 2003 From: mertz at gnosis.cx (David Mertz) Date: Wed, 10 Sep 2003 14:02:14 -0400 Subject: Slight metaclass confusion References: <fd3e3161.0309090259.eaa3623@posting.google.com> <mailman.1063132305.28723.python-list@python.org> <Pine.LNX.4.50.0309100947550.1659-100000@fileserver.cluster.local> <wM2X/kKkXQ6e092yn@gnosis.cx> Message-ID: <mc2X/kKkXELa092yn@gnosis.cx> |mro = getattr(obj, "mro", None) |if mro: | for i in mro: | func = getattr(i, "function") | if func: | return func(*args, **kw) |#Fall through |return getattr(type(obj), "function")(obj, *args, **kw) Pretty much, but it looks like you have a couple errors in your example. I think this is better (also undertested): def callmeth(obj, methname, *args, **kw): meth = obj.__dict__.get(methname) if meth is not None: # Might be in object's dict return meth(*args, **kw) if hasattr(obj, "mro"): # Might be in the ancestry for klass in obj.mro(): meth = getattr(klass, methname) if meth is not None: return meth(*args, **kw) # Or finally, look in class of obj return getattr(type(obj), methname)(*args, **kw) I think this does roughly the right thing if a non-callable "meth" is encountered. 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 mitchchapman at earthlink.net Thu Sep 11 21:19:52 2003 From: mitchchapman at earthlink.net (Mitch Chapman) Date: Fri, 12 Sep 2003 01:19:52 GMT Subject: python on mac (os x): application automation In-Reply-To: <bjr0bd$284m$1@otis.netspace.net.au> References: <bjr0bd$284m$1@otis.netspace.net.au> Message-ID: <3F611F6E.9060302@earthlink.net> Leo wrote: > hi there > > i have just started with mac development and i use applescript at the moment > for iTunes and iPhoto automation. > > but i'd like to do it from python. does anybody know weather that's > possible and if there is a add on for that? > > thanks, leo > > Bob Ippolito has built aeve for just such purposes. He recently announced aeve 0.0.3; you can find the announcement here: http://mail.python.org/pipermail/pythonmac-sig/2003-September/008692.html Because I am lazy and do not read documentation :) I just downloaded all of the source distributions from his website. He also provides binary distributions, which can be installed using PackageManager. To build aeve for Python 2.3 from source, you'll need to download and install each of these tarballs, using the usual 'sudo python setup.py install' incantations: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/Pyrex-0.8.2.tgz http://undefined.org/python/TECManager-0.1.tgz http://undefined.org/python/LaunchServices-0.1.tgz http://undefined.org/python/aeve-0.0.3.tgz Bob's announcement includes sample code showing how to get the name of the currently-playing iTunes track. He also provided the following variation, which works if you happen to be playing no tracks: #!/usr/bin/env pythonw import aeve iTunes = aeve.talkto('com.apple.iTunes') if iTunes.player_state == 'playing': print iTunes.current_track.name else: print "iTunes is not currently playing a track" Please also note that, in order to use aeve, you will probably need to invoke python as pythonw (or run from within a MacPython IDE) so you can talk to the window manager. -- Mitch From robin at jessikat.fsnet.co.uk Tue Sep 9 08:00:15 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 9 Sep 2003 13:00:15 +0100 Subject: Jython class names References: <zsNtMLAchYX$EwY3@jessikat.fsnet.co.uk> <bjk2fk$38o$07$1@news.t-online.com> Message-ID: <WYZkBWAPDcX$Ewf4@jessikat.fsnet.co.uk> In article <bjk2fk$38o$07$1 at news.t-online.com>, Peter Otten <__peter__ at web.de> writes >Robin Becker wrote: > >> I recently came across a problem with porting to Jython >> >> basically the following is prints 1 in CPython, but not in Jython. >> >> class C: >> pass >> >> red = C() >> print red.__class__.__name__ is 'C' >> >> >> it seems that Jython doesn't intern names in the same way or instances >> are not constructed in the same way. Is the above test robust or should >> I always be using == for testing class names? > >I have no Jython around, but I expect the following to always work: > I just tried and wow >>>> class C: pass >... >>>> C().__class__.__name__ is C.__name__ >True it doesn't work C:\jython-2.1>jython Jython 2.1 on java1.4.2 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> class C: pass ... >>> C().__class__.__name__ is C.__name__ 0 >>> C().__class__.__name__ == C.__name__ 1 >>> ...... > >(Of course isinstance() will also return True for subclass instances) > >Peter We're using the name tests in case we get the class from different import paths. -- Robin Becker From NO-MAIL at hotmail.com Wed Sep 10 03:25:33 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Wed, 10 Sep 2003 07:25:33 GMT Subject: CGI -- generating images -- \x0A always added! References: <jyw7b.16997$ip5.1259550@twister.southeast.rr.com> <mailman.1063167315.23982.python-list@python.org> <xJz7b.17514$ip5.1282848@twister.southeast.rr.com> Message-ID: <NlA7b.17517$ip5.1283526@twister.southeast.rr.com> I'm very sorry. Of course it was my fault. I forgot import sys :) This code works. Thank you all! sys.stdout.write( "Content-type: image/gif\n\n" ) sys.stdout.write( data ) sys.stdout.flush() # or close() "M-a-S" <NO-MAIL at hotmail.com> wrote in message news:xJz7b.17514$ip5.1282848 at twister.southeast.rr.com... > > >>> print "foo",;sys.stdout.softspace = 0 > > This doesn't work. \x0A is added anyways. And from what I've read it shoudn't work -- it influences only the blank BEFORE each print > that doesn't go after NL. > > > sys.stdout.write( "Content-type: image/gif\n\n" ) > > sys.stdout.write( data ) > > sys.stdout.close() # or flush() > > Doesn't work at all. Server error. Premature end of script headers. > > > From naesten at myrealbox.com Wed Sep 10 19:16:00 2003 From: naesten at myrealbox.com (Samuel Bronson) Date: 10 Sep 2003 23:16:00 GMT Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> Message-ID: <pan.2003.09.10.23.15.56.933429@myrealbox.com> On Wed, 10 Sep 2003 12:40:37 -0700, achris wrote: > > The yield statement looks to be a big step toward some kind of lightweight > concurrency-oriented programming in python. Is there any similarly nice > way to do the opposite of yield, just sit around (perhaps in the middle of > a loop) and wait until some other routine (unknown to the waiting module) > hurls a value in? > > If this is not implemented now, is there any chance that it's on the list > of things to come? > > > Al Well, aside from Stackless's microthreading, you might want to check out Twisted -- it isn't as magical as yield, but it gets the job done pretty well. From jwbiagio at sbcglobal.net Tue Sep 30 00:37:55 2003 From: jwbiagio at sbcglobal.net (Joshua W. Biagio) Date: Mon, 29 Sep 2003 21:37:55 -0700 Subject: BaseHTTPServer/SimpleHTTPServer HTTP/1.1 support? Message-ID: <000e01c3870c$9e4ba220$870a0a0a@wavicle7q777ds> Hello all, I am having difficulty getting the HTTP/1.1 support (i.e. pipelining and persistent connections) for the BaseHTTPServer library to work. When I change the line for the protocol in BaseHTTPServer from "HTTP/1.0" to "HTTP/1.1", the SimpleHTTPServer program can still serve directory listings and even graphics files, but it hangs when I try to browse to an HTML file. I have a directory of web pages that I use to test servers (such as Medusa and Quixote, etc.), and the python library functions Base/SimpleHTTPServer work fine in HTTP/1.0 mode but not in HTTP/1.1 mode. I am using Python 2.3 under Windows XP. Has anyone seen behavior or does anyone have a fix? Thank you for any information in this matter- jwb -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20030929/d34384ff/attachment.html> From aleax at aleax.it Sun Sep 21 17:18:20 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 21 Sep 2003 21:18:20 GMT Subject: Closures in python References: <9caba98e.0309180208.692e9b68@posting.google.com> <bkc5lv$5c4$1@news1.wdf.sap-ag.de> <HBF.20030918w8nt@bombur.uio.no> <bkcbdu$l0c$1@ginger.mathworks.com> <HBF.200309217by@bombur.uio.no> Message-ID: <wAobb.135308$R32.4217650@news2.tin.it> nospam wrote: > JCM wrote: >> >>> def foo(): >> ... x = [3] >> ... def bar(): >> ... x[0] += 1 >> (...) >> >> This is actually one of my biggest complaints about Python. I'd like >> syntactic disambiguation between definition and assignment in order to >> have control over which scope you're assigning into. > > Maybe Python could be changed to let 'foo.x' inside function foo mean > the x variable in foo? That would be backwards-incompatible, since foo.x already means something -- the attribute x of object foo (yep, functions are objects and can have attributes), which has no connection whatsoever with the local variable x inside (some of the potentially many currently active instances of) functions named foo. Alex From ulope at gmx.de Thu Sep 25 17:15:17 2003 From: ulope at gmx.de (Ulrich Petri) Date: Thu, 25 Sep 2003 23:15:17 +0200 Subject: Another Python rookie trying to port to C/C++ question. References: <GSGcb.24394$dk4.776543@typhoon.sonic.net> Message-ID: <bkvlt6$6i933$1@ID-67890.news.uni-berlin.de> "Don Bruder" <dakidd at sonic.net> schrieb im Newsbeitrag news:GSGcb.24394$dk4.776543 at typhoon.sonic.net... > > I expect that either will be a reasonable facsimile of how Python > handles dicts, with, of course, the corresponding overhead (which may be > surprisingly little, I'm thinking... but I have yet to code that part, > so I may find out it's going to be a nightmare) of "We want the value > that goes with key, so we've got to walk the KeyArray[] until we find a > match, then extract the value from the other array", or a similar > procedure for the doubly-linked list. Python hashes the keys for fast lookup. > (Note 1) > Along with quite a bit of entirely unwelcome "Python evangelism" -- > Which part of "I don't care how good, bad, or indifferent Python is > compared to C/C++, or any other language. I want this Python code to be > written in C/C++, end of discussion." wasn't clear enough for those of > you who took it upon yourselves to preach (including the idiot who > decided to spew a relatively impressive (as such things go) string of > insults about how stupid I am, how far up my ass my head is, and how > pathetic my family all the way back to Adam must be for producing such a > throwback because I've got no interest in adopting "the perfect > language...") at me on the merits of Python, both on group and > in-mailbox? You are treated as you treat others. It might suprise you but this is a newsgroup not your personal information lookup place. From lupan at zamek.gda.pl Sat Sep 6 03:31:34 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Sat, 06 Sep 2003 09:31:34 +0200 Subject: XRC, wxMenuBar's, and wxMenuBarPtr's References: <ac4e4ba8.0309052109.15cd0f6d@posting.google.com> Message-ID: <87vfs6s78p.fsf@psi.lupan.zamek.gda.pl> Hi, wxMenuBarPtr has FindItemById so m = self.MenuBar.FindItemById(XRCID("MenuItemSnapToGrid")) should work. -- =*= Lukasz Pankowski =*= From FBatista at uniFON.com.ar Wed Sep 24 13:30:39 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 24 Sep 2003 14:30:39 -0300 Subject: __init__ return value Message-ID: <A128D751272CD411BC9200508BC2194D03382FFE@escpl.tcp.com.ar> Studying the Tim Peter's FixedPoint code, found this: # can we coerce to a float? yes = 1 try: asfloat = float(value) except: yes = 0 if yes: self.__init__(asfloat, p) return This code is part of the __init__ method of the class. The question is about the last two lines: When you call self.__init__(...), doesn't it return a value that you should return too? I thought it could be like this: ... if yes: newobject = self.__init__(asfloat, p) return newobject Thanks for all. Facundo Batista Gesti?n de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5132 0132 From ivoras at fer.hr Tue Sep 16 15:16:50 2003 From: ivoras at fer.hr (Ivan Voras) Date: Tue, 16 Sep 2003 21:16:50 +0200 Subject: tuples vs lists References: <bk7eo9$g4g$1@bagan.srce.hr> <9egemvkhp2s55horjr9dfveml22158d62g@4ax.com> <bk7lfj$v5p$1@bagan.srce.hr> <3F67606B.C9A89EF3@engcorp.com> Message-ID: <bk7nlb$5jp$1@bagan.srce.hr> Peter Hansen wrote: > Ivan Voras wrote: >> >> Ok, I gather touples should be smaller & faster as I thought :) > > Don't make a decision based on performance. Use tuples if you > require the immutability, or if you want to follow Guido's "advice" > (?) to treat them as simple unnamed structs. I know that. I was just wandering if they also behave faster. Lists are only interesting to me in case I need mutability. -- -- Every sufficiently advanced magic is indistinguishable from technology - Arthur C Anticlarke From afriere at yahoo.co.uk Wed Sep 24 22:20:37 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 24 Sep 2003 19:20:37 -0700 Subject: Need arguments for "Python vs. Perl as an OOPL" References: <roy-002696.23242122092003@reader2.panix.com> <3F7049D3.14C48D43@engcorp.com> Message-ID: <38ec68a6.0309241820.6f2a894b@posting.google.com> Peter Hansen <peter at engcorp.com> wrote in message news:<3F7049D3.14C48D43 at engcorp.com>... > > I ask because I suspect the best way of convincing them will be to do > nothing, and stand back watching as your Python prototype continues to > work without problems, while those attempting to rewrite it in Perl > waste a lot of time and never get it quite working... and even if they > do, just print out a couple of pages from both and show them to the > "powers that be" and that ought to do the trick. > I'm in a similar position to the parent poster, with my boss "flagging" the fact that my app will have be translated back into Perl at some stage. The difference is that some parts of my project are already being used in 'production.' I agree with your strategy, although the indication is that it will be me who will be doing the re-writting. :/ It's amazing how inertia can work to your advantage, especially in a short-staffed shop. While the boss, understandibly, doesn't want every programmer going off and writing in their pet language, the ultimate test remains, "does it get the job done?" From tim.one at comcast.net Sun Sep 21 18:03:42 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 21 Sep 2003 18:03:42 -0400 Subject: python script as an emergency mailbox cleaner In-Reply-To: <xxobb.50052$Aq2.31203@newsread1.news.atl.earthlink.net> Message-ID: <LNBBLJKPBEHFEDALKOLCMEPEGAAB.tim.one@comcast.net> [Phil Weldon] Phil, top-posting makes it very hard to follow a discussion. I'll reply briefly here, but if you want to continue it, please move it to the spambayes list and interleave your comments with the text of the msg you're reply to. > Yes, I tend to discount your advice because it may be that you aren't > considering the messages generated by Worm.Automat.AHB are a very > restricted subset of spam, the legitimate 'undeliverable e-mail' > messages are closely related, and the 'undelivered e-mail' messages > caused by Worm.Automat.AHB generated e-mail with the target e-mail > address in the FROM line are also closely related. The current need > is a quick way to counter the 'spam' effects of Worm.Automat.AHB, not > correctly categorizing Nigerian fund transfer and Viagra spam sets. As I said the first time, the worm spew in my classifier (you surely don't think you're the only one getting these msgs, right?) was adequately caught after training on 6 of the beasts. You'll catch the worm spew too if you train on 1500 of them, but at the cost of warping the classifier. > To further explain, the bogus 'undeliverable e-mail' type messages are > permutating and the database supplying the input to the worm's > generator is growing. There are at least two classes of bogus > 'undeliverable mail'; > > 1. e-mail generated by the worm > 2. real 'undeliverable e-mail' messages that are the results of the > worm using your e-mail address as the sender on bogus 'undeliverable > e-mail' which then generates a legitimate but unwanted and useless > 'undeliverable e-mail' message. > > Now, if you have the time to supply your arguments rather than cv, > I'll be happy to learn. spambayes never relied on arguments, it relied on testing. Indeed, that's why it works <wink>. > And, to quote the Inboxer help file, > > "The text box in the Create Filters area indicates the number of > messages that were processed to build the filters. Generally, the > higher the number, the more accurate the filters will become." Partly true, and partly misleading due to brevity. Things aren't *that* simple in reality (how could they be?). If, after the "Generally", they added some weasel-words about training set balance, I'd be happier with it, but it's still just "generally". > So far the scoring Inboxer developed on the basis of the ~1500 bad > and 264 good examples results in no false negatives or false > positives, including correctly classifing a dozen completely > legitimate 'undelivered e-mail' messages in a set of ~ 400 new > messages. In part that's because I believe Inboxer uses the spambayes experimental_ham_spam_imbalance_adjustment: True option. This option was intended to fight the worst effects of people taking "more is better" too literally, getting their training data out of balance. The result of this option is that once you have a large imbalance in one direction (and you do: 1500::264 is an out-of-whack ratio), training on additional messages in the already-over-represented class (spam, for you) has very little effect. What you're seeing now is the good effects of that option trying its hardest to ignore the imbalance you created. It has bad effects too, which you'll see later; the spambayes archives have many discussions of this already, so suffice it to say here that we're removing the code that supports the option. The bad effects of unbalanced training will be more severe then, but easier to recognize and address (the bad effects this option creates are subtler -- in your case, if you get a significantly different new kind of worm spew, you'll find it very hard to get it classed as spam, because training on new spam will have little effect for you from now on). > The -1500 bad e-mail messages have a date spread of 18SEP03 though > 20SEP03 while the 265 good e-mail messages have a date spread of > 1AUG03 through 20SEP03. Both sets were sent to my ISP mailbox. OK by me <wink>. > I will try dividing the two sets of messages into smaller sets and > try the results of your suggestion on new e-mails as they collect. > By the way, my current ratio of Worm.Automat.AHB instigated messages > to legitimate e-mail (which for my purposes includes traditional > spam) is far greater than 1500:265; it's more like 1500:50. > > And I guess I should download from spambayes There's no need to download anything from the spambayes project if you're happy with Inboxer. > and donate to PSF That's always appreciated! > since my daughter is using Python in her physics classes at Carnegie- > Mellon. Concidently, I just happened to be looking at my loose-leafed > copy of Feynman's Lectures on Physics with a reference manual in the > back for FORTRAN IV I had to use for physics classes. There kids today don't know what pain is, eh <wink>? From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Wed Sep 17 14:38:05 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Wed, 17 Sep 2003 22:38:05 +0400 Subject: Sound, time and platform issues In-Reply-To: <bka8ne$q0hl7$1@ID-162581.news.uni-berlin.de> References: <bka4k6$j9a$1@news.peterlink.ru> <bka8ne$q0hl7$1@ID-162581.news.uni-berlin.de> Message-ID: <bka9mc$kqo$1@news.peterlink.ru> Tobias Pfeiffer wrote: > Hi! > > anton muhin <antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru> wrote in > news:bka4k6$j9a$1 at news.peterlink.ru: > > >>3. If there is no Windows solution, what is the simplest way to use >>Linux? I have a notebook and rather limited knowledge of Linux. I >>don't want to install Linux on the notebook---harddrive is somewhat >>limited. However, I heard that there are some variants of *nix that >>needs only boot-CD. Does anybody have experience with systems like >>these? > > > Yuz. A little bit, at least. There's two alternatives I know of. [skipped] > Bye > Tobias Thanks a lot. anton. From rh4170056 at juno.com Sun Sep 21 13:07:58 2003 From: rh4170056 at juno.com (rhmd) Date: 21 Sep 2003 10:07:58 -0700 Subject: Help me choose a C++ compiler to work with Python Message-ID: <616fccba.0309210907.1e35b92d@posting.google.com> Just found Python and I love it. What an elegant language! I would like to use it for various applications, but the mathematical calculations are way too slow (a million sines 8 seconds in Python vs. 2 seconds in Excel VBA), so was thinking of learning enough C++ to do the number crunching in C++ and integrating the C++ routines with Python. My question: My question: Which compiler works best with Python? I use Windows XP and 98. Have very little experience with C++. Am doing statistical and other simulations that require billions of calculations (taking 1 to 2 hours in Excel VBA). GCC is free, MS C++.Net is affordable at <$100 but supposedly has problems until the next version (and I could only use it on my XP machine), older versions of MS C++ are no longer for sale. What's the most robust solution? I would also like to make .dll files that I can plug into MS Excel. Sorry for the vagueness of this question, but I'm sure many of you have experience with this and any information, opinions, and even prejudices about the various compilers are welcome. Thanks. From danielk at aracnet.com Sat Sep 13 01:06:55 2003 From: danielk at aracnet.com (Daniel Klein) Date: Fri, 12 Sep 2003 22:06:55 -0700 Subject: Debug python programs References: <bjpn2s$8bh$1@pegasus.csx.cam.ac.uk> Message-ID: <bc95mvoqno9jbvdi9799dneneosc6jootk@4ax.com> On Thu, 11 Sep 2003 12:41:48 +0100, York <yorklee70 at yahoo.com> wrote: >Would you please recommend some good softwares/methods for >tracking/debugging python codes. I just use the Python debugger by importing the pdb module. http://www.python.org/doc/2.3/lib/module-pdb.html Of course there are IDEs that have built-in debuggers. Dan From oblivious at web.de Thu Sep 25 14:15:25 2003 From: oblivious at web.de (Dominic) Date: Thu, 25 Sep 2003 20:15:25 +0200 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) In-Reply-To: <3F731B17.61C17B3A@engcorp.com> References: <mailman.1064390741.20344.python-list@python.org> <3F71B857.2D1E3268@engcorp.com> <Xns9400E70CB6F9Fcliechtigmxnet@62.2.16.82> <3F720759.34D7BD3E@engcorp.com> <3F720D28.83C3E99@engcorp.com> <noCcb.119695$hE5.4100692@news1.tin.it> <3F731B17.61C17B3A@engcorp.com> Message-ID: <bkvbb5$6mi$00$1@news.t-online.com> >>I and Just canvassed widely at Europython, looking for people to >>suggest more use cases, and nobody came up with anything that stood >>up to examination beyond our basic use case of "debugging possibly >>buggy (nonterminating) code, in cases where we just can't run the >>possibly buggy code in the main thread and delegate a separate >>watchdog thread to the purpose of interrupting the main one" One use case could be if you only want to use a limited number of threads for some reason. Then you could interrupt a low priority task and reassign the thread to some more urgent task. Afterwards the old task could be resumed. To make this work you would have to make the code aware of those interrupts. While playing with the new feature I noticed that it takes a long time (>3 seconds) until the exception is thrown. In contrast to the possibility to interrupt the main thread with interrupt_main which seems not to be delayed. Besides with Pyrex it's 2-4 lines to access PyThreadState_SetAsyncExc from Python :-) Ciao, Dominic From newsgroups at jhrothjr.com Fri Sep 5 18:23:36 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 18:23:36 -0400 Subject: Why the 'self' argument? References: <slrnblh5ru.nd5.gstaniak@inka.zagiel.pl> <vlh7otscuo8gb1@news.supernews.com> <3f58a2bd$0$156$a1866201@newsreader.visi.com> <vlhba85atlte07@news.supernews.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <vlhidvcpq9a980@news.supernews.com> <qpOW/ks/KnRV089yn@the-wire.com> <vlhtm1bmc7m295@news.supernews.com> <3f59014d$0$152$a1866201@newsreader.visi.com> Message-ID: <vli387c9mm140a@news.supernews.com> "Grant Edwards" <grante at visi.com> wrote in message news:3f59014d$0$152$a1866201 at newsreader.visi.com... > In article <vlhtm1bmc7m295 at news.supernews.com>, John Roth wrote: > > >> There's no difference in the sense that a method is simply a > >> function whose first parameter refers to the class instance to > >> be worked on. No magic words, no "undeclared" parameters. It > >> means that in my demo code in limitcases.py (somewhere in the > >> newsgroup lately) I can say > >> > >> limitcases.Lowest.__str__ = lambda x: "-Infinity" > >> > >> to give the Lowest class a new method sans ennuis. > > > > But why do it that way? > > So that there's no difference between a function and a method. > > Simplicity and orthogonality are good things -- despite what > C++ proponents thing. > > > Neither Java nor Ruby require giving the instance a name. > > So? > > Personally I don't like invisible, implied, automatic stuff > like that. > > Can't stand automatic transmissions either -- the damn things > have no idea what's ahead, and always seem to be in the wrong > gear at critical moments. > > > Hence my comment that requiring it is more complex than not > > requiring it. > > No, it's more complex the Java/Ruby way, since you have to have > two sets of rules for what a name means depending on whether > you're inside a "normal" function or a method. In Python > there's just one set of rules -- mostly. As I said earlier, it's quite possible to define it so that there is always an instance of some kind; whether that's an instance a class or the module itself. > I have enough trouble remembering how the stuff I design works. ;) > > I don't want to have to keep track of more scoping/name-space > rules than absolutely necessary. I think my comments have shown that you can reduce the amount of scoping / name space rules noticably. John Roth > > -- > Grant Edwards grante Yow! Intra-mural sports > at results are filtering > visi.com through th' plumbing... From disgracelands at quietblue.co.uk Wed Sep 17 17:10:12 2003 From: disgracelands at quietblue.co.uk (disgracelands) Date: Wed, 17 Sep 2003 22:10:12 +0100 Subject: Clearing file object buffers Message-ID: <784ab.4$YT6.3@news-binary.blueyonder.co.uk> In my code i have setup sys.stdout and sys.stderr as file objects so that i can easily track whats going on during the course of my program. So far its proving useful but the objects seem to be buffering any text supplied to their write() functions and when i hit an error condition and have to exit early they fail to write and i'm left with empty files. Is there any way to force the file objects to flush the buffer to file on disc? thanks, dis From mcherm at mcherm.com Tue Sep 9 12:16:09 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 9 Sep 2003 09:16:09 -0700 Subject: Ternery operator Message-ID: <1063124169.3f5dfcc961acc@mcherm.com> > [Michael, shouting] > > NOT TRUE! > > > > NEITHER of your options does short-circuit evaluation. Richie Hindle: > > Er: > > >>> def one(): > print 1 > return 1 > > >>> def two(): > print 2 > return 2 > > >>> (True and [one()] or [two()])[0] > 1 > 1 > >>> (False and [one()] or [two()])[0] > 2 > 2 > >>> [...] > [Not condoning the use of this idiom, just correcting a factual error.] Well, I was shouting to be sure I was heard, because I was pretty sure I was right, and was worried about spreading misinformation. Well, I clearly should have worried a bit harder. You are correct, the idiom (<condition> and [<true-branch>] or [<false-branch>])[0] _does_ indeed short circuit correctly. And now it's ME who's spreading misinformation. Sorry. Of course it's still an ugly idiom. But there's a distinction between ugly-but-works and ugly-and-wrong. -- Michael Chermside From BrenBarn at aol.com Mon Sep 8 01:23:58 2003 From: BrenBarn at aol.com (OKB (not okblacke)) Date: 8 Sep 2003 05:23:58 GMT Subject: exec code with timeout? References: <Xns93EFD117DA30FOKB@130.133.1.4> <mailman.1062996311.6727.python-list@python.org> Message-ID: <Xns93EFE34728E26OKB@130.133.1.4> Graham Fawcett wrote: > The RestrictedPython module in Zope may suit your needs; it was > designed for a > similar use scenario. Search the list, there was a discussion about > RestrictedPython not long ago. Thanks. I looked at the page that was referenced from here, but it says RestrictedPython "doesn't implement resource limitations, like preventing scripts from eating up all available RAM or simply never terminating". Preventing scripts from never terminating is exactly what I am interested in. (This isn't a halting problem kind of thing -- I just want to unceremoniously kill exec-ed code that doesn't terminate in a given amount of time.) Also, it seems a bit heavyweight. The page implies that it uses a modified compiler, etc.; I don't know how that would work with running interactively edited code. -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From falted at openlc.org Tue Sep 2 14:48:32 2003 From: falted at openlc.org (Francesc Alted) Date: Tue, 02 Sep 2003 20:48:32 +0200 Subject: Hunting a memory leak References: <slrnbkucfq.41o.falted@inspiron.openlc.org> <7h3oey84qho.fsf@pc150.maths.bris.ac.uk> <slrnbkv5h6.i5.falted@inspiron.openlc.org> <slrnbkv748.on.falted@inspiron.openlc.org> <vl147iqv8kk6da@corp.supernews.com> Message-ID: <bj2om3$nuj$1@nsnmrro2-gest.nuria.telefonica-data.net> Edward K. Ream wrote: > Here are two general ideas: > > 1. Try to simplify the problem. Pick something, no matter how small (and > the smaller the better) that doesn't seem to be correct and do what it > takes to find out why it isn't correct. Yeah... using this approach I was finally able to hunt the leak!!!. The problem was hidden in C code that is used to access to a C library. I'm afraid that valgrind was unable to detect that because the underlying C library does not call the standard malloc to create the leaking objects. Of course, the Python reference counters were unable to detect that as well (although some black points still remain, but not very important). Anyway, thanks very much for the advices and encouragement! Francesc Alted From a.neudecker at uni-bonn.de Mon Sep 1 08:26:16 2003 From: a.neudecker at uni-bonn.de (Andreas Neudecker) Date: Mon, 01 Sep 2003 14:26:16 +0200 Subject: My script is taking 12 hours+ any suggestions? In-Reply-To: <3f4ff9f8$0$23588$5a62ac22@freenews.iinet.net.au> References: <3f4ff9f8$0$23588$5a62ac22@freenews.iinet.net.au> Message-ID: <bivdt8$18p0$1@f1node01.rhrz.uni-bonn.de> Hi, even if you find ways to speed up the code through editing, you might want to try out Psyco: http://psyco.sourceforge.net/ . I have tried it recently and it speeds up execution considerably. Regards Andreas Ideasman wrote: > Hi I have a made a script that process normals for a flat shaded 3D mesh's. > It compares every vert with every other vert to look for verts that can > share normals and It takes ages. > > I'm not asking anyone to rewrite the script- just have a look for any > stupid errors that might be sucking up time. > > > > > > > > > #!/usr/bin/python > ############## > # AUTOSMOOTH # > ############## > import sys > import os > import string > import math > > # Used to write floats that dont' contain letters/ > def saneFloat(float): > #return '%(float)b' % vars() # 6 fp as house.hqx > return '%f' % float # 10 fp > > > > #Open file from the command line, turn into a list and close it. > file = open(sys.argv[-1], 'r') > fileLineList = file.readlines() > file.close > > # Remember the number of lines for progress indication. > fileLen = len(fileLineList) > > # Autosmooth value. Higher will autosmooth larger angles. > maxDiff = 1.66 > > # Loop through the lines. > lineIndex = 0 > while lineIndex < len(fileLineList): > > #Find Geom TAG.. > if str(fileLineList[lineIndex])[0:8] == 'Geometry': > lineIndex += 1 > # break if looping beyong the file, > if lineIndex > len(fileLineList): > break > > # Here we remember lines that have been processed. > # it needs to be reset for each geom object. > listOfDoneLines = [] > > # Start a new loop that checks the current vert against all the > others > newLoopindex = lineIndex > while len(string.split(fileLineList[newLoopindex])) == 12: > print '\n', fileLen, newLoopindex, > > #vertexnum = newLoopindex - lineIndex > > # Compare the 2 lines > newCompareLoopindex = newLoopindex + 1 # compare the current > vert to this new one. > thisPassDoneLines = [] # act apon this after comparing with > each vert > thisPassDoneNormals = [] > while len(string.split(fileLineList[newCompareLoopindex])) > == 12: > > # Speed up the process by using 2 if's, splitting the > string only if it has not been evaluated already. > if newCompareLoopindex not in listOfDoneLines: > comp1 = string.split(fileLineList[newLoopindex]) > comp2 = string.split(fileLineList[newCompareLoopindex]) > > if [comp1[0], comp1[1], comp1[2]] == [comp2[0], > comp2[1], comp2[2]]: > > if newLoopindex not in listOfDoneLines: # Only > needs to be added once > listOfDoneLines.append(newLoopindex) > > if newLoopindex not in thisPassDoneLines: # Only > needs to be added once > thisPassDoneLines.append(newLoopindex) > thisPassDoneNormals.append([eval(comp1[8]), > eval(comp1[9]), eval(comp1[10])]) > > listOfDoneLines.append(newCompareLoopindex) > thisPassDoneLines.append(newCompareLoopindex) > thisPassDoneNormals.append([eval(comp2[8]), > eval(comp2[9]), eval(comp2[10])]) > print '#', > > newCompareLoopindex += 1 > > > > if len(thisPassDoneLines) > 1: # Ok We have some verts to > smooth. > > > # This loops through all verts and assigns each a new > normal. > for tempLineIndex in thisPassDoneLines: > > tempSplitLine = > string.split(fileLineList[tempLineIndex]) > > # We add to these for every vert that is similar, > then devide them to get an average. > NormX = 0 > NormY = 0 > NormZ = 0 > > # A list of vert line indicies that we will create > to store verts that have normals close to ours. > thisVertFrendsCount = 0 > > # This compares the current vert with all the > others, if they are close then add to vertFrends. > for tNorm in thisPassDoneNormals: # tNorm is just > used for one of the normals in the thisPassDoneNormals > > if abs(eval(tempSplitLine[8]) - tNorm[0]) + > abs(eval(tempSplitLine[9]) - tNorm[1]) + abs(eval(tempSplitLine[10]) > -tNorm[2])< maxDiff: > > #maxDiff > NormX += tNorm[0] > NormY += tNorm[1] > NormZ += tNorm[2] > > thisVertFrendsCount += 1 > > > #Now devide the normals by the number of frends. > NormX /= thisVertFrendsCount > NormY /= thisVertFrendsCount > NormZ /= thisVertFrendsCount > > # make unit length vector. > d = NormX*NormX + NormY*NormY + NormZ*NormZ > if d>0: > d = math.sqrt(d) > NormX/=d; NormY/=d; NormZ/=d > > > # Write the normal to the current line > tempSplitLine[8] = str(saneFloat(NormX)) > tempSplitLine[9] = str(saneFloat(NormY)) > tempSplitLine[10] = > str(saneFloat(NormZ)) > > fileLineList[tempLineIndex] = > string.join(tempSplitLine) + '\n' > > > > newLoopindex += 1 > > lineIndex += 1 > > > # Writing to file > # file to write > file = open(sys.argv[-1], 'w') > file.writelines(fileLineList) > file.close() > From max at alcyone.com Tue Sep 30 22:38:26 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 30 Sep 2003 19:38:26 -0700 Subject: getting values from an "exec" statement References: <ad32251c.0309301513.1b11a8ce@posting.google.com> Message-ID: <3F7A3E22.86AB0D@alcyone.com> Toby Donaldson wrote: > I'm designing an educational application that will run Python code and > check the output against a pre-define answer. I want to use the "exec" > statement to run the code, but I don't know how to get output from it. Override sys.stdout with a proxy that will capture what's send to stdout so you can do something with it. Of course, this won't help your second problem -- trying to set up a useful sandbox -- but it's a start for non-malicious code. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I am still learning. \__/ (Michaelangelo's motto) From cygwin-help at cygwin.com Thu Sep 4 14:34:31 2003 From: cygwin-help at cygwin.com (cygwin-help at cygwin.com) Date: 4 Sep 2003 18:34:31 -0000 Subject: confirm unsubscribe from cygwin@cygwin.com Message-ID: <1062700471.12028.ezmlm@cygwin.com> Hi! This is the ezmlm program. I'm managing the cygwin at cygwin.com mailing list. To confirm that you would like python-list at python.org removed from the cygwin mailing list, please send an empty reply to this address: cygwin-uc.1062700471.nellflaigclagldbcadg-python-list=python.org at cygwin.com Usually, this happens when you just hit the "reply" button. If this does not work, simply copy the address and paste it into the "To:" field of a new message. I haven't checked whether your address is currently on the mailing list. To see what address you used to subscribe, look at the messages you are receiving from the mailing list. Each message has your address hidden inside its return path; for example, mary at xdd.ff.com receives messages with return path: <cygwin-return-<number>-mary=xdd.ff.com at cygwin.com. Some mail programs are broken and cannot handle long addresses. If you cannot reply to this request, instead send a message to <cygwin-request at cygwin.com> and put the entire address listed above into the "Subject:" line. --- Administrative commands for the cygwin list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: <cygwin-subscribe at cygwin.com> To remove your address from the list, send a message to: <cygwin-unsubscribe at cygwin.com> Send mail to the following for info and FAQ for this list: <cygwin-info at cygwin.com> <cygwin-faq at cygwin.com> Similar addresses exist for the digest list: <cygwin-digest-subscribe at cygwin.com> <cygwin-digest-unsubscribe at cygwin.com> To get messages 123 through 145 (a maximum of 100 per request), mail: <cygwin-get.123_145 at cygwin.com> To get an index with subject and author for messages 123-456 , mail: <cygwin-index.123_456 at cygwin.com> They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: <cygwin-thread.12345 at cygwin.com> The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: <cygwin-subscribe-john=host.domain at cygwin.com> To stop subscription for this address, mail: <cygwin-unsubscribe-john=host.domain at cygwin.com> In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at cygwin-owner at cygwin.com. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: <anonymous at sources.redhat.com> Received: (qmail 12021 invoked by uid 48); 4 Sep 2003 18:34:31 -0000 Date: 4 Sep 2003 18:34:31 -0000 Message-ID: <20030904183431.12019.qmail at sources.redhat.com> From: anonymous at sources.redhat.com To: cygwin-unsubscribe-python-list=python.org at sources.redhat.com From tl_nntp at webcrumb.com Tue Sep 2 05:58:29 2003 From: tl_nntp at webcrumb.com (Tom Lee) Date: Tue, 02 Sep 2003 09:58:29 GMT Subject: Overloading objects In-Reply-To: <mailman.1062424624.4041.python-list@python.org> References: <mailman.1062424624.4041.python-list@python.org> Message-ID: <3f5469c4@news.comindico.com.au> Batista, Facundo wrote: > In others languages I can do (using sintaxis of Python): > > > def myMethod (self, name): > self.name = name > > def myMethod (self, name, age): > self.name = name > self.age = age > > > If I'm not wrong, this is "Method Overloading". > > I thought using defaults: > > def myMethod (self, name, age=None): > self.name = name > if age not None: > self.age = age > > > but I'm concerned about the scalability of this. > > What's the most pythonic way to do this? Using something like *args or > **args? > > Thank you! > > > . Facundo Scalability doesn't even come into this question - if you're really worried about performance, don't use Python. Anyway, you have two or three choices: 1. Do it the way you're doing it. 2. Check parameter types at runtime using type() and the is keyword. e.g. if type( somevar ) is int: self.do_int_stuff( somevar ) else: self.do_other_stuff( somevar ) 3. Use similar names for similar methods. wxPython does this. e.g. def Clean( self, something ): # common implementation def CleanWithScourer( self, something ): # implementation using a Scourer instead of the default cleaning implement Hope this helps. - Tom L From godoy at metalab.unc.edu Tue Sep 30 19:54:27 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 30 Sep 2003 20:54:27 -0300 Subject: Threading and Windows. References: <m3smmfu7m7.fsf@ieee.org> <33803989.0309300315.7e132c0@posting.google.com> <m34qyuqxzf.fsf@ieee.org> <3f79c219$0$576$b45e6eb0@senator-bedfellow.mit.edu> Message-ID: <m3isn9g7d8.fsf@ieee.org> Brian Kelley <bkelley at wi.mit.edu> writes: > If you are using wxPython you might want to check out this little package: > > http://staffa.wi.mit.edu/people/kelley/ > > look for LongRunningTasks at the bottom. > > -brian I didn't knew this address but I got something like that from http://wiki.wxpython.org/index.cgi/LongRunningTasks It didn't solve my problem but thanks for this new pointer. In my case I really needed something that ran a new proccess. -- Godoy. <godoy at metalab.unc.edu> From ivoras at fer.hr Wed Sep 17 07:44:40 2003 From: ivoras at fer.hr (Ivan Voras) Date: Wed, 17 Sep 2003 13:44:40 +0200 Subject: tuples vs lists References: <bk7eo9$g4g$1@bagan.srce.hr> <9egemvkhp2s55horjr9dfveml22158d62g@4ax.com> <bk7lfj$v5p$1@bagan.srce.hr> <3F67606B.C9A89EF3@engcorp.com> <bk7nlb$5jp$1@bagan.srce.hr> <3F676AAB.92479235@engcorp.com> Message-ID: <bk9h4m$q3p$1@bagan.srce.hr> Peter Hansen wrote: > Ivan Voras wrote: >> I know that. I was just wandering if they also behave faster. Lists >> are only interesting to me in case I need mutability. > > I'd suggest you have that backwards. Lists should _always_ be > interesting > to you. Tuples should be interesting only in the case where you need > *immutability*. I disagree. :) I would always use tuples except when I explicitely need mutability. That doesn't meen that I would intentionaly (badly) restructure code just to use tuples, only that in many cases my structures don't need to be modified. -- -- Every sufficiently advanced magic is indistinguishable from technology - Arthur C Anticlarke From mack at incise.org Mon Sep 1 01:08:46 2003 From: mack at incise.org (Nick Welch) Date: Mon, 1 Sep 2003 00:08:46 -0500 Subject: Python Documentation? In-Reply-To: <LQydncwLlNp2UM-iXTWJkA@comcast.com> References: <LQydncwLlNp2UM-iXTWJkA@comcast.com> Message-ID: <20030901050846.GB14796@incise.org> pydoc is pretty nice, try "pydoc str", and then use / to search for "split". As far as searching the online docs, it takes a little adaptation. To look for str.split, I'd do a google "site:www.python.org built-in types", and then look for str, and then look at split. And doing just that, and clicking once or twice, brought me to: http://www.python.org/doc/current/lib/string-methods.html Although I agree, it would be cool if the online documentation supported such direct search methods as e.g. www.php.net/split. -- Nick Welch aka mackstann | mack @ incise.org | http://incise.org What is the difference between a Turing machine and the modern computer? It's the same as that between Hillary's ascent of Everest and the establishment of a Hilton on its peak. From jjl at pobox.com Thu Sep 4 12:41:22 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Sep 2003 17:41:22 +0100 Subject: htmllib.py and parsing malformed HTML References: <G1T4b.2227$gJ.1163@bignews3.bellsouth.net> <bj1sh5$e9i7j$1@ID-63505.news.uni-berlin.de> <JP%4b.4205$tH.3863@bignews4.bellsouth.net> <873cfeyhqw.fsf@pobox.com> <09J5b.203$MD.41@bignews3.bellsouth.net> Message-ID: <87he3sik0d.fsf@pobox.com> KC <nskhcarlso at bellsouth.net> writes: > John J. Lee wrote: > > > So, what about *your* code's error log (or the equivalent -- > > presumably an unhandled traceback)?? It's not obvious that your [...] > If this parser was handling a "great variety of nonsense" I would > wholeheartedly agree with you. However, since this HTML is from a > single vendor and that vendor is a government entity, this solution Oh, got you. Fair enough [...] > for technology usage within our organizations. You can always tell when someone's 'business button' has been pushed when they use the word 'within' ;-) John From PeterAbel at gmx.net Mon Sep 29 16:12:39 2003 From: PeterAbel at gmx.net (Peter Abel) Date: 29 Sep 2003 13:12:39 -0700 Subject: Checking for invalid keyword arguments? References: <roy-B6EED5.17061128092003@reader2.panix.com> Message-ID: <21064255.0309291212.1a64dc58@posting.google.com> Roy Smith <roy at panix.com> wrote in message news:<roy-B6EED5.17061128092003 at reader2.panix.com>... > I've got a function that takes a couple of optional keyword arguments. > I want to check to make sure I didn't get passed an argument I didn't > expect. Right now I'm doing: > > conversion = None > drop = False > for key, value in kwArgs.items(): > if key == 'conversion': > conversion = value > elif key == 'drop': > drop = value > else: > raise TypeError ('Unexpected keyword argument %s' % key) > > which seems kind of verbose. Is there a neater way to do this check? One solution - which reminds me of *slots* - could be the following: >>> def fn(**kwa): ... allowed='conversion drop some_thing else'.split() ... not_used =filter(lambda var:var not in kwa,allowed) ... not_allowed=filter(lambda var:var not in allowed,kwa) ... print 'not_allowed:\t'+'\n\t\t'.join(not_allowed) ... print 'not_used :\t'+'\n\t\t'.join(not_used) ... >>> fn(drop=1,conversion=True,foo=5, false=False) not_allowed: false foo not_used : some_thing else >>> Regards Peter From daniel at dittmar.net Wed Sep 17 15:25:54 2003 From: daniel at dittmar.net (Daniel Dittmar) Date: Wed, 17 Sep 2003 21:25:54 +0200 Subject: Graphic python debugger In-Reply-To: <20030917120146.3c5202e2.max@fr.fm> References: <20030917120146.3c5202e2.max@fr.fm> Message-ID: <bkachs$43$1@news.eusc.inter.net> Maxime Biais wrote: > I'm looking for a graphic debugger for python on linux like DDD or GVD. > I tried pdb and pdb-mode for emacs, but I would use a more gvd-like > debugger. See also the FAQ: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.001.htp Daniel From jroznfgre at jngpugbjreXEBCXNbet.cy Sun Sep 21 06:09:39 2003 From: jroznfgre at jngpugbjreXEBCXNbet.cy (JZ) Date: Sun, 21 Sep 2003 12:09:39 +0200 Subject: How you chomp in python References: <mailman.1064022207.30931.python-list@python.org> Message-ID: <04uqmvo81qucr6lmevbcludhe04eb1oad3@4ax.com> On Fri, 19 Sep 2003 18:43:14 -0700, "Fernando Armenta" <farmenta at pillardata.com> wrote: >How you cut off the ^M at the end of a line? rstrip is not working. Strings in Perl are mutable so chomp() change the string in place. Strings in Python are *not* mutable, so rstrip() does *not* change the string in place. >>> s = "abc\n" >>> s.rstrip() 'abc' >>> s 'abc\n' >>> s = s.rstrip() 'abc' -- JZ From sheu at bu.edu Thu Sep 18 21:03:54 2003 From: sheu at bu.edu (Shu-Hsien Sheu) Date: Thu, 18 Sep 2003 21:03:54 -0400 Subject: file object: seek and close? In-Reply-To: <20030919003543.GC9792@unpythonic.net> References: <3F69DA35.8070207@bu.edu> <20030919003543.GC9792@unpythonic.net> Message-ID: <3F6A55FA.30304@bu.edu> It turns out to be 'cause I used 'list' as my variable name. I changed it to something else and now it works fine. Thanks to all! I should have be more careful about the variable names. I have been using "list" in some small scripting which worked flawlessly and it just pop up to my mind easily. -shuhsien From bobnotbob at byu.edu Sun Sep 14 12:35:22 2003 From: bobnotbob at byu.edu (Bob Roberts) Date: 14 Sep 2003 09:35:22 -0700 Subject: better use of os.system() Message-ID: <c4e6b17d.0309140835.3408fc52@posting.google.com> How can I make it so that I can pass anything into os.system() any command that I would type into the command line (bash on cygwin)? For example, "lower" is a small script of mine that I use frequently, and I would like to be able to call if from python. os.system("lower") results in: lower: not found I want it to run "lower" just like it would if I typed "lower" at the bash prompt. How can I do that? From dakidd at sonic.net Mon Sep 15 02:30:44 2003 From: dakidd at sonic.net (Don Bruder) Date: Mon, 15 Sep 2003 06:30:44 GMT Subject: Advice from Jeff (Was Re: Is there "let binding" in Python?) References: <20030914214340.13608.qmail@web40904.mail.yahoo.com> <mailman.1063592122.17998.python-list@python.org> Message-ID: <o0d9b.21665$dk4.674856@typhoon.sonic.net> In article <mailman.1063592122.17998.python-list at python.org>, Jeff Epler <jepler at unpythonic.net> wrote: <major snippage> > Not an answer, but advice: when writing programs in Python, write Python > programs. Gawd, but that's profound! And on several levels... No... I'm serious. But I'm also smiling. > If it's your task to translate some Scheme (or any other > language) into Python as literally as possible, my heart goes out to you. How miserable do you expect me to be translating from Python to C/C++ as literally as possible? Sounds like you think the Scheme guy has some serious heartbreak ahead. So far, with a good working knowledge of C, and picking up serious steam in C++ as I go, (Note 1) I'm trying to take a Python program to C/C++, with a preference for C++. So far, here at the very beginning of the start of the project, things *SEEM* to be going well. I've got several simple routines from one of the classes converted into pieces of a C++ class, and a few stub routines, and it compiles & runs. Note 1: Been trying to teach myself C++ for a while now, and doing this port is sorta my final exam in "Don learns C++ 101". Do I know enough to make it happen? I do? Great! I don't? Drat! Go RTFM some more to see what I've missed and correct the lack if I can figure out how. And if I can't figure it out that way, well... There's always consulting with the faculty and student body of Usenet University - Umpty-two-million experts in 14-gazillion fields can't *ALL* be wrong simultaneously. I hope... :) On the way, I expect I'll pick up more than a little ability to read a Python program, even if I never manage to type in a single line of Python code. Not that learning to code in Python is a goal of this project of mine, but hey... you can't avoid getting some of the source language rubbed off on you when doing a port. Not if you want the port to work, anyway. Who knows... In the process of doing the port, I may begin to like Python enough to actually try to use it. -- Don Bruder - dakidd at sonic.net <--- Preferred Email - SpamAssassinated. Hate SPAM? See <http://www.spamassassin.org> for some seriously great info. I will choose a path that's clear: I will choose Free Will! - N. Peart Fly trap info pages: <http://www.sonic.net/~dakidd/Horses/FlyTrap/index.html> From jdhunter at ace.bsd.uchicago.edu Wed Sep 10 16:34:56 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 10 Sep 2003 15:34:56 -0500 Subject: ANN hashtar 0.1: archival encryption to corruptible media Message-ID: <m2he3kfklr.fsf@mother.paradise.lost> hashtar is a utility designed for encrypted archiving to media vulnerable to corruption (eg, CDR, DVDR). http://nitace.bsd.uchicago.edu:8080/hashtar Comments, bug reports, suggestions for improvement all welcome. John Hunter OVERVIEW hashtar: an encrypted archive utility designed for secure archiving to media vulnerable to corruption. Recursively encrypt the files and directories passed as arguments. Rather than preserving the directory structure, or archiving to a single file as in tar, the files are encrypted to a single dir and named with the hash of their relative path. The file information (filename, hash, permission mode, uid, gid) is encrypted and stored in the header of the file itself, and can be used to restore the original file with dir structure from the archive file. For example, the command > hashtar.py -cvf tmp.htar finance/ prompts for a password and generates an encrypted recursive archive of the finance dir in the tmp.htar dir, with filenames mapped like finance/irs/98/f1040.pdf -> tmp.htar/e5/e5ed546c0bc0191d80d791bc2f73c890 finance/sale_house/notes -> tmp.htar/58/580e89bad7563ae76c295f75aecea030 finance/online/accounts.gz.mcr -> tmp.htar/bb/bbf12f06dc3fcee04067d40b9781f4a8 finance/phone/prepaid1242.doc -> tmp.htar/c1/c1fe52a9d8cbef55eff8840d379d972a The encrypted files are placed in subdirs based on the first two characters in their hash name because if too many files are placed in one dir, it may not be possible to pass all of them as command line arguments to the restore command. The entire finance dir structure can later be restored with > hashtar.py -xvf tmp.htar The advantage of this method of encrypted archiving, as opposed to archiving to a single tar file and encrypting it, is that this method is not sensitive to single byte corruption, which becomes important especially on externally stored archives, such as on CDR, or DVDR. Any individual file contains all the information needed to restore itself, with directory structure, permission bits, etc. So only the specific files that are corrupted on the media will be lost. The alternative strategy, encrypting all the files in place and then archiving to external media, doesn't suffer from single byte corruption but affords less privacy since the filenames, dir structure, and permission bits are available, and less security since a filename may indicate contents and thus expose the archive to a known plaintext attack. A match string allows you to only extract files matching a given pattern. Eg, to only extract pdf and xls files, do > hashtar.py -m pdf,xls -xvf tmp.htar Because the filenames are stored in the header, only a small portion of the file needs to be decrypted to determine the match, so this is quite fast. Data can be encrypted and decrypted across platforms (tested between linux and win32 and vice-versa) but of course some information may be lost, such as uid, gid for platforms that don't support it. USAGE: > hashtar.py [OPTIONS] files OPTIONS -h, --help Show help message and exit -fDIR, --arcdir=DIR Write hashed filenames to archive dir -pFILE, --passwdfile=FILE Get passwd from FILE, otherwise prompt -mPATTERN, --match=PATTERN Only extract files that match PATTERN. PATTERN is a comma separated list of strings, one of which must match the filename -u, --unlink Delete files after archiving them -c, --create Create archive dir -x, --extract Extract files recursively from archive dir -v, --verbose Decrypt files recursively WARNING: I think this software is suitable to protect your data from your sister, your boss, and even the nosy computer hacker next door, but not the NSA. REQUIREMENTS: python2.3 - python.org yawPyCrypto and Flatten - http://yawpycrypto.sourceforge.net/ pycrypto - http://www.amk.ca/python/code/crypto.html The python dependencies are very easy to install; just do the usual > python setup.py install PLATFORMS: Tested on linux and win32 AUTHOR: John D. Hunter <jdhunter at ace.bsd.uchicago.edu> LICENSE: same as python2.3 KNOWN BUGS: Ignores symbolic links DEDICATION: For Erik Curiel, who's life's work I lost when I volunteered to backup the only copy of his home dir on a CD containing a single encrypted gzipped tar file, which was subsequently corrupted. From jussij at zeusedit.com Wed Sep 10 18:49:13 2003 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Thu, 11 Sep 2003 08:49:13 +1000 Subject: My future Python IDE article References: <Ft5S/kKkX87K092yn@gnosis.cx> <mailman.1061926129.29249.python-list@python.org> <84fc4588.0309110205.c885e29@posting.google.com> Message-ID: <3F5FAA69.1086@zeusedit.com> Anand Pillai wrote: > > > David Mertz wrote: > > > So c.l.py readers... make the case for your favorite one > > > getting on the list. > > GNU Emacs + python-mode is my favorite. > Apart from that I use: > > 1. XEmacs + python-mode, (not as good as Emacs + python-mode) > 2. IDLE I you develop for python on the Windows platform I suggest taking a look at Zeus. http://www.zeusedit.com/lookmain.html Zeus has a built in python scripting engine, while the built in class browser, auto complete and sytnax highlighting all support pyhton. Jussi Jumppanen Author of: Zeus for Windows (All new version 3.90 out now) "The C/C++, Cobol, Java, HTML, Python, PHP, Perl programmer's editor" Home Page: http://www.zeusedit.com From jussij at zeusedit.com Tue Sep 30 19:37:14 2003 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Wed, 01 Oct 2003 09:37:14 +1000 Subject: IDE Python References: <blcsi4$c2i$1@news-reader3.wanadoo.fr> Message-ID: <3F7A13AA.7827@zeusedit.com> jean.kasapyan wrote: > I search Python IDE with Code Intellisense You did not specify which platform, but if you develop on the Windows platform the latest version of Zeus does this. Once you create a Zeus workspace, Zeus will automatically run ctags to produce a tags database, will populate a class tree with this data and it also the tags information for code intellisensing: http://www.zeusedit.com/lookclass.html Jussi Jumppanen Author of: Zeus for Windows (All new version 3.90 out now) "The C/C++, Cobol, Java, HTML, Python, PHP, Perl programmer's editor" Home Page: http://www.zeusedit.com From max at alcyone.com Wed Sep 24 18:37:46 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 24 Sep 2003 15:37:46 -0700 Subject: CGI Redirect to another page References: <NW7cb.525$0j5.737525852@newssvr11.news.prodigy.com> <09a3d6364c.tim@worthy.demon.co.uk> <2c60a528.0309240338.1e4dd261@posting.google.com> <uoocb.691$291.949392743@newssvr11.news.prodigy.com> Message-ID: <3F721CBA.CF114FF@alcyone.com> Andrew Chalk wrote: > What is wrong with meta-refresh? The use of the Location header is much more direct. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ An undevout astronomer is mad. \__/ Edward Young From essai1 at mci.local Wed Sep 10 18:21:29 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Thu, 11 Sep 2003 00:21:29 +0200 Subject: TTF fonts rendered in Python References: <mailman.1063224795.24414.python-list@python.org> Message-ID: <bjo87i$tse$1@news-reader2.wanadoo.fr> PIL ? http://www.pythonware.com/products/pil/ -- Michel Claveau From oser at hep.uchicago.edu Mon Sep 1 04:13:31 2003 From: oser at hep.uchicago.edu (Scott Oser) Date: Mon, 1 Sep 2003 08:13:31 GMT Subject: Account error Message-ID: <200309010813.h818DVjI15770787@hep.uchicago.edu> This account no longer exists. From aleax at aleax.it Fri Sep 5 10:48:30 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 14:48:30 GMT Subject: Invisible function attributes References: <51809ae4.0309030715.7706cadb@posting.google.com> <87he3tfopa.fsf@pobox.com> <51809ae4.0309040627.28d7a075@posting.google.com> Message-ID: <2n16b.18138$hE5.641055@news1.tin.it> Olivier Lefevre wrote: ... > function is a class) and, since functions can't have instances, treating > it as a sort of static member of the function, which should be available > as soon as declared. Obviously I got it all wrong. Instead, they work Basically only in the "declared" part. Python has no declarations, only executable statements. > like local variables except that they "persist" after the function has > exited. That still feels weird to me. What are they used for? Give me > a compelling reason to have such a beast in the language. The ability to associate arbitrary information with a function can be used by any framework for the framework's own purposes. Historically, some frameworks were (ab)using function's docstrings (attribute __doc__) for such purposes; arbitrary function attributes were added to Python so that frameworks would use them instead of __doc__, leaving the latter free for its intended use, i.e., human-readable documentation. For a small-scale toy example, consider an "accumulator-maker". One way you could code it might be: def makeAccumulator(): def accumulate(x): accumulate.total += x accumulate.total = 0 return accumulate to be used, e.g., as: a = makeAccumulator() for x in (3, 4, 10, 23, 12): a(x) print a.total Of course, one could redesign makeAccumulator to return a class instance rather than a function: class makeAccumulator(object): def __init__(self): self.total = 0 def __call__(self, x): self.total += x to be used in the same way. Generally, classes and their instances are a more general and powerful way than closures &c to associate data and behavior in Python. Still, Python does support closures to some limited extent, and the ability to associate arbitrary attributes to each function object can be seen, in part, as a natural complement for that support. Alex From admin4055 at centrum.cz Sat Sep 20 07:57:48 2003 From: admin4055 at centrum.cz (Ivan Letal) Date: Sat, 20 Sep 2003 13:57:48 +0200 Subject: console chat Message-ID: <bkhf8h$1tio$1@ns.felk.cvut.cz> I want to make a python script which connects to a server to start getting data and interacts with user in the same time ala chat. I want it to run in a terminal/console. After I connect a socket, how to ensure that it is writing text from the server if there is any waiting for possible user input in the same time? Thanks From tzot at sil-tec.gr Tue Sep 16 13:08:53 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 16 Sep 2003 20:08:53 +0300 Subject: tuples vs lists References: <bk7eo9$g4g$1@bagan.srce.hr> Message-ID: <9egemvkhp2s55horjr9dfveml22158d62g@4ax.com> On Tue, 16 Sep 2003 18:51:38 +0200, rumours say that "Ivan Voras" <ivoras at fer.hr> might have written: >Are there any performance/size differences between using tuples and using >lists? Assuming you know that tuples are immutable and lists are mutable (they can grow, shrink, get sorted etc), tuples consume less memory (lists allocate more memory than your list needs, to avoid reallocating space on every append/insert). This accounts for size. Performance-wise, I don't think there is a noticable difference between indexing lists and tuples (but you can always use the timeit module). IIRC Guido has stated that tuples are not intended to be immutable lists, but a kind of handy unnamed structs (a la C) or records (a la Pascal). Keep in mind also that lists have useful methods (like count and index) that tuples don't. This about functionality. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From timr at probo.com Sun Sep 7 00:23:21 2003 From: timr at probo.com (Tim Roberts) Date: Sat, 06 Sep 2003 21:23:21 -0700 Subject: in Ram database? References: <v03110742bb7da1ba2767@[192.168.0.2]> <mailman.1062819310.17917.python-list@python.org> Message-ID: <racllvoqohn84k1fb4o1iaavbpud478h8g@4ax.com> William Trenker <wtrenker at shaw.ca> wrote: > >Here is a simple example: > >import sqlite #module name exposed by the PySQLite wrapper >conn = sqlite.connect(db=':memory:') #special connect string to open an in-memory db >cursor = conn.cursor() #standard DB-API-2 from this point >cursor.execute('create table test (a varchar, b int);') >cursor.execute('commit;') #end PySQLite implicit transaction >cursor.execute('begin transaction;') #wrap the inserts in an explicit transaction for speed >for i in range(0,10000): > cursor.execute('insert into test (a,b) values (%s,%i);'%(str(i),i)) >cursor.execute('commit;') >cursor.execute('select sum(b) from test;') >print cursor.fetchall()[0][0] This fails for me. There seems to be quite a bit of confusion in sqlite.py regarding the transaction state. The Connection object maintains a flag called inTransaction that doesn't get cleared when you call "commit" through the Cursor, so the script fails during termination because the Connection tries to rollback what IT thinks is an open transaction. So, I tried changing it to use conn.commit() instead of cursor.execute("commit"), but that causes a new problem: the cursor.execute("begin transaction") fails beause cursor.execute automatically opens a new transaction before sending the SQL to the engine, and nested transactions aren't allowed. Deleting the call to "begin transaction" solves that problem, because the first "execute" in the loop causes a transaction to be opened automatically. Hmmm; this may be an opportunity for me to actually contribute to pysqlite, which is one of the more useful things I've come across in Python. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rob at cs.brown.edu Thu Sep 18 18:58:51 2003 From: rob at cs.brown.edu (Rob Hunter) Date: Thu, 18 Sep 2003 18:58:51 -0400 Subject: Binding frustration In-Reply-To: <l4mcnWRY6vxusveiU-KYgg@comcast.com> Message-ID: <ABC96B8C-EA2B-11D7-967C-003065F081D2@cs.brown.edu> On Thursday, September 18, 2003, at 06:21 PM, Terry Reedy wrote: > > "Rob Hunter" <rob at cs.brown.edu> wrote in message > news:mailman.1063920805.24865.python-list at python.org... >> def inGenre(g): # g is a genre >> if <here I test if "title" is of genre g (using a simple > Python >> dictionary I have collected from a mini web crawl)>: >> result = result + [g] # if title is of genre g, then > add >> it to the accumulator >> >> UnboundLocalError: local variable 'result' referenced before > assignment > > When, within a function, you assign to a variable that has not been > declared global, then you implicitly declare that variable to be local > to the function -- in this case, inGenre(). But local var 'result' > has not previously been assigned a value within inGenre. Hence the > error message. As JCM said, try result.append(g). So it seems that if Python made a syntactic distinction between introducing a new binding, and assigning to an old one, then this problem would go away. That's what is happening with result.append(g), right? Because of the syntax in this statement (ie, there's no "=" in it), Python knows that _result_ must exist, so it goes and looks for it. But, IMO, I *should* be allowed to use the + (append) operator. Because there is no syntax for a new binding (like LET, for example), Python awkwardly forces the programmer to choose either the local scope or the global one when it comes to assignment. And so, in my case, it forces me to use another (but semantically, quite similar) language construct. Does anyone know why they didn't have an explicitly new binding syntax? Perhaps to minimize the initial part of the learning curve. This makes sense, but I would have much preferred it the other way. Rob > > Terry J. Reedy > > > -- > http://mail.python.org/mailman/listinfo/python-list > From sross at connectmail.carleton.ca Tue Sep 2 11:45:08 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 2 Sep 2003 11:45:08 -0400 Subject: Docs on speeding up Python code? References: <bj2can$17ea$1@f1node01.rhrz.uni-bonn.de> Message-ID: <pV25b.843$I_2.211439@news20.bellglobal.com> "Andreas Neudecker" <a.neudecker at uni-bonn.de> wrote in message news:bj2can$17ea$1 at f1node01.rhrz.uni-bonn.de... > Is there anywhere a concise Howto, article, PEP, whatever that describes > possible measures to make Python code faster (and probably 'cleaner', > too)? And possibly in a way, that a beginner or intermediate Python user > can understand? ;-) > > If you know of any such docs, I would be happy if you could post some links. > http://manatee.mojam.com/~skip/python/fastpython.html HTH Sean From jdhunter at ace.bsd.uchicago.edu Tue Sep 16 13:50:16 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 16 Sep 2003 12:50:16 -0500 Subject: distutils on win32 with link.exe -- use dlls? Message-ID: <m2r82g4o87.fsf@mother.paradise.lost> I am using distutils to build a python extension module on win32. I initialize the Extension class with a list of libraries with Extension("_gd", ["_gdmodule.c"], include_dirs=incdirs, library_dirs=libdirs, libraries=libs, define_macros=macros)], and am using VC6++ where libs is a list ['gd', 'png', ...]. Distutils produces a link command with the required libraries as link.exe blahblah gd.lib png.lib jpeg.lib blahblah However, I have DLL versions of these libraries in my library path, ie, libgd.dll, libjpeg.dll, etc... Is there a macro or compile flag or other setting to inform distutils to look for the DLLS of the required libraries rather than the *.lib files? Thanks, John Hunter From CousinStanley at hotmail.com Wed Sep 24 21:37:48 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 24 Sep 2003 18:37:48 -0700 Subject: RELEASED Python 2.3.1 References: <mailman.1064390741.20344.python-list@python.org> <bksi8l$5bce8$1@ID-130333.news.uni-berlin.de> <u172glc2.fsf@python.net> Message-ID: <bktgkc$5gk64$1@ID-130333.news.uni-berlin.de> | There's a checkbox which you can uncheck | to disable installing the htmlhelp file. | | Then you can download the HTML archive | and install it manually. Thomas .... Thanks for the reply .... It's good to know that an alternative for the individual HTML doc files will remain .... Would it be feasible to eliminate the Python Docs from the standard distribution and always download separately if desired ???? This would eliminate downloading the docs twice if the user wants the separate doc files and provide a leaner download for non-programming Python users that will never develop anything in Python themselves but who want a run-time environment only .... -- Cousin Stanley Human Being Phoenix, Arizona From cbbrowne at acm.org Tue Sep 2 17:03:17 2003 From: cbbrowne at acm.org (Christopher Browne) Date: 2 Sep 2003 21:03:17 GMT Subject: what's wrong with REBOL? References: <6005702b.0309020727.4ba46e78@posting.google.com> Message-ID: <bj30il$eoev7$2@ID-125932.news.uni-berlin.de> After takin a swig o' Arrakan spice grog, mnhenley at msn.com (Mike Henley) belched out...: > I first came across rebol a while ago; it seemed interesting but then > i was put off by its proprietary nature, although the core of the > language is a free download. .. much omitted ... > What's wrong with Rebol? "What's wrong" is that 'proprietary nature.' If I write code in Perl, Python, or Ruby, I can be certain that I won't get bitten because of someone pulling the rug out from under them. I can't be certain in the same way of the perpetual availability of REBOL. Furthermore, if I am considering whether to build and contribute a module to REBOL (where the user base is necessarily limited) or to Perl/Python/Ruby, I'd be more inclined to do the latter. And so there are LOTS of third party libraries for these other languages. -- (reverse (concatenate 'string "moc.enworbbc" "@" "enworbbc")) http://cbbrowne.com/info/linuxdistributions.html Rules of the Evil Overlord #102. "I will not waste time making my enemy's death look like an accident -- I'm not accountable to anyone and my other enemies wouldn't believe it. From hildegarde_roth at yahoo.de Thu Sep 18 14:28:41 2003 From: hildegarde_roth at yahoo.de (Hilde Roth) Date: 18 Sep 2003 11:28:41 -0700 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <bk80n3$rsb$03$1@news.t-online.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <87znh26z7y.fsf@pobox.com> Message-ID: <95b4b9ac.0309181028.2e58b894@posting.google.com> > Numeric (and presumably numarray) can handle arbitrary Python objects. Oh. I will look at them pronto, then. As for: > I'd guess it's highly unlikely ever to be part of the standard > sequence protocol, though. Passing a slice is passing an abstraction of a sequence (since indexing a list with a slice returns a list). Given that, it seems hard to justify not accepting the sequence itself... Passing the abstraction rather than the thing itself should be an optimization, as in xrange vs. range, left to the discretion of the programmer. -- O.L. From python at sarcastic-horse.com Mon Sep 15 11:19:07 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Mon, 15 Sep 2003 11:19:07 -0400 (EDT) Subject: datetime: How to get diff between 2 dates in month units? In-Reply-To: <20030915000631.GB27698@ibook> References: <56819.199.169.240.132.1063397952.squirrel@svr1.turboweb.net> <20030915000631.GB27698@ibook> Message-ID: <46665.199.169.240.132.1063639147.squirrel@svr1.turboweb.net> This is a great module. Thanks for the link. What do you think about using operator overloading to avoid having to do the mx.DateTime.RelativeDateDiff(...) function instead? >> I have a lot of monthly time series data. I need to be able to compare >> two dates and get the number of months that they are apart. > [...] > > If you can rely on external modules, you may use mx.DateTime for that. > >> >>> d1 = datetime.date(2002,1,1) >> >>> d2 = datetime.date(2001,12,1) >> >>> diff = d1-d2 >> >>> diff.days >> 31 > > This would be: > >>>> d1 = DateTime.Date(2002,1,1) >>>> d2 = DateTime.Date(2001,12,1) >>>> diff = DateTime.RelativeDateDiff(d1,d2) >>>> diff.months > 1 > > [...] >> >>>firstdate = newMonthlyDatetime(2002, 5) >> >>>Nov2002 = newMonthlyDatetime(2002, 11) >> >>>diff = Nov2002 - firstdate >> >>>diff.months >> 6 > > And this would be: > >>>> firstdate = DateTime.Date(2002, 5) >>>> Nov2002 = DateTime.Date(2002, 11) >>>> diff = DateTime.RelativeDateDiff(Nov2002, firstdate) >>>> diff.months > 6 > > -- > Gustavo Niemeyer > http://niemeyer.net > From jrbexbox at hotmail.com Mon Sep 8 10:31:35 2003 From: jrbexbox at hotmail.com (Rebecca Taylor) Date: 8 Sep 2003 07:31:35 -0700 Subject: win32com python AttributeError! Message-ID: <f431a335.0309080631.43c5fad1@posting.google.com> Hi, I am having trouble with win32com for python. I get the following error when I try to issue any command after using Dispatch. >>> xl=win32com.client.Dispatch("Excel.Application") >>> xl.Visible=0 Traceback (most recent call last): File "<pyshell#7>", line 1, in ? xl.Visible=0 File "D:\Python22\Lib\site-packages\win32com\client\dynamic.py", line 504, in __setattr__ raise AttributeError, "Property '%s.%s' can not be set." % (self._username_, attr) AttributeError: Property 'Excel.Application.Visible' can not be set. >>> I have programs that I used to use all the time and they simply won't run. Is this an error with python or win32com or my setup? Thanks, -rebecca From eric.brunel at pragmadev.N0SP4M.com Wed Sep 24 05:47:54 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Wed, 24 Sep 2003 11:47:54 +0200 Subject: Python <-> C via sockets References: <8ad2cfb3.0309240113.19d9198a@posting.google.com> Message-ID: <bkroq8$8ud$1@news-reader1.wanadoo.fr> Nick Keighley wrote: > I'm probably missing something rather obvious, but is there a known > problem with getting a Python based socket program to communicate with > a C based socket program? A simple echo server written in Python > (the example from Python in a Nutshell actually) will happily talk > to a Python based client. If a C based client is substitued the connection > is refused (or so the C client reports). The C client will talk to > a C server. Communications between C and Python via sockets definetly work: we do that every day (no kidding ;-) Can you post an example of your code? -- - Eric Brunel <eric dot brunel at pragmadev dot com> - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From anton at vredegoor.doge.nl Mon Sep 1 05:19:25 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 01 Sep 2003 11:19:25 +0200 Subject: Declaration of an array of unspecified size References: <m814lvc8h44vbd5g1m2iv05r33qg8ag9ta@news.stofanet.dk> <biu6k0$c8fs4$1@ID-67890.news.uni-berlin.de> Message-ID: <biv3jc$h3b$1@news.hccnet.nl> "Ulrich Petri" <ulope at gmx.de> wrote: >An optimzed (untested) version: > >class PopMailServer: > def __init__(self, host, user, pass): > self.host = host > self.user = user > self.password = pass > self.mail = [] > > def action(self): > pop = poplib.POP3(self.host) > pop.user(self.user) > pop.pass_(self.password) > for x in p.list()[1]: > num, len = x.split() > self.mail.append(pop.retr(num)[1]) > pop.quit() > print "Total mails: %d" % len(self.mail) > >of course this lacks exception handling... You followed the OP into using "pop" as a name for an instance. However "pop" is also a *method* of type list. While it's not as bad as for example using the name "str" for a string ("str" is a build-in function which is not reachable anymore if it's name is used this way) this still makes my spider sense tingle. Whether it's because you failed to mention this or just because it's dialectical I don't know :-) Anton From sross at connectmail.carleton.ca Tue Sep 23 01:14:57 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 23 Sep 2003 01:14:57 -0400 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <SnObb.1581$PT3.257319@news20.bellglobal.com> <63gvmvcf6iakbs8pgll7u8ogblkbqld6fp@4ax.com> Message-ID: <6EQbb.1770$PT3.279727@news20.bellglobal.com> "Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message > Personally, I think the conventional '..' has more chance than your > '...'. Hi. Actually, I think '...' is more conventional notation for expressing a range of numbers. Like when you want to show a sequence: # odd numbers greater than 3, but less than 257 5, 7, 9, 11, ..., 255, 257 That sort of thing. Also, '...' is one dot further away from a single dot '.', than is '..'. Is that important? Maybe. I figure it takes away one argument: "a..b looks too much like a.b" by saying "Well, a...b doesn't" Of course, a#%$^^#b doesn't either.... Anyway ... > >Leaving the ellipsis aside, you could add methods to int/long (also ala > >Ruby), > > > >for i in 0.upto(10): > > # suite > > > ># to count down > >for i in 10.downto(0): > > # suite > > I'm not sure about this - I'm bouncing between "that's neat!" and > "yuck!", but the "yuck!" part may just mean I need to get used to it. > I'm more: I've seen it in Ruby and Smalltalk (where integers have such methods), and it's not '...' , nor is it range(), so that might be an alternative. Whether it is a good alternative ... <shrug>. It doesn't add new syntax, only new methods to existing objects. But, it does not appear to provide any marked improvement over range (or xrange). So, it's neither here nor there for me. In my own language, were I to make one, I would use: for i in start to stop by step: # suite But, that's not going to happen in this language; neither do I expect it to, nor would I ask for it (I'd make my own, if I really wanted it). Still, it's interesting to play with different formulations, to see if they do or do not work well. From ktilton at nyc.rr.com Wed Sep 3 15:00:11 2003 From: ktilton at nyc.rr.com (Kenny Tilton) Date: Wed, 03 Sep 2003 19:00:11 GMT Subject: Lisp with Kenny! <g> Message-ID: <3F5639FA.9000600@nyc.rr.com> No, seriously, I want to do some free Lisp classes for anyone interested. One or two nights a week. BYO computer or use one of mine. BYO code to work on, or we can work thru the CL text of your choice. (But do snag one, or find something on-line you want to follow.) btw, don't be shy. I enjoy teaching and am accustomed to helping folks at different levels of experience. Anyone prepared to make the effort will have a good time. Peer-tutoring is cool, so you can also help each other, and other strong lispniks are welcome to drop in. If you are interested, please let me know which evening(s) are best for you. (Tuesdays seem to be taken already.) The location will be: 171 West 73rd St, NYC 10023, just east of Amsterdam Ave. -- kenny tilton clinisys, inc http://www.tilton-technology.com/ --------------------------------------------------------------- "Career highlights? I had two. I got an intentional walk from Sandy Koufax and I got out of a rundown against the Mets." -- Bob Uecker From __peter__ at web.de Mon Sep 29 14:06:23 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Sep 2003 20:06:23 +0200 Subject: A startup puzzle References: <vngnif6v8ip4c6@corp.supernews.com> Message-ID: <bl9sds$8b0$07$1@news.t-online.com> Edward K. Ream wrote: > I've just about convinced myself there is no good, clean solution to the > following puzzle. I wonder if you agree. If I understand you correctly, you do leoGlobals.py _app=None def app(): global _app if not _app: # other code _app = Application() return _app leoMain.py from leoGlobals import * app = app() app.mainLoop() leoOther.py from leoGlobals import * app().doSomething() Does it happen that your program runs without ever creating the Application instance? If not, there's no point in lazy creation: leoGlobals.py app=None def createApp(): global app assert not app app = Application() leoMain.py from leoGlobals import * createApp() app.mainLoop() leoOther.py from leoGlobals import * # this works iff you can ensure that leoMain.py is the # only "entry point" to your application app.doSomething() If I missed something, it would probably help if you post similar code fragments to show where the above scheme would fail to work. Peter From joerg.maier at rz.uni-mannheim.de Sat Sep 6 13:16:39 2003 From: joerg.maier at rz.uni-mannheim.de (=?ISO-8859-15?Q?J=F6rg?= Maier) Date: Sat, 06 Sep 2003 19:16:39 +0200 Subject: cygwin python with Tkinter and pexpect module Message-ID: <bjd4t7$gn0fe$1@ID-181971.news.uni-berlin.de> Hey guys, i have a big problem using Tkinter and pexpect in cygwin. i try to program an winscp-like rsync Program for all posix Platforms (linux, macosx, cygwin). i got a class SslConnection with a method listDirectory that gives back a list of an remote directory using pexpect. this method works in linux, it works in cygwin-python from command-line, but invoked in an Tkinter-Program i got the strange Exception: E:\cygwin\bin\python2.3.exe: *** unable to remap E:\cygwin\bin\tk84.dll to same address as parent(0x710000) != 0xC20000 28 [main] python 604 sync_with_child: child 1848(0x63C) died before initialization with status code 0x1 3133 [main] python 604 sync_with_child: *** child state child loading dlls E:\cygwin\bin\python2.3.exe: *** unable to remap E:\cygwin\bin\tk84.dll to same address as parent(0x710000) != 0xC20000 174653 [main] python 604 sync_with_child: child 1932(0x5F8) died before initial ization with status code 0x1 203190 [main] python 604 sync_with_child: *** child state child loading dlls dont know what to do , gui-program is running under linux. Any ideas? Is this a bug in cygwin tcltk? thanks for every advice, joerg -- Hi I am a signature virus. Please copy me to your .signature file to help me spread. From sross at connectmail.carleton.ca Fri Sep 26 14:42:28 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 26 Sep 2003 14:42:28 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <wCGcb.3064$yU5.2141@nwrdny01.gnilink.net> <8RScb.169633$R32.5449258@news2.tin.it> <uk77vhagj.fsf@boost-consulting.com> <WNYcb.12686$yD1.1505440@news20.bellglobal.com> <eppstein-B529F3.09181826092003@news.service.uci.edu> <dJ_cb.13620$yD1.1517951@news20.bellglobal.com> <eppstein-AF4213.10592426092003@news.service.uci.edu> Message-ID: <5L%cb.13662$yD1.1524835@news20.bellglobal.com> "David Eppstein" <eppstein at ics.uci.edu> wrote in message news:eppstein-AF4213.10592426092003 at news.service.uci.edu... > Your proposed name has an implication for the semantics. Do the implied semantics of ireverse() differ from those implied by the names iter_backwards(), reverse_view(), riter(), etc.? Because, to me, they' re just different words for the same idea. > I was questioning the feasibility of the implied semantics. Fine. Take it up with the person who proposed the idea. > I don't think you're let off the hook by the excuse that "it's only a name". I'm let off the "hook" because I was never on it. The responsibility for answering your questions re: the feasability of this enterprise do not fall to me, but to the proponent of the enterprise. It's like someone said they where going to build a bridge from the mainland to Hawaii, and that they would paint it green. And I said, "What about painting it red?" And you asked me, "And how to you propose to build this bridge?". My answer is, "Uh, why don't you ask the fellow over there who brought up the thing in the first place. I'm just talking paint colours over here." I think your questions are mis-directed. And, even if they are not, I don't have your answers, I'm not going to try to come up with them, and I feel no responsibility to do so. From jean.kasapyan at wanadoo.fr Tue Sep 30 17:28:35 2003 From: jean.kasapyan at wanadoo.fr (jean.kasapyan) Date: Tue, 30 Sep 2003 23:28:35 +0200 Subject: IDE Python Message-ID: <blcsi4$c2i$1@news-reader3.wanadoo.fr> Hello, I search Python IDE with Code Intellisense Thanks JEAN From felix_mcallister at hotmail.com Tue Sep 16 03:17:20 2003 From: felix_mcallister at hotmail.com (Felix McAllister) Date: Tue, 16 Sep 2003 08:17:20 +0100 Subject: Win32 Com + ADO: How to compare the result of a recordset to 'nothing' References: <tvj9b.31786$pK2.53500@news.indigo.ie> Message-ID: <8Oy9b.31875$pK2.53696@news.indigo.ie> Thanks to all who replied to my posting. There were a number of things wrong with my code. 1. Giles Brown was correct in stating that the NextRecordset method returns a tuple. I should have seen this in the debugger when I printed the value out: [Dbg]>>> rs.NextRecordset() (<COMObject NextRecordset>, -1) 2. There was a typo in the call to NextRecordset - I had "NextRecordSet" [capital S]. I didn't know that case mattered. The correct loop code is as follows: while rs != None: rs.MoveFirst() while not rs.EOF: xmlString = xmlString + rs.Fields[0].Value rs.MoveNext() rs = rs.NextRecordset()[0] Felix. > Hi, > When using win32com.client, how do you test for a 'nothing' com object as you can in VB? I have an example here when using ADO to loop over multiple recordsets returned from a query. I get the following error: > > Traceback (most recent call last): > File "C:\dev\python\MySamples\dbtest.py", line 14, in ? > rs.MoveFirst() > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 460, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: <unknown>.MoveFirst > > I'm assuming that after the result of rs.NextRecordSet is invalid somehow (it shouldn't be, BTW, as a similar loop runs fine in VB). > > In Perl, I'd just use : if (defined($rs).... > > Any help appreciated, > > Felix. > > The code is as follows: > ###########################3 > import win32com.client > conn = win32com.client.Dispatch("ADODB.Connection") > conn.ConnectionString = "Driver={SQL Server};Server=(local);Database=Test;Trusted_Connection=yes;" > conn.Open() > rs = conn.Execute("TestSPXML")[0] > xmlString = "" > while rs != None: > rs.MoveFirst() # FAILS HERE ON THE SECOND ITERATION OF THE LOOP > while not rs.EOF: > xmlString = xmlString + rs.Fields[0].Value > rs.MoveNext() > rs = rs.NextRecordSet() > print xmlString > conn.Close() From eppstein at ics.uci.edu Tue Sep 23 15:26:56 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 23 Sep 2003 12:26:56 -0700 Subject: Thoughts on PEP284 References: <mailman.1064341934.21653.python-list@python.org> Message-ID: <eppstein-CA53C5.12265623092003@news.service.uci.edu> In article <mailman.1064341934.21653.python-list at python.org>, Michael Chermside <mcherm at mcherm.com> wrote: > Stephen Horne writes: > > True, it is mostly just an alternative notation for range or xrange. > > But the integer for loops thing is something that never seems to go > > away. PEP284 itself quotes four previous PEPs on broadly the same > > issue. > > I am of the opinion that the introduction of enumerate() (in 2.3) will > go a long ways toward reducing the desire for better integer loop > syntax. I'm sure it will never go away completely, but if the demand > seems to die down after a year or so, then I'd guess it was due to > enumerate(). It will certainly reduce the typical range(len(L)) verbosity. It doesn't do anything to help the readability of expressions like range(dim-2,-1,-1) (example from some code I wrote a couple weeks ago). Actually, looking at that code, the range is not the least readable part of it: if dim == 1: positions = dict([(s, (positions[s][0],0)) for s in positions]) elif dim == 2: positions = dict([(s, (2*positions[s][0],2*positions[s][1])) for s in positions]) elif not place3d(): X = coordinate(range(1,dim)) Y = coordinate(range(dim-2,-1,-1)) positions = dict([(s, (X[s],Y[s])) for s in positions]) Dictionary comprehensions (PEP 274) would go a long way towards cleaning this up: if dim == 1: positions = {s: (positions[s][0],0) for s in positions} elif dim == 2: positions = {s: (2*positions[s][0],2*positions[s][1])) for s in positions} elif not place3d(): X = coordinate(range(1,dim)) Y = coordinate(range(dim-2,-1,-1)) positions = {s: (X[s],Y[s]) for s in positions} The use of PEP 284 syntax (replace the range by [i for dim-2 >= i >= 0]) would I think help but not as much. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From follower at iname.com Tue Sep 16 01:16:25 2003 From: follower at iname.com (Follower) Date: 15 Sep 2003 22:16:25 -0700 Subject: Finally found a use for lambda! References: <roy-FFBAC5.22283914092003@reader2.panix.com> <d2f38965.0309150133.4aef2253@posting.google.com> <840592e1.0309150557.37661282@posting.google.com> Message-ID: <d2f38965.0309152116.17830217@posting.google.com> >(ObMinimalism=Obfuscation Minimalism? Ob = Obligatory (Old school Usenet idiom...) This was in reference to the seemingly eternal programmer desire to reduce key strokes. And, as mentioned elsewhere, this is even fewer: self.failIf("bar" in foo) From mertz at gnosis.cx Wed Sep 3 00:32:19 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 03 Sep 2003 00:32:19 -0400 Subject: what's wrong with REBOL? References: <6005702b.0309020727.4ba46e78@posting.google.com> <bj30il$eoev7$2@ID-125932.news.uni-berlin.de> <mailman.1062542045.14859.python-list@python.org> <w4WV/kKkXY/L092yn@gnosis.cx> Message-ID: <T7WV/kKkXoAN092yn@gnosis.cx> Jeff Epler <jepler at unpythonic.net> wrote previously: |There are legal reasons: Perhaps the software will be found to violate |a patent, or infringe copyright. Perhaps it will be judged to violate a |DMCA-type law. Perhaps a new "software defects" law will be impossible |for free software to conform to (for instance, due to a requirement that |the software developer post a bond against damages caused by defects in |the software). Yeah... and perhaps the word 'disingenuous' will be removed from future editions of popular dictionaries; and then we will lack a concise way to describe "special pleading" of this sort. I think it's unlikely though. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From andrew-pythonlist at puzzling.org Sun Sep 28 22:09:08 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 29 Sep 2003 12:09:08 +1000 Subject: write a file "copy" program in Python for Unix and Windows... In-Reply-To: <rmMdb.366088$2x.112007@rwcrnsc52.ops.asp.att.net> References: <rmMdb.366088$2x.112007@rwcrnsc52.ops.asp.att.net> Message-ID: <20030929020908.GE2173@frobozz> On Mon, Sep 29, 2003 at 01:59:52AM +0000, Ben Kial wrote: > I need to write a program to "copy" files and preserved the files' > atime, mtime, ctime, file permissions. I also need to have this > program working in Unix and Windows, where the "Archive" > attribute on the file also has to be preserved (any more > Windows idiosyncrasies?). > > Any help will be very much appreciated. Thanks in advance. Try shutil.copy2 (and/or other functions in the shutil module). -Andrew. From ulope at gmx.de Fri Sep 19 08:23:25 2003 From: ulope at gmx.de (Ulrich Petri) Date: Fri, 19 Sep 2003 14:23:25 +0200 Subject: Binding frustration References: <mailman.1063925970.14284.python-list@python.org> Message-ID: <bkesft$105nn$1@ID-67890.news.uni-berlin.de> "Rob Hunter" <rob at cs.brown.edu> schrieb im Newsbeitrag news:mailman.1063925970.14284.python-list at python.org... > > So it seems that if Python made a syntactic distinction between > introducing a new binding, and assigning to an old one, then this > problem would go away. That's what is happening with result.append(g), > right? Because of the syntax in this statement (ie, there's no "=" in > it), Python knows that _result_ must exist, so it goes and looks for > it. But, IMO, I *should* be allowed to use the + (append) operator. > Because there is no syntax for a new binding (like LET, for example), > Python awkwardly forces the programmer to choose either the local scope > or the global one when it comes to assignment. And so, in my case, it > forces me to use another (but semantically, quite similar) language > construct. > What result.append(bla) does is not an "assignement to an old binding". It mutates the object that is bound to the name "result". In order to do so Python looks up the name in the local namespace if it isn't found there it looks in the namespace above and so on. Whenever you use the assignment syntax (foo = bar) you create a "new" binding unless you have declared the name global. HTH Ciao Ulrich From felix_mcallister at hotmail.com Mon Sep 15 11:35:56 2003 From: felix_mcallister at hotmail.com (Felix McAllister) Date: Mon, 15 Sep 2003 16:35:56 +0100 Subject: Win32 Com + ADO: How to compare the result of a recordset to 'nothing' References: <tvj9b.31786$pK2.53500@news.indigo.ie> <mailman.1063637661.28370.python-list@python.org> Message-ID: <A%k9b.31795$pK2.53440@news.indigo.ie> Bob, You need to change the (local) part of the connection string to a SQL Server instance on your machine or network. You might also have to change the Trusted Connection=yes part to use a SQL Server login name and password, if that instance isn't set up for trusted connections. Felix. From sfb at alysseum.com Fri Sep 19 19:29:48 2003 From: sfb at alysseum.com (Simon Bayling) Date: Fri, 19 Sep 2003 23:29:48 +0000 (UTC) Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <mailman.1063810287.4212.python-list@python.org> <6ee58e07.0309171548.314a046c@posting.google.com> <3y7ab.1043$Od.78860@twister.tampabay.rr.com> <3f697584$0$10966$fa0fcedb@lovejoy.zen.co.uk> <Xns93FAC750B300Ek23vzqpmre@194.106.32.13> <3f6a2bd3$0$10998$fa0fcedb@lovejoy.zen.co.uk> <6e07b825.0309182013.3ddeb760@posting.google.com> Message-ID: <Xns93FC50C7B120k23vzqpmre@194.106.32.13> I see your smiley, but still; Is there a bug so trivial that you would rather leave it than fix it? > You have our permission to go out an buy that second monitor, > so that this DREADFUL problem never happens again. ;^) - Simon. From exarkun at intarweb.us Mon Sep 1 15:50:10 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Mon, 1 Sep 2003 15:50:10 -0400 Subject: Traversing the object space. In-Reply-To: <6ee58e07.0309011031.5e56000b@posting.google.com> References: <6ee58e07.0309011031.5e56000b@posting.google.com> Message-ID: <20030901195010.GA10824@intarweb.us> On Mon, Sep 01, 2003 at 11:31:45AM -0700, Lothar Scholz wrote: > Ruby has a nice function that can traverse the complete object space > of your program. > > Is there anything like this in python ? It seems to be not in the > standart library but maybe i can find a short script somewhere else. > > It is a nice way for to do some memory checks to find out if a part of > your app is generating too much objects. import gc print gc.get_objects() Jp > -- > http://mail.python.org/mailman/listinfo/python-list -- "Pascal is Pascal is Pascal is dog meat." -- M. Devine and P. Larson, Computer Science 340 From itamar at itamarst.org Tue Sep 16 14:09:22 2003 From: itamar at itamarst.org (Itamar Shtull-Trauring) Date: Tue, 16 Sep 2003 14:09:22 -0400 Subject: ANN: Twisted networking framework 1.0.7 Message-ID: <20030916140922.357a87b7.itamar@itamarst.org> Twisted is an event-driven networking framework for server and client applications. For more information, visit http://www.twistedmatrix.com, join the list http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python or visit us on #twisted at irc.freenode.net. What's New in 1.0.7 =================== - Client Jabber support. - twisted.xish, an XML package supporting a DOM-like API and a XPATH-like API. - Woven web templating toolkit is now much faster, and no longer supports the interim APIs it had during development. - Security tightening in the web server, especially on Windows. - XML-RPC server is now easier to extend, and can publish the XML-RPC introspection API as an option. - Working minimum and maximum sizes for database connection pools. - New connection API for Perspective Broker, allowing easy SSL support, reconnection, etc.. - Better lenient HTML parsing in microdom. - Many improvements to mail protocols (SMTP, POP3, IMAP). - Continued switch to updated cred unified authentication backend in the various protocols supported by Twisted. - SOAP support now requires SOAPpy 0.10.1 or later. - mailmail, a replacement for the common usage of command-line /usr/sbin/sendmail. - Bug fixes, documentation improvements, more tests. What is Twisted? ================ Twisted is an event-driven framework for building networked clients and servers. It contains a powerful and simple networking core, a full-featured suite of interoperable protocols, among them a powerful web server and applications framework. Twisted supports many event loops for both server apps and GUI integration on the client side, including: - Win32 events, including GUI support - GTK+ - GTK+ 2 - Qt - wxPython - Tkinter Twisted can run protocols over TCP, SSL, UDP, multicast, Unix sockets and subprocesses. It also includes scheduling support, threading integration, RDBMS event loop integration and other basic requirements for networked applications. Also included are implementations of many protocols. In some cases this includes complete frameworks providing facilities on top of the base protocol: - SSH - IMAP - DNS - FTP (client only, server needs rewrite) - HTTP, including a complete web framework - Jabber client - XML-RPC server and client frameworks - SOAP server framework - NNTP and complete NNTP server framework - SOCKSv4 (server only) - SMTP - IRC - telnet - POP3 - AOL's instant messaging TOC - MSN messaging - OSCAR, used by AOL IM as well as ICQ (client only) - MouseMan serial mice, and GPS devices - Twisted Perspective Broker, a remote object protocol From aleax at aleax.it Sat Sep 6 11:17:24 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 06 Sep 2003 15:17:24 GMT Subject: Why python??? References: <mailman.1062790509.19411.python-list@python.org> <bjarq6$j45$00$1@news.t-online.com> <NO66b.30883$R32.926812@news2.tin.it> <bjb4hk$ohm$01$1@news.t-online.com> <Jbg6b.32033$R32.992758@news2.tin.it> <bjcbha$vmp$02$1@news.t-online.com> Message-ID: <8Um6b.34442$R32.1077180@news2.tin.it> Michael Peuser wrote: ... >> > (1) More power for same price - this works in favour of 'complex > software' >> > (2) Same power for less money - this works in favor of 'cheap software' >> >> And software is developed more cheaply in higher level languages than >> in lower level ones. Therefore, both [1] and [2] work in favour of >> HLL's, which let you develop more complex software for the same price or >> the same software (software of the same functional complexity, but more >> often than not somewhat hungrier of hardware resources) faster & cheaper. > > No one will ever dispute this. Oh good, because your assertions DID "dispute this" -- you very specifically claimed that there was no such thing helping Python as Moore's Law helped Linux!!! > The question is however: How much HLL is enough? That may be ONE question, and I'll gladly try to answer it if and when a language with a substantially higher level than Python is alternative for a project about which I get input. In general it's not trivial to stay BOTH very-high-level AND general purpose enough for a really wide range of tasks. A language we're developing at AB Strakt as part of the CAPS framework, for example, looks like...: attribute salary is Currency "Salario mensile" restriction quantity(1) on create code Python if value[0] < minimumSalary: value = [ minimumSalary ] return value %% etc -- now THAT is a higher-level language than Python, and it's a dream to use for directly transcribing into executable code the results of ERD analysis for typical business applications to be deployed as multi-layer clients/middleware/server distributed apps; but I wouldn't even DREAM of using it to program a completely different kind of application, such as a videogame, a compiler, a web-spider engine, and the like, all application areas for which Python, which is MUCH more general-purpose, is so perfectly well suited. Note that this language uses Python as its lower-level embedded language; indeed the whole VVHL (very-very high-level) program gets compiled into Python (by a Python-coded compiler, of course) and executed as Python (by a Python-coded middleware, of course -- resting on top of a very special Python-coded OODB and feeding clients such as GUI ones, Web apps, and batch scripts -- all typically coded, of course, in Python). No "height" is "enough", PER SE, in a sufficiently restricted domain -- and "multiuser business apps centered on cooperation of knowledge workers" turns out to be sufficiently restricted to let us at AB Strakt design a special language for it, one which catches the essentially "declarative" aspects of the field and embeds Python for non-declarative business rules such as the above "ensure salary is >= minimumSalary by raising it if needed". Of course, if and when we find out that this kind of on-create action (business rule) is frequent enough to warrant it, we may want to push the language level of our own declarative language up a bit further (perhaps by some kind of macro mechanism) into ensure minimum(minimumSalary) (just guessing at the hypothetical future syntax here) in much the same way as the existing "restriction" statement expresses constraints that are meant to make a commit attemot fail rather than fixing it somehow. But below our VVHL language we'll always need a totally general purpose one; our language is not meant to compile itself and never will (while Python will, see the pypy project). I am not sure how much higher than Python you can go *while staying fully general-purpose* -- or if it would be wise to. We'll see when and if somebody invents such a language with a FP level of, say, roughly one or two lines per FP (Python is at about 4-5, I would guess). _Simplicity_ is also important, as such relative failures as PL/I and Algol68 show; Python's magic is that it gets to be so powerful AND simple at the same time -- whether that feat is repeatable at much higher semantics levels, I dunno. (NB in this context FP=Function Point -- nothing to do with Functional Programming, as is happens). > Why are purely functional languages practically unknown? What's that gotta do with the issue? Neither ML nor Haskell are substantially different from Python in terms of FP language level. My personal guess is that using functional programming effectively requires a certain mathematical mindset that most people just don't have. Using Python doesn't -- "it fits your brain", as amply demonstrated over and over already. > [Some absulutely convincing remarks and well structured destription of the > current situation on the server market by Alex] > > My original point in answer to Facundu Bastidas' remark was: IF the > hardware costs had not dropped down to the same order as (base!) software > costs, than Linux would not have had any chance! This is still what I > think with my zero knowledege. It's weird to argue a conterfactual hypothetical, but I don't see why (e.g.) IBM couldn't have cottoned on to Linux as a cheaper and more profitable alternative for their system integration business than developing and maintaining their own sub-brand of Unix, whatever may have happened to hardware costs. > My other point was that there nothing like that is going on in the > software development business. The price of tools is of no significance. You are wrong. Maybe on some level it "shouldn't" be, but bean counters are going really wild these days -- and new frugal startup companies (very different mindset than those of just a few years ago) ARE looking hard at EVERY penny they spend as a matter of routine. Each penny has to justify itself directly -- a rule that served such now-huge companies as Walmart or Ikea quite well over the years, after all. Furthermore, using open source tools isn't just a COST advantage: it gives obvious strategic benefits -- it lets you have a backup strategy that you might lack if the sole supplier of your tools went belly-up, or got bought out by some other company for its customer base (but with the strategy of slowly killing the tools that are making you its customer), or simply decided to kill your tools in favour of some costlier/more profitable others (suppliers DO that, you know, if they get a good enough stranglehold on their customers). Some companies have suffered enough such episodes in the past that they DO have a strategic bias towards open source by now. > It is the (expected increase of productivity) The DoD Ada is the best > example I can think of. > > We have not yet reached the situation, where the vendor includea all the > hardware you need when you buy a program. Actually there are such cases (although "buy" is typically incorrect -- such sw/hw combinations are typically *leased*), but I do think they're quite a minor factor in the IT industry today, as yet. >> >> say COBOL, even if you needed to supply training for it (it's not >> >> hard to teach COBOL to somebody who knows assembly, anyway -- the >> >> reverse is harder). >> > I am on your way; maybe they more probably would be trained for some >> > "macro language". This is no 'paradigm change'. Most C++ programmers (I >> > know what I say!) write C programs. > >> History proves you are wrong: in practice, COBOL was what took over >> the market for business application development, *NOT* macro assembly >> as you claim would "more probably" happen. A paradigm change, to be >> sure, but it's what DID win historically. By ignoring history, as >> you're doing, you may not be doomed to repeat it, but you sure do >> handicap grievously your chances to predict the future. > > Please! I do nor ignore history! I hypothetically predicted something what > I know did not happen, but what would have been more plausible. It did not So, you should understand that your criteria of prediction are wrong. > happen because the number of programmers was small at that time. In fact Clearly irrelevant. If programmer productivity was very low, then more programmers were needed to produce any given total program functionality than would be with higher productivity (or, with the same number of programmers much more functionality could be produced). Thus it made more sense to train programmers in a higher-productivity technology than to NOT do so -- and the returns of this strategy were (assuming enough demand for program functionality, which has always been the case) PER PROGRAMMER, just as the expenses, thus the total number of programmers is not relevant in the decision-making process. > not COBOL took over but RPG, to correct your historical background. RPG played quite a role, but much more software was in fact developed in COBOL than in RPG. > In most companies you do not train programmers but (try to) hire > experienced staff. Most companies in Europe do BOTH things. Laying people off is just too costly. >> for many examples. As the evidence accumulates, Python also starts >> getting in non-sneakily, by executive decision rather than by the above >> means -- and keeps proving itself. > > We shall wish that. It's a fact, not a wish. Progress may not be as swift as we might WISH, but it's undeniably happening. >> And Moore's Law is absolutely crucial to this relentless trend. > > I see no reason why not C# and .NET will be the winners!? If dotNET should emerge as the favoured platform, Python will then occupy that niche just as it did for the JVM, and it will offer just the same productivity advantages wrt C# as it does wrt Java or C++ and for identical reasons: higher level, and simplicity. > ... >> > I should as well like to discuss your aspect of programmer's > productivity. >> > This is an important factor. However all investigations show that >> > programmer's productivity is an unmeasurable quantity. >> >> Once again, you are totally wrong, and moreover, you are wrong in an >> assertion that you choose to express in the broadest, unqualified terms. > > I was very well aware of what I was saying ;-) > >> Lutz Prechelt's study, the best-known example of empirical investigation >> of programmer productivity, show Python and Perl ruling the roost, and >> grinding e.g. Java into the dust. > Bu some coincidence I came over that study some months ago (googling for > some Python matter). I was impressed by the thouroughness of the study but > not of the result. The study concentrated on coding and some Of course. Including maintenance (bugs discovered indicating the need for corrective maintenance). > string/pattern matching related task Of course, any empirical study will concentrate on one task. I would not describe that "phone book" example as "string/pattern matching", exclusively, of course. > There will be different results when doing embedded applications Quite possibly, but as I've already explained that's maybe 10% of software development, so, who cares? Embedded applications with hard real time constraints would see an interesting fight between, say, C and (some constrained subset of) C++ -- all the major languages used in programming applications, such as Java, Python and C#, have no guarantees of hard real-time constraints. And so? Who cares? >> This only confirms in a specific case >> study the well-know results of the Function Point community: the higher >> level a language, the least amount of code per FP it needs, the higher >> the productivity in all phases of coding and maintenance. > > Coding is agreed, maintenance is still questionable. Corrective maintenance costs are well predicted by density of bugs (which Prechelt did measure) and addition of functionality is strongly correlated to the cost of the first development (when using decent methodologies, of course -- "waterfall" ones are just untenable, but then nobody proposes THOSE as being a better fit for Python!-). >> > Do it with Python then and show it to the world ;-) > >> It's been done more than once, and it's being done again as we speak, >> many times over -- again, see the Python Success Stories. Google is >> an example that didn't choose to submit all details of its Python >> success -- but Norvig, Google's search-quality director, has stated >> unambiguously what a crucial role Python has played and still plays >> in Google's amazing ongoing success. The Open-Source Applications >> Foundation is doing the same with Chandler, a personal information >> manager application. > > It is not clear whether this is just a niche market like e.g. MATLAB. Sure -- Google is one niche, Industrial Light and Magic another, completely unrelated niche, the OSAF a third one, games yet another, and so on, and so forth. Breaking up the range of application of a general purpose programming language such as Python into a zillion niches is just silly, but feel free to go right ahead -- it's no use, but if it amuses you, sure, why not. MATLAB may be one niche of C's application (I do believe MATLAB is coded in C, but I don't know for sure), but that says essentially nothing regarding C's (obviously far wider) range of applicability. Alex From __peter__ at web.de Thu Sep 18 19:14:12 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Sep 2003 01:14:12 +0200 Subject: Binding frustration References: <mailman.1063921226.27885.python-list@python.org> Message-ID: <bkde9j$icj$04$1@news.t-online.com> Rob Hunter wrote: > So it just occurred to me that probably, in this case, the Python way > is the Scheme way: > > def getGenres(title): > > def inGenre(g): > return <boolean test using g and title and the dictionary> > > return filter(inGenre, ['Comedy','Suspense', ...]) > > :) > > But still, wrt my original complaint, doesn't it seem wrong that I > couldn't write that program? > Doesn't it strike you that the function name inGenre suggests a test rather than a function with side effects? I think your second approach is clearer than the workaround using result.append() that was suggested in previous posts. Why would you nest inGenre() inside getGenres(). Testing if a title is in one specified genre is a useful application, too. Thus the title must be made explicit. Let's see: from sets import Set genres = { "Comedy": Set(["t1", "t2", "t3"]), "Suspense": Set(["t2", "t4", "t5"]) } def inGenre(title, titlesInGenre): return title in titlesInGenre def getGenres(title, genres): return [name for name, titles in genres.iteritems() if inGenre(title, titles)] allTitles = Set() for ts in genres.values(): allTitles |= ts allTitles.add("t0") for title in allTitles: print title, "is in genres:", ", ".join(getGenres(title, genres)) print if inGenre("t1", genres["Comedy"]): print "t1 is a comedy" Hey, all functions have nice arguments in/return value out interfaces and all binding woes have suddenly vanished :-) More seriously, Python's binding concept is simple enough that you will soon overcome that frustration. Peter From godoy at metalab.unc.edu Tue Sep 9 16:37:44 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 09 Sep 2003 17:37:44 -0300 Subject: Request for comments on modular application design and security. References: <m3r82qj83t.fsf@ieee.org> Message-ID: <m365k1itpj.fsf@ieee.org> Jorge Godoy <godoy at metalab.unc.edu> writes: > How can I pass this information from one proccess to another without > compromising security and in a way that's available in both Linux > and Windows? (They have half of the machines running each OS and are > migrating to Linux.) It seems that PyRO will do that. Is it the best approach? -- Godoy. <godoy at metalab.unc.edu> From __peter__ at web.de Mon Sep 22 03:39:24 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Sep 2003 09:39:24 +0200 Subject: convert Unicode to lower/uppercase? References: <HBF.20030919jmx2@bombur.uio.no> <bkepb9$6a4$01$1@news.t-online.com> <299f1138.0309210940.32e9acfe@posting.google.com> <bkkusk$pvi$05$1@news.t-online.com> Message-ID: <bkm919$ast$01$1@news.t-online.com> "Martin v. L?wis" wrote: > jallan wrote: > >> But that really doesn't work properly. According to Unicode specs and >> German usage the uppercase of "?" is actually "SS", that is the single >> character "?" should uppercase to two characters. > > Can you cite exact chapter and verse of the Unicode specs that say so? > According to the Unicode database, > > http://www.unicode.org/Public/UNIDATA/UnicodeData.txt > > has neither an uppercase mapping, nor a lowercase mapping. It seems like UnicodeData.txt does not give the full story. Quoting from http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt: [...] # (For compatibility, the UnicodeData.txt file only contains case mappings for # characters where they are 1-1, and does not have locale-specific mappings.) [...] # <code>; <lower> ; <title> ; <upper> ; (<condition_list> ;)? # <comment> [...] # The German es-zed is special--the normal mapping is to SS. # Note: the titlecase should never occur in practice. It is equal to titlecase(uppercase(<es-zed>)) 00DF; 00DF; 0053 0073; 0053 0053; # LATIN SMALL LETTER SHARP S [...] Thus, to comply with the standard, "?".upper() --> "SS" is required. > Also, in German, the uppercase mapping of ? is of ongoing debate. My personal impression is that, even before the orthography reform in 1998, the SZ variant was seldom used. For the "official" rule see http://www.ids-mannheim.de/reform/a2-3.html. Peter From lac at strakt.com Sat Sep 13 15:39:16 2003 From: lac at strakt.com (Laura Creighton) Date: Sat, 13 Sep 2003 21:39:16 +0200 Subject: Anybody know the Etymology of the word 'Sprint' as in coding Sprint? Message-ID: <200309131939.h8DJdGHP007875@ratthing-b246.strakt.com> I think it comes from Jeff Sutherland's Agile Programming Methodology, called Scrum http://jeffsutherland.com/scrum/index.html where work is planned into month long interations called Sprints. (Jeff must have terrific stamina if he thinks that the thing to call a month-long race is a Sprint :-) ) These days we do them shorter -- as in a 4 days Sprint before Pycon. Anybody know the etymology for sure? Laura From soundwave56 at yahoo.ca Thu Sep 4 17:28:24 2003 From: soundwave56 at yahoo.ca (Hank) Date: 4 Sep 2003 14:28:24 -0700 Subject: quick and smart way for parsing a CSV file? References: <731fc603.0309031242.4e5493ce@posting.google.com> <3F5656CA.519ABADF@easystreet.com> Message-ID: <731fc603.0309041328.4e83f8ab@posting.google.com> where would i get this csv module from? does it come with python 2.2? thanks achrist at easystreet.com wrote in message news:<3F5656CA.519ABADF at easystreet.com>... > Hank wrote: > > > > Hi, > > > > I have a CSV file from excel that looks like this (simplified): > > > > name,description,type1,type2,name,filename > > test1,this is a test,0.000,1.000,, > > test2,another test,1.000,0.000,newname,filename > > test3,this is a test,0.000,1.000,, > > test4,this is a test,0.000,1.000,, > > test5,this is a test,0.000,1.000,, > > test6,this is a test,0.000,1.000,, > > > > what i want at the end is a dictionary like > > > > dict1[name] = test1 > > dict1[description] = "this is a test" > > . > > . > > . > > dict2[name] = test2 > > dict2[description] = "another test" > > > > > import csv > > dicts = [] > > inputFile = open("SomeDurnFileName.csv", "rb") > parser = csv.reader(inputFile) > firstRec = True > for fields in parser: > if firstRec: > fieldNames = fields > firstRec = False > else: > dicts.append({}) > for i,f in enumerate(fields) > dicts[-1][fieldNames[i]] = f From stefnin at alussinan.org Mon Sep 29 10:28:47 2003 From: stefnin at alussinan.org (Stéphane Ninin) Date: 29 Sep 2003 14:28:47 GMT Subject: asyncore question References: <Xns93F48D6F052CAstefninalussinanorg@213.228.0.75> <mailman.1063370360.32090.python-list@python.org> <p2j9b.3994$U41.2930@nwrdny01.gnilink.net> Message-ID: <Xns9405A6A7BD0A1stefninalussinanorg@213.228.0.133> Also sprach Raymond Hettinger : >> >> I believe it's an oversight in asyncore. >> Either create_socket should take >> a map parameter, or __init__ should store the initial map and >> create_socket should use it. One workaround is to create the socket >> yourself and call set_socket(sock, some_map). > > Please submit a bug report. > > I think this patch should work, *** asyncore.py Mon Sep 29 16:20:13 2003 --- asyncore-new.py Mon Sep 29 16:20:26 2003 *************** *** 201,206 **** --- 201,211 ---- addr = None def __init__(self, sock=None, map=None): + if (map is None): + self.map = socket_map + else: + self.map=map + if sock: self.set_socket(sock, map) # I think it should inherit this anyway *************** *** 248,254 **** self.socket = socket.socket(family, type) self.socket.setblocking(0) self._fileno = self.socket.fileno() ! self.add_channel() def set_socket(self, sock, map=None): self.socket = sock --- 253,259 ---- self.socket = socket.socket(family, type) self.socket.setblocking(0) self._fileno = self.socket.fileno() ! self.add_channel(self.map) def set_socket(self, sock, map=None): self.socket = sock *************** *** 353,359 **** raise socket.error, why def close(self): ! self.del_channel() self.socket.close() # cheap inheritance, used to pass all other attribute --- 358,364 ---- raise socket.error, why def close(self): ! self.del_channel(self.map) self.socket.close() # cheap inheritance, used to pass all other attribute should I add it first to the bug [758241], or create a patch for it ? In that case, how to connect the patch to the bug it is supposed to solve ? I guess I am a bit out of topic here, in that case where should I ask such questions ? Regards, -- St?phane Ninin From jepler at unpythonic.net Tue Sep 30 12:06:53 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 30 Sep 2003 11:06:53 -0500 Subject: Is this is bug or something change in Python 2.3 In-Reply-To: <200309300854.42105.spatel@landrum-brown.com> References: <200309300854.42105.spatel@landrum-brown.com> Message-ID: <20030930160647.GA12344@unpythonic.net> The reason is the difference in the way sys.path is set: $ cat x.py import sys; print repr(sys.path[0]) $ python2.2 ./x.py '.' $ python2.3 ./x.py '/net/filesrv1/sd3a/users/jepler' Jeff From wweexxsseessssaa at telus.net Mon Sep 29 10:45:38 2003 From: wweexxsseessssaa at telus.net (John Hall) Date: Mon, 29 Sep 2003 14:45:38 GMT Subject: OT: John Cleese and the Monty Python book Message-ID: <65hgnvkrh84v4bbmijqdivbih54e74metn@4ax.com> I just read this in The Independent (Brit newspaper). What John Cleese is doing now, and chat about the people of Monty Python's Flying Circus. I know that Guido is a fan - perhaps other Pythonistas are also. -- John W Hall <wweexxsseessssaa at telus.net> Cochrane, Alberta, Canada. "Helping People Prosper in the Information Age" From BjornPettersen at fairisaac.com Wed Sep 17 17:54:23 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Wed, 17 Sep 2003 16:54:23 -0500 Subject: Clearing file object buffers Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624CE9@stpmsg00.corp.fairisaac.com> > From: disgracelands [mailto:disgracelands at quietblue.co.uk] > > In my code i have setup sys.stdout and sys.stderr as file > objects so that i > can easily track whats going on during the course of my > program. So far its > proving useful but the objects seem to be buffering any text > supplied to > their write() functions and when i hit an error condition and > have to exit > early they fail to write and i'm left with empty files. > > Is there any way to force the file objects to flush the > buffer to file on > disc? >>> import sys >>> dir(sys.stdout) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__ite r__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'clo se', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next' , 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'w rite', 'writelines', 'xreadlines'] >>> print sys.stdout.flush.__doc__ flush() -> None. Flush the internal I/O buffer. >>> hth, -- bjorn From jepler at unpythonic.net Mon Sep 8 08:55:34 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 8 Sep 2003 07:55:34 -0500 Subject: GIFs Using Tkinter In-Reply-To: <3f5c6b2f$0$20870$91cee783@newsreader02.highway.telekom.at> References: <3f5c6b2f$0$20870$91cee783@newsreader02.highway.telekom.at> Message-ID: <20030908125529.GA23847@unpythonic.net> gregor, I was also able to get a reliable display using bytes = open(imgfile, "rb").read() bytes = base64.encodestring(bytes) img = PhotoImage(data=bytes) If you're using Windows, the missing part may be the "b" (binary) option when opening the file. If not, you'll need to provide more information about what you're doing. Jeff From newsgroups at jhrothjr.com Thu Sep 18 15:26:18 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 18 Sep 2003 15:26:18 -0400 Subject: file object: seek and close? References: <mailman.1063901845.25188.python-list@python.org> <bkcpdn$f1k$00$1@news.t-online.com> <3F69EE44.5020100@bu.edu> <bkctm3$34s$05$1@news.t-online.com> Message-ID: <vmk1mcbdm5n575@news.supernews.com> "Peter Otten" <__peter__ at web.de> wrote in message news:bkctm3$34s$05$1 at news.t-online.com... > Shu-Hsien Sheu wrote: > > > Hi, > > > > I did some tests and it seems that it was the line that I defined list > > as a pdbdict0 object was causing the problem. > > > > If I remove the line: > > > > list = pdbdict0() > > > > This is really strange. I still cannot reproduce the error. > > > > > class pdbdict0(dict): > > def __init__(self): > > super(dict, self).__init__() > > self['header'] = '' > > self['compnd'] = [] > > > > Wouldn't that be: > > class pdbdict0(dict): > def __init__(self): > super(pdbdict0, self).__init__(self) > self['header'] = '' > self['compnd'] = [] > > or better: > > def bdbdict0(): > return {"header": "", "compnd": []} > > While the pdbdict0 implementation seems broken, I have no clue what causes > the file to be closed. > > Totally unrelated: Don't use list and type as variable names. They are > already used as built-in classes. Actually, that's probably the problem right there. Never, ever use anything in the built-in namespace as a variable name. John Roth > > Peter From uce at ftc.gov Tue Sep 23 21:59:15 2003 From: uce at ftc.gov (Gordon Airport) Date: Tue, 23 Sep 2003 21:59:15 -0400 Subject: Thoughts on PEP315 In-Reply-To: <oalumvopu9afuhno85tbp2erl52rk9hht1@4ax.com> References: <oalumvopu9afuhno85tbp2erl52rk9hht1@4ax.com> Message-ID: <Nc2dnbMyZd7uZ-2iU-KYhw@comcast.com> The point of do-while loops is that you don't need setup code anymore, right? How about this: ... dowhile <condition>: <loop body> ... where the body is run once before it becomes a standard while loop. It looks like we all think of this structure as a "do-while loop", so the expression is natural. This also makes it easy to change loop types - just add or remove the "do". Slight downside is that the execution flow isn't exactly as you read it. From alpot at mylinuxsite.com Sun Sep 7 12:23:55 2003 From: alpot at mylinuxsite.com (hostmaster) Date: 08 Sep 2003 00:23:55 +0800 Subject: Question on Standard Types Message-ID: <1062951834.13887.27.camel@mylinuxsite.com> Hi, I'm quite new to Python and I am reading this book called 'Core Python Programming' by Wesley J. Chun. I think that this is not a new book but I believe some of the points are still valid. There is this part in the book where it says: "In Python, standard types are not classes, so creating integers and strings does not involve instantiation". But later in the book, it talks about 'numeric objects' created when a numeric literal is assigned to a reference. So my question now is, if standard types are objects, shouldn't they have classes as well ? Isn't it that a class is the blueprint of an object? If they don't have a class to begin with, how are these objects created? Thanks. Al From NO-MAIL at hotmail.com Tue Sep 16 15:41:25 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 19:41:25 GMT Subject: None, False, True References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> <bk7lq1$qicfh$1@ID-70710.news.uni-berlin.de> <bk7mkg$4s$1@news.peterlink.ru> Message-ID: <FHJ9b.13226$x21.7557@twister.southeast.rr.com> "anton muhin" <antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru> wrote in message news:bk7mkg$4s$1 at news.peterlink.ru... > Defenitely. If I remember it right, None is going to be promoted into > keywords soon. Therefore the warning. > > hth, > anton. > Will it be lower-case (together with false and true) like all other keywords or is it just a start of mess? M-a-S From tina_li23AThotmailDOTcom Tue Sep 23 15:32:20 2003 From: tina_li23AThotmailDOTcom (Tina Li) Date: Tue, 23 Sep 2003 15:32:20 -0400 Subject: Bottleneck? More efficient regular expression? References: <3f7069db_4@corp.newsgroups.com> <eppstein-22C96A.10011623092003@news.service.uci.edu> Message-ID: <3f70a03d$1_4@corp.newsgroups.com> Hello, Thanks for the suggestion. It does solve my problem -- but just out of curiosity, I'd like to know what caused the over-limit as well. Thanks again! Tina "David Eppstein" <eppstein at ics.uci.edu> wrote in message news:eppstein-22C96A.10011623092003 at news.service.uci.edu... | In article <3f7069db_4 at corp.newsgroups.com>, | "Tina Li" <tina_li23 AT hotmail DOT com> wrote: | | > I've been struggling with a regular expression for parsing XML files, | > which keeps giving the run time error "maximum recursion limit | > exceeded". | | Why not use a real XML parser? xml.parsers.expat is easy enough to use, | doesn't have problems with recursion limits, and will continue working | when someone generates a valid XML file in a slightly different version | than the one you expect. | | -- | David Eppstein http://www.ics.uci.edu/~eppstein/ | Univ. of California, Irvine, School of Information & Computer Science -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From jroznfgre at jngpugbjreXEBCXNbet.cy Sat Sep 20 08:47:10 2003 From: jroznfgre at jngpugbjreXEBCXNbet.cy (JZ) Date: Sat, 20 Sep 2003 14:47:10 +0200 Subject: Webware and RAM! References: <d30mmv0fh2ohgbnl15t6muf7n2rdlvtgcl@4ax.com> <m3ad90u1kf.fsf@drizzle.com> Message-ID: <d0jomvse3jd8ikqvt4tnjc7a3bje0dndlv@4ax.com> On Fri, 19 Sep 2003 10:32:00 -0700, "Elf M. Sternberg" <elf at drizzle.com> wrote: >Huh. Weird. I run WebKit in threaded mode, so there's only 1 >daemon running ever, and it starts at about 7 MB. That's right. I was wrong. I was fooled with 'top' command of my RH7. -- JZ From skip at pobox.com Tue Sep 16 15:22:13 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 16 Sep 2003 14:22:13 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <tmH9b.79$2k.36@reader1.news.jippii.net> References: <mailman.1063659502.2922.python-list@python.org> <tmH9b.79$2k.36@reader1.news.jippii.net> Message-ID: <16231.25317.741455.556170@montanaro.dyndns.org> Harri> Py_None is special because it is shared between all interpreters, it is Harri> global. Py_None is defined as: ... Harri> From the above we see that when Py_None reference count reaches Harri> zero, a destructor none_dealloc is called. ... Harri> This makes no sense at all. Why Py_FatalError? It would be better Harri> to have Harri> static void Harri> none_dealloc(PyObject* ignore) Harri> { Harri> } Actually, it makes perfect sense. The reference count of Py_None is never supposed to reach zero. If that happens it's because you have a bug (too many Py_DECREFs or not enouch Py_INCREFs). Your version of none_dealloc silently masks the error. Harri> so that it is not necessary to call Py_INCREF(Py_None) Harri> Py_DECREF(Py_None) at all. Guess how many times these are called Harri> in Python C API? Py_INCREF is called 2001 times and Py_DECREF two Harri> times. You mean how many places does Py_(IN|DE)CREF(Py_None) appear? Note that in most situations the interpreter itself calls Py_DECREF(<return value>) for you. You just can't tell that "<return value>" is Py_None using a static scan of the C source code. Harri> By changing the way how Py_None is freed (by doing nothing) Harri> Python would get simpler and faster. I think you are completely missing the point of Python's reference counting. Py_None is nothing special except for the fact that it is not allocated on the stack. In fact, if you removed all the INCREFs and DECREFs I think you'd have to special-case the code which detects negative reference counts. Py_None's reference count would quickly go negative and instead of the normal reference counting dance you'd always be calling the error function which handles negative ref counts. It would always have to compare its argument object with Py_None to make sure it wasn't complaining about the now-special Py_None object. Skip From Alexandre.Fayolle at logilab.fr Fri Sep 5 11:22:42 2003 From: Alexandre.Fayolle at logilab.fr (Alexandre Fayolle) Date: Fri, 5 Sep 2003 17:22:42 +0200 Subject: [ANN] pygantt-0.9.2 Message-ID: <20030905152242.GB683@calvin> Hello, Logilab has released pygantt-0.9.2. Pygantt is a tool which takes an XML description for a project tasks and resources and generates Gantt diagrams. It is released under the Gnu GPL. This new release features some heavy refactoring, as well as some nice new features (such as skill handling for resources) and bugfix (especially in the scheduling part of the code). Project homepage: http://www.logilab.org/projects/pygantt Direct download: ftp://ftp.logilab.org/pub/pygantt/pygantt-0.9.2.tar.gz -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From alessandro at sephiroth.it Mon Sep 22 09:54:30 2003 From: alessandro at sephiroth.it (Alessandro Crugnola *sephiroth*) Date: Mon, 22 Sep 2003 13:54:30 GMT Subject: py2exe: dynamic module does not define init function References: <81zbb.99124$hE5.3508075@news1.tin.it> <FoCbb.100492$hE5.3545186@news1.tin.it> Message-ID: <qaDbb.101005$hE5.3554558@news1.tin.it> > The message is telling you that audiere.dll does NOT define the > mandatory function named 'initaudiere' which it should absolutely > define to allow the "import audiere" statement. If the import > works fine outside of a py2exe'd environment but fails in the > latter then I suspect you may be getting the "wrong" DLL in the > second case (e.g. maybe you didn't copy audiere.dll to the > directory in which py2exe's tweaked import expects to find it). Thanks Alex for the reply, but if the audiere.dll has been copied in the dist/app/ directory (the one with the .exe) doesn't it mean that py2exe find it? Maybe i have to copy manually the dll ? -- Alessandro Crugnola [sephiroth] Flash | PHP Developer http://www.sephiroth.it Team Macromedia Volunteer for Flash http://www.macromedia.com/go/team Flash-php mailing list http://www.flash-php.it/index.php?ml=fpcoders&action=subscribe From Paul.Moore at atosorigin.com Tue Sep 16 11:46:59 2003 From: Paul.Moore at atosorigin.com (Moore, Paul) Date: Tue, 16 Sep 2003 16:46:59 +0100 Subject: Datetime utility functions Message-ID: <16E1010E4581B049ABC51D4975CEDB8803060C81@UKDCX001.uk.int.atosorigin.com> From: Gustavo Niemeyer [mailto:niemeyer at conectiva.com] > Your message arrived in the exact time.. :-) I agree! > Have a look at this: I like that. I'm not entirely happy with the name of the class, but as I can't come up with a better suggestion, I shouldn't criticise... >> My specific requirements were: >> >> 1. Get the last day of the month contatining a given date(time). I >> really was surprised to find this one missing, as it seems to me that >> the datetime module must know what the last day for each month is, so >> exposing it wouldn't have been hard. > I don't understand this one. The last day of the month containing > a given datetime? A datetime is absolute, how would it be "contained" > in something else? Sorry, I didn't explain that very well. Imagine an application to report stats over a period. The user can specify a date, and the report will be for a calendar month, containing the user's required date. So my code will be something like start = user_date.replace(day=1) # Start of the month end = "Last day of the month" There isn't really a good way of getting "end". I can either add 1 month (which involves splitting out the month and year, and handling the end of year) and then subtracting 1 day, or I can try setting the day to 31, 30, 29, 28 in turn, and stop as soon as I don't get an exception. Neither method is hard, it just seems like one of those tasks that should be simple. With your "relativedelta" I could do this pretty easily, by end = start + relativedelta(months=+1, days=-1) but I still feel that I'd need to have an explanatory comment. The datetime module *knows* the number of days in the month - I'd just like it to tell *me*. Paul. From lizard0000092 at yahoo.com Wed Sep 17 16:22:06 2003 From: lizard0000092 at yahoo.com (Rebecca Hauge) Date: Wed, 17 Sep 2003 13:22:06 -0700 (PDT) Subject: Python 2.1 Compilation error - can't find krb5.h In-Reply-To: <1063814087.10299.48.camel@localhost.localdomain> Message-ID: <20030917202206.36332.qmail@web20708.mail.yahoo.com> Thank you! Your suggestion worked great! --- Jeremy Hylton <jeremy at alum.mit.edu> wrote: > On Wed, 2003-09-17 at 11:07, Gabby wrote: > > I am attempting to compile python 2.1 from the > source on a RedHat 9.0 > > system. The problem is that a openssl header file > (kssl.h) requires > > krb5.h which isn't in the usual place > (/usr/include). Instead krb5.h > > gets installed at usr/kerberos/include. The > openssl version is > > 0.9.7a-2. When I build python, the ./configure > works fine but the > > make' has problems building the _socket extension. > The beginning of > > the error message is pasted below. How do I let > python know where to > > find the krb5.h file? > > This problem is fixed in CVS, but there hasn't been > much interest in a > 2.1.4 release since it's now two minor revisions out > of date. > > The solution is to add the following bit of code to > setup.py just after > ssl_incs is defined. > > krb5_h = find_file('krb5.h', inc_dirs, > > ['/usr/kerberos/include']) > if krb5_h: > ssl_incs += krb5_h > > Jeremy > > __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From max at alcyone.com Tue Sep 9 04:08:25 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Sep 2003 01:08:25 -0700 Subject: Get the date of last modification of a file References: <rE27b.45940$R32.1458201@news2.tin.it> <3F5CBAB8.F8888E3@engcorp.com> <UNf7b.48792$R32.1584881@news2.tin.it> Message-ID: <3F5D8A79.F38BA0A4@alcyone.com> Manuel Bastioni wrote: > os isn't built-in :-( In that case, I think the relevant question is why you think you need a builtin function rather than a standard library function. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ To be refutable is not the least charm of a theory. \__/ Friedrich Nietzsche From max at alcyone.com Sun Sep 7 23:48:41 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 07 Sep 2003 20:48:41 -0700 Subject: Is there a unicode EOF mark like DOS ascii ctl-z or unix crl-d ? References: <bjgf10$d5s$0@216.39.172.122> <3F5BD4DD.57D90AF5@alcyone.com> <bjgs8l$6d0$0@216.39.172.122> Message-ID: <3F5BFC19.D098115B@alcyone.com> Bengt Richter wrote: > Thanks. I tried EOT on the assumption, but windows console type > command doesn't stop on it, > much less notepad, so I guess I have to do something else. If you're using Windows, you'll have to go with whatever nonstandard options they give you. I don't think contemporary Windows editors respond to a keystroke to mean end of file. If you're using command line stuff in DOS, it's C-z (ASCII SUB, which means something entirely different from end of file). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ To be a man means to be a fellow man. \__/ Leo Baeck From florian.proff.schulze at gmx.net Thu Sep 4 08:00:29 2003 From: florian.proff.schulze at gmx.net (Florian Schulze) Date: Thu, 04 Sep 2003 14:00:29 +0200 Subject: Thank you!!! References: <bj5ki4$fmgdl$1@ID-174077.news.uni-berlin.de> Message-ID: <opruy4y30yttxc4i@news.t-online.de> This could be a bad subject nowadays, but since this mail was so small I took a peek into it. Nice to hear that you like Python ;) Regards, Florian On Wed, 3 Sep 2003 22:56:05 +0200, MK <MK at foo.com> wrote: > Thank you, Pythonistas. > > You gave me a medium to express myself. > > What is Fender to Jimi, or color to Monet, > Python is for me. > > My thoughts are flowing naturally with you, > Python. What is "Voodoo Chile" to Jimi, that's > short, elegant and working ZEN-code in > Python for me. > > Truly a freeing, non-linear and transcendent(*) > experience, > yours > MK > > > > (*) > Those excit?ng, legendary days when I implemented > a paint program in 6502 assembler, and a CAD/CAM program > in Turbo Pascal. > > And then 10 years of IT toiling... Am I loosing my faith? > > But programming is fun, again!!! > PYTHON!! PYTHON!! PYTHON!! PYTHON!! > PYTHON!! PYTHON!! PYTHON!! PYTHON!! > > -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From felix_mcallister at hotmail.com Wed Sep 24 08:27:06 2003 From: felix_mcallister at hotmail.com (Felix McAllister) Date: Wed, 24 Sep 2003 13:27:06 +0100 Subject: command exit status on windows References: <Gmfcb.13418$g4.272374@news1.nokia.com> Message-ID: <A4gcb.33123$pK2.58766@news.indigo.ie> On Windows NT, 2000, 2003 and XP this generally works as well, although you'll find that some command line applications specifically written for Windows don't bother with a return code. I can't comment about Windows 95, 98 or ME. The os.system call (which works on both Unix and Windows) returns the correct status code. Felix > Hello, > > Is there a way to check if a command executed in ms-dos returns 0 (success) > or greater than 0 (fail) ? > > In Unix the module commands.getstatusoutput returns exit status.. > > > Thanks in advance. > > -SV From jetman516 at hotmail.com Mon Sep 29 13:36:36 2003 From: jetman516 at hotmail.com (The Jetman) Date: 29 Sep 2003 10:36:36 -0700 Subject: [2.2.1]How To Gracefully Shutdown an XML-RPC Server References: <a38d43b0.0309261712.540f96da@posting.google.com> <yx6db.4829$RW4.3093@newsread4.news.pas.earthlink.net> Message-ID: <a38d43b0.0309290936.26ab0f46@posting.google.com> "Andrew Dalke" <adalke at mindspring.com> wrote in message news:<yx6db.4829$RW4.3093 at newsread4.news.pas.earthlink.net>... > The Jetman: > > I'm reading source code, but I haven't found any examples of > > how to simply shutdown my XML-RPC server. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114579 > > Or you can ungracefully use os._exit, like pulling the emergency > brake on a train. > > Andrew > dalke at dalkescientific.com Andrew: Thanx ! I *swear* I always spend at least a couple hours or so looking for stuf like this on my own ! That's the single most frustrating part about the Web (besides this idiotic W32.Swen virus/worm) ! No matter how you compose a query, there's always something that you miss.... BTW, I haven't tried it, but I bet os._exit will fail just like sys.exit(). Besides the reason for a graceful shutdown is more than cosmetic, since a forced shutdown (like a Ctrl-C) may occasionally leave the sockets allocated (which *has* happened.) Later....Jet From max at alcyone.com Thu Sep 18 16:36:18 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 18 Sep 2003 13:36:18 -0700 Subject: needs help in how to translate ≴ and ≵ References: <mailman.1063887985.10861.python-list@python.org> Message-ID: <3F6A1742.73915D17@alcyone.com> "Raaijmakers, Vincent (IndSys, GE Interlogix)" wrote: > On my terminal, I can display that character this way: > >>> print unichr(8820).encode("utf-8") > ??? > (I think that's a less-than symbol, "<" above an equivalent symbol (~) > with a vertical bar through it, but I really can't tell in this > font...) Yep, that's what it is, see the entry 2274 (hex) here: http://www.unicode.org/charts/PDF/U2200.pdf -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ War is like love, it always finds a way. \__/ Bertolt Brecht From peter at engcorp.com Fri Sep 26 08:55:54 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 26 Sep 2003 08:55:54 -0400 Subject: Where to import modules? References: <bl1bes$13qe$1@f1node01.rhrz.uni-bonn.de> Message-ID: <3F74375A.F9D4B0EB@engcorp.com> Andreas Neudecker wrote: > > I have a "style" question: Sometimes, modules will only be used in a > particular, optional, part of a program (function, class), that will not > always be used when the application is run. So I think it is better to > import them only there, not on the top of the file (together with the > other imports). Is that okay, or are there good reasons for not doing so? There are not *strong* reasons for avoiding the delayed-import style, although clearly maintainability can be affected. It makes it somewhat harder for a maintainer to see that a given module is used at all. I would not bother putting imports that are rarely used in only the functions which need them *unless* I had a really large module which took a long time to import and I was actually having problems with startup time for the application. Basically doing this is an optimization, and you shouldn't be optimizing before the program is working, and you shouldn't be optimizing without a real need for it. (That is, just because it's a little faster doesn't mean it's worth doing.) -Peter From hokiegal99 at hotmail.com Wed Sep 17 19:52:40 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Wed, 17 Sep 2003 19:52:40 -0400 Subject: convert ints in a range to strings References: <bkap6g$4o1$1@solaris.cc.vt.edu> <7xwuc7ouvw.fsf@ruckus.brouhaha.com> Message-ID: <3F68F3C8.6040206@hotmail.com> Thank you (Paul & Duncan) for showing me how to do this! Paul Rubin wrote: > hokieghal99 <hokiegal99 at hotmail.com> writes: > >>------------------------------ >>a="192." >>b="168." >>c="1." >>r = range(256) >>for r in r: >> print a + b + c + r > > > for r in range(256): > print "192.168.1.%d" % r From hildegarde_roth at yahoo.de Thu Sep 18 14:21:43 2003 From: hildegarde_roth at yahoo.de (Hilde Roth) Date: 18 Sep 2003 11:21:43 -0700 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <bk80n3$rsb$03$1@news.t-online.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <bk9sfo$55q$06$1@news.t-online.com> <95b4b9ac.0309171233.21f4c07@posting.google.com> <87llsma4fb.fsf@psi.lupan.zamek.gda.pl> Message-ID: <95b4b9ac.0309181021.14b45d65@posting.google.com> > It will be harder to parse. No because in many cases the reason why you want to use the syntax l[seq] is that you already have seq, so you would refer to it by name and "l[s]" is definitely not hard to parse. > l[:3] would be l[(0, 3)] > l[3:] would be l[(3,-1)] Not at all. I was suggesting to use a semi-colon not a colon. Thus if l is (10,20,30,40), l[:3] -> (10,20,30) whereas l[(0,3)] -> (10, 30), i.e., same as in your class-based example, minus the parentheses, which I now realize are superfluous (odd that python allows you to omit the parentheses but not the commas). > 2. Slicing two dimensional object will not be possible as the notion > you proposed is used just for that (ex. l[1,2] which is equivalent > to l[(1,2)] see below), and Numeric and numarray use it. Same misunderstanding as above, I believe. Let, e.g., l be ((1,10,100),(2,20,200),(3,30,300),(4,40,400)). Then l[2:; 1:] -> [(30, 300), (40, 400)]. This is equivalent to [i[1:] for i in l[2:]] but, at least to me, it is the index notation that is easier to parse. Incidentally, it strikes me that there are a lot of superfluous commas. Why not just (1 10 100) or even 1 10 100 instead of (1,10,100)? The commas do make the expression harder to parse visually. > >>> # multi dimensional indexing > >>> c[1,3] I disagree that this is "multidimensional". You are passing a list and getting back a list, so this is still flat. I think you are confusing dimensionality and cardinality. > Numeric and numarray use it This is good if it is true (I have yet to look at these two because my work is not primarily numerical) but, again, the restriction of this syntax to arrays, and arrays of numeric values at that, strikes me as completely arbitrary. The bottom line is that python claims to be simple but has a syntax which, in this little corner at least, is neither simple nor regular: xranges and slices are both sequence abstractions but are used in different contexts and have different syntaxes; C-style arrays are treated differently than lists of lists of ..., although they are conceptually equivalent; numeric structures are treated differently than non-numeric ones etc etc Oh well. Maybe a future PEP will streamline all that. Hilde From mpeuser at web.de Thu Sep 4 15:41:47 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 4 Sep 2003 21:41:47 +0200 Subject: Drag and drop in Tkinter. How difficult is it? References: <ApGdnUgAC6p1AMuiU-KYuA@comcast.com> Message-ID: <bj84ir$g15$06$1@news.t-online.com> "Marc" <losnations at comcast.net> schrieb im Newsbeitrag news:ApGdnUgAC6p1AMuiU-KYuA at comcast.com... > Hi all, > > I was thinking about developing a drag and drop application and was curious > how difficult it is to do. Basically I want to have a set of objects that I > move around the screen and drop into place. > > Anyone else ever done it? Got any tips? There is a nice example here using an as well nice Tree widget: http://www.esrf.fr/computing/bliss/guides/python/modules/Tree/Tree.html Kindly Michael From tim.parkin at pollenationinternet.com Sun Sep 7 15:13:19 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 20:13:19 +0100 Subject: Comments on Python Redesign In-Reply-To: <y/2W/kKkXcZZ092yn@gnosis.cx> Message-ID: <002801c37574$1f66e900$0a00a8c0@JASPER> David/Lulu said: >Yeah... this moves it from truly awful to merely bad. So that's a good >step. Even so, the lines of text are squashed together vertically in an >awkward way that makes reading difficult. I don't even really know how >that effect was achieved (or in what browser)... is there a CSS >attribute for "really small vertical spacing"? 1) it's an image 2) as an image created in fireworks, I expected line spacing to honor html spacing. It doesn't however so I've fixed it. >In my experience, good pages remain good even in the complete absence >of >their CSS stylesheet. Well, and CERTAINLY good pages do not embed >ad-hoc <font> tags all over them, but I don't think the redesign demo >did that. While I'm only guessing, this is a page that would fare >poorly with the CSS dropped, and with user-specified fonts and colors >specfied. 1) it's an image 2) images don't have font tags 3) haven't got a clue what you mean about it fairing badly with css dropped and fonts and colours changed. If by this you mean rendered in text mode then the design would be a lot better than the existing site as IT'S AN IMAGE you don't really have any way of knowing. >The problem is that it is WAY over-designed. It looks like something >you'd design for a magazine, not for the web, with many browsers >possible. Parkins, or whoever, has a certain browser and screen size, >and probably took out a ruler to align everything properly on that >unique combination. 1) My name is parkin. 2) The site is designed to reflect the expectations of commercial customers who are used to the likes of peoplesoft and atg, etc. also it's designed to project an image to set Python alongside existing enterprise programming langagues (apologies for using the e word) 3) it's an image. Images don't stretch. If I make it any bigger it would not fit in 800 wide browsers. A lot of designers make a choice between fixed width and fluid. I would probably choose fluid for all but the home page however I'm looking at fluid techniques for that too. Tim From ask at me.com Wed Sep 24 02:01:18 2003 From: ask at me.com (Greg Krohn) Date: Wed, 24 Sep 2003 06:01:18 GMT Subject: Barcode generator for Python? References: <mailman.1064348557.16937.python-list@python.org> Message-ID: <Oqacb.1215$NX3.109@newsread3.news.pas.earthlink.net> "jennyw" <jennyw at dangerousideas.com> wrote in message news:mailman.1064348557.16937.python-list at python.org... > Does anyone know of a barcode generator for Python? I'm looking to do > this on Windows. It would be nice to find something free, but that's not > necessary (so long as it's reasonable). It doesn't have to be > Python-specific, either, so long as I can call it from Python. I'd love > to hear any suggestions. > > I've seen bookland.py, but the kind of barcodes I'm looking to generate > are not ISBN barcodes. > > Thanks! > > Jen > I have a script that creates UPC barcodes, but that's not what you're looking for, is it? If it is, let me know and I'll try and find the script. greg From aleax at aleax.it Mon Sep 8 14:59:58 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Sep 2003 18:59:58 GMT Subject: Comments on Python Redesign References: <mailman.1062969251.5905.python-list@python.org> <qU9W/kKkXURB092yn@gnosis.cx> <mailman.1062983352.15417.python-list@python.org> <qnY6b.42704$R32.1360114@news2.tin.it> <bjiec6$itc87$1@ID-139865.news.uni-berlin.de> Message-ID: <Ok47b.31806$hE5.1140021@news1.tin.it> Dave Kuhlman wrote: ... >> So, you're asserting that the target audience of the site IS and >> SHOULD BE >> "developers". Surprise, surprise: this assertion IS "a marketing >> issue". Marketing BEGINS with the identification of target >> audiences and the products and services that will best meet the >> target audiences' need. > > We're not, I believe, arguing about the target audience for > Python. We're arguing about the target audience for > http://www.python.org. Yes, and? A site has a target audience just as assuredly as any other product or service has. If you don't consciously identify that audience, it just "happens", but such "deciding to not decide" is "marketing by accident" -- ineffective but still there. > Further more, saying that the choice of a target audience or that > the choice of the service and product to be provided is a > marketing issue begs the question. It just assumes that marketing > should take over decisions about the direction of a company or a > site. Of course not, because there are constraints that it's not marketing's job to identify, e.g. finances and technical issues. It's from a hopefully synergical interaction of marketing and other functions that the direction emerges. >> Many techies think of "marketing" as a dirty word because it's so >> often >> misused as an inappropriate synonym for "selling". Using words >> properly, marketing is a perfectly legitimate and important >> activity: identify who you're addressing, address their needs >> through appropriate products and services, communicate to them >> that your products and services do address their needs, listen to >> their feedback and adjust your products and services to meet their >> needs even better, look for other audiences that might get their >> needs met by your products and services possibily with some >> modifications. > > These are all good suggestions for a Python promotion site or for a > site for a company that sells Python services. These are suggestions totally independent from Python or any other specifics. Any entity that aims to further the success and spread of [e.g.] Python, as the Python Software Foundation's charter says, _had better_ keep these functions in mind. > I am on the side of those who say that the marketing and > promotion should not be done at the Python home page, > http://www.python.org. It does not seem to be the main focus at And I am on the side of those who say that "wasting" the obvious recognition value of www.BASENAMEHERE.org -- the site that will be automatically visited by semismart browsers if the user just types BASENAMEHERE on the URL field then Enter -- would be totally absurd. Techies know enough to follow links presented from said page. Non-techies need to be more pampered. > http://www.perl.org/ nor at http://java.sun.com/. What promotion Look at www.java.com, *NOT* at java.sun.com. The former is what "the suits" visit by default. Alex From klappnase at web.de Thu Sep 4 16:53:45 2003 From: klappnase at web.de (klappnase) Date: 4 Sep 2003 13:53:45 -0700 Subject: Optionmenu. References: <bj7j47$g5rpn$1@ID-108351.news.uni-berlin.de> Message-ID: <a7a67196.0309041253.7b35e02d@posting.google.com> Thor <thor__00 at yahoo.com> wrote in message news:<bj7j47$g5rpn$1 at ID-108351.news.uni-berlin.de>... > I have the following function (with some things removed): > > def add_stock(): > stockw=Tk() > stockw.title("New stock solution") > sofl=Frame(stockw) > sofl.pack() > u=StringVar() > u.set("M") > cw=OptionMenu(sofl,u,"M","m","u","v","w") > cw.grid(row=1,column=2) > > but the widget keeps not showing teh selected option. If I fo the same out > of the function it works without problem (with stockw.mainloop()). What am > I missing? Anybody can point me out to the solution/the right webpage? Hi, I'm not sure if that is your problem here, but I think you should not use pack() and grid() inside the same window, otherwise strange things might happen. Maybe with sofl.grid() it will work. Michael From ianb at colorstudy.com Tue Sep 30 22:45:39 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Tue, 30 Sep 2003 21:45:39 -0500 Subject: distutils (packaging) newbie questions please.... In-Reply-To: <9Moeb.10508$NX3.4770@newsread3.news.pas.earthlink.net> Message-ID: <57AC2596-F3B9-11D7-B902-000393C2D67E@colorstudy.com> On Tuesday, September 30, 2003, at 06:57 PM, Greg Krohn wrote: >> 1. What exactly goes into the __init__.py files? I know what to put in >> setup.py >> and I know __init__.py is used for packages but I don't know what >> to put IN this file. > > You don't NEED to put anything in it, it works fine as an empty file. > You > CAN put code in there to initialize your package, but personally I've > never > had to. As a minor detail, it is better to put something in there (like just a single #). Some tools (WinZip in particular, I believe) ignore zero-length files in archives, which will cause problems in this case. Ian From ak at nospam.com Tue Sep 30 23:19:57 2003 From: ak at nospam.com (AK) Date: Wed, 01 Oct 2003 03:19:57 GMT Subject: I, monster: nethack-like game References: <q02eb.44767$ai7.16580@newsread1.news.atl.earthlink.net> <3F79D2F3.4F4FB1DD@alcyone.com> Message-ID: <xJreb.2$f11.1@newsread1.news.atl.earthlink.net> In article <3F79D2F3.4F4FB1DD at alcyone.com>, Erik Max Francis wrote: > AK wrote: > >> Hi, I coded a little game in curses, loosely based on nethack but >> where >> you command the monsters against the hero (and his dog). > > You might want to mention this in the rec.games.roguelike.development > newsgroup. > Thanks, will do.. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 24 02:20:58 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 24 Sep 2003 07:20:58 +0100 Subject: Pre-PEP: reverse iteration methods References: <HA5cb.185$kD3.168@nwrdny03.gnilink.net> <nD7cb.2405$PT3.395618@news20.bellglobal.com> <Fi9cb.1443$RW4.368@newsread4.news.pas.earthlink.net> Message-ID: <ttd2nvc2klbala95i1k0sodbcns7i3m2lt@4ax.com> On Wed, 24 Sep 2003 04:44:21 GMT, "Andrew Dalke" <adalke at mindspring.com> wrote: >-1 from me. 'backwards' looks to me like something which changes >the list ordering in place, like what 'reverse' does. Or something >which returns a new list but in reverse order. It's an adjective, >when it should be a verb. I disagree with this. IMO something that modifies a value in place should be named using a verb (such as reverse, or sort, or update...). Something that returns a value without modifying its parameters/object should be named to describe what it returns - normally a noun or adjective (such as globals, len, isinstance). So if we had a sorting function that returns a sorted version of the parameter without modifying its parameter, I'd want it to be called 'sorted' as opposed to the current in-place 'sort'. Of course there are non-modifying functions that are named as verbs (map, filter and reduce being particularly obvious), but that does seems slightly wrong to me - though for the ones I've listed there is basically an overriding convention (they are well known names). -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From uwe.schmitt at procoders.net Tue Sep 9 05:33:41 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 9 Sep 2003 09:33:41 GMT Subject: Ternery operator References: <doJ6b.1999$Ft.737@newssvr22.news.prodigy.com> <bjhrj4$2loh4$1@hades.rz.uni-saarland.de> <3F5C7CBD.A6C97371@engcorp.com> Message-ID: <bjk6pl$2nir7$1@hades.rz.uni-saarland.de> Peter Hansen <peter at engcorp.com> wrote: > Uwe Schmitt wrote: >> >> Andrew Chalk <achalk at xxxmagnacartasoftware.com> wrote: >> > Is there a python equivalent of the C ternery operator? >> >> > I.e.: >> >> > fred = (x == 1) ? 12 : 15 >> > I would think a *Python* equivalent to ?: should not use > direct equality comparison with 1. Better to drop the "==1" > parts in any of the above, to allow the usual Python interpretation > of what is True and what is False to occur. > ...so fred = [12, 15][not x] is sufficient. You made a mistake, compare : [12,15][not x] (x==1) ? 12 : 15 x=0 15 15 x=1 12 12 x=2 12 15 Normaly you should simulate "C ? T : F" either by [T,F][not C] or (C and [T] or [F])[0] in the first case T and F are evaluated allways, the latter solution does short circuit evaluation, which is according to the C/C++ semantics of the ternary operator. Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt http://www.procoders.net schmitt at procoders.net "A service to open source is a service to mankind." From roy at panix.com Sun Sep 7 09:02:07 2003 From: roy at panix.com (Roy Smith) Date: Sun, 07 Sep 2003 09:02:07 -0400 Subject: Why python??? References: <3335321.1062775466@dbforums.com> <mbx6b.1996$Yt.953@newsread4.news.pas.earthlink.net> <eppstein-626068.20342506092003@news.service.uci.edu> Message-ID: <roy-F9F065.09020607092003@reader2.panix.com> David Eppstein <eppstein at ics.uci.edu> wrote: > I don't remember any discussion of student fears about relevance the > last few times the issue of which language to use came up at faculty > meetings. Employability of our graduates, yes, but student bitching, no. I think a university program needs to address both employability and theory. It's inconcievable to me that somebody could get a degree in computer science these days without knowing C++ and Java. It's equally inconcievable to me that they wouldn't also know several other languages. From __peter__ at web.de Fri Sep 26 06:24:41 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Sep 2003 12:24:41 +0200 Subject: Getting the Directory/Path details References: <ab5a234a.0309250906.44b42beb@posting.google.com> <bkv866$u2n$07$1@news.t-online.com> <ab5a234a.0309260111.12dea1ad@posting.google.com> Message-ID: <bl147n$jjk$01$1@news.t-online.com> Kali K E wrote: > Thank you very much for the answer. It works fine when used first > time. But when the directory already exists I am getting the following > traceback message. > Traceback (most recent call last): > File "temp6.py", line 15, in ? > os.makedirs(os.path.join(folder, sf)) > File "/usr/lib/python2.2/os.py", line 203, in makedirs > mkdir(name, mode) > OSError: [Errno 17] File exists: > '/hda1/home/kalike/chnages/python/result' > > How do I take care in such a case? I modified the code to accept already existing directories. The strategy is: Try to create the directory If creation fails, see if the directory already exists. If yes move to the next directory, otherwise throw an exception. class DirectoryException(Exception): pass for sf in subfolders: dirpath = os.path.join(folder, sf) try: os.makedirs(dirpath) except OSError, e: if e.errno == 17: if not os.path.isdir(dirpath): raise DirectoryException, "'%s' can neither be created nor is it an existing directory" % dirpath else: raise # cannot handle it here > Also can you please let me know where I can search for all these OS or > system calls. Is it available as a document some where? It seems you are not familiar with the concept of Exceptions. So, if you were already exposed to another programming language, I'd suggest reading the tutorial that comes with your distribution first, otherwise look out for a textbook. The relevant links on the python site are (in recommended reading order): http://www.python.org/doc/current/tut/tut.html http://www.python.org/doc/current/lib/module-os.path.html http://www.python.org/doc/current/lib/module-os.html Peter From achalk at XXXmagnacartasoftware.com Thu Sep 4 13:59:00 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Thu, 04 Sep 2003 17:59:00 GMT Subject: Tracking Sessions in a Python CGI app. Message-ID: <E3L5b.1175$U45.838@newssvr22.news.prodigy.com> Is there a unique session ID created in a Python CGI app.? If not, and I suspect not, what is the best way to keep track of the session that loads each web page? I need to store form data from multiple forms completed by the user. What is the best way to keep track of which user is which? Thanks! From sheu at bu.edu Thu Sep 18 13:41:24 2003 From: sheu at bu.edu (Shu-Hsien Sheu) Date: Thu, 18 Sep 2003 13:41:24 -0400 Subject: file object: seek and close? In-Reply-To: <bkcpdn$f1k$00$1@news.t-online.com> References: <mailman.1063901845.25188.python-list@python.org> <bkcpdn$f1k$00$1@news.t-online.com> Message-ID: <3F69EE44.5020100@bu.edu> Hi, I did some tests and it seems that it was the line that I defined list as a pdbdict0 object was causing the problem. If I remove the line: list = pdbdict0() there would be no IOError messages. I tried defining list as a dictionary, and there was IOError as well. However, if I defined list as a list, or defined any variable other than 'list' as dict, it would be just fine. Really weird. If I remove the seek method, there would be no IOError message either. It seems that, f.seek plus ' list = somekind of dictionary' caused the file object to close. Great thanks! -shuhsien ---------------------------------------------------------------------------------------------------------------------------- class pdbdict0(dict): def __init__(self): super(dict, self).__init__() self['header'] = '' self['compnd'] = [] # read the pdb file f = open('Z:\\3.4.21.1\\1acb.pdb', 'r') # check if the file is an old type pdb (type = 0) or a new type pdb (type = 1) type = 0 for lines in f: if lines[:6] == 'TITLE': type = 1 if lines[:6] == 'COMPND': break f.seek(0) # read in the information if type == 0: list = pdbdict0() # << this line seems to be causing the file object to close for lines in f: lines = lines[:70] .......................................................................... Traceback (most recent call last): File "C:\Documents and Settings\sheu\My Documents\precise\parspdbtest0.py", line 27, in -toplevel- for lines in f: ValueError: I/O operation on closed file ---------------------------------------------------------------------------------------------------------------------------------------------- From max at alcyone.com Sat Sep 6 01:01:50 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 05 Sep 2003 22:01:50 -0700 Subject: just curious References: <rnd6b.904924$ro6.18233500@news2.calgary.shaw.ca> Message-ID: <3F596A3E.FBB3C3D@alcyone.com> Elaine Jackson wrote: > Any deep reason for this, or "just because"? TIA. It's because the augmented assignment operators, like +=, are supposed to efficiently mutate objects when they have the opportunity (at least for the builtin classes). So a = a + b always creates a new object, but a += b might just mutate a preexisting object if that option is available. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The great floodgates of the wonder-world swung open. \__/ Herman Melville From frr at easyjob.net Fri Sep 12 06:16:35 2003 From: frr at easyjob.net (Fernando Rodriguez) Date: Fri, 12 Sep 2003 12:16:35 +0200 Subject: Trouble with source-code encoding Message-ID: <9u63mvoij7b8h2fh6tmj2e9af1akqjl3de@4ax.com> Hi, I just upgraded to Python2.3 and I'm getting a weird warning complaining about the encoding and asking me to read a pep. OK, I read the Pep and know what syntax to specify the enconding: # -*- coding: <encoding name> -*- However, th epep doesn't list the name of valid encodings. What's the name for west european encoding? From Hoosbruin at Kconline.com Thu Sep 4 19:06:36 2003 From: Hoosbruin at Kconline.com (Andy) Date: Thu, 4 Sep 2003 18:06:36 -0500 Subject: Text file extract Message-ID: <1PudndLL4fUZWMqiU-KYuA@kconline.com> I have a test file and need to split the data based upon a record in a certain field. Then write those record to a multiple files in different folders. Example data: RECORD 1) ABCD,666,TOM,4.00,9/1/03 RECORD 2) TYTY,666,TIM,4.00,9/1/03 RECORD 3) ABCD,666,BILL,4.00,9/1/03 RECORD 4) XXXX,666,TOM,4.00,9/1/03 All the fields will be comma separated and the 3rd field will contain the record I will use to split. So records 1 and 4 get written to the same file call it Cust.txt and write it to folder \\server\tom\Cust.txt Then record 2 gets written to cust.txt in a different folder \\server\tim\cust.txt and so on..... I have never written a Python script so would like to see how this would be done. I deal with a lot of text file input and would like to see how easy Python handles this task.. thanks in advance... If you could doc some of your code so I can follow thru it .. would be great. From paul.moore at atosorigin.com Mon Sep 29 07:49:03 2003 From: paul.moore at atosorigin.com (Paul Moore) Date: 29 Sep 2003 04:49:03 -0700 Subject: What's the best MP3 (ID3) access library to use? Message-ID: <182bcf76.0309290349.452a6643@posting.google.com> I'm looking for a Python library to access ID3 information in MP3 files. A search of Parnassus picked up a number of possibilities, but I can't work out which best suits what I'm trying to do. Some seem out of date, others are Unix only, etc. There doesn't seem to be an obvious "standard" module to use. Basically, I want to write some scripts to "tidy up" a collection of MP3 files, reporting oddities in information, rationalising details, etc. So I believe that my requirements are: - Works on Windows - Allows easy access to title, artist, album info - Allows updates I don't know much about the technical details of MP3/ID3 formats, the objective is basically to automate a slog through a large number of files with an editor program. An example of the sort of thing I want to do - I've got some files with Artist = "Various" and Title = "Real Artist - Track Name" (from compilation albums) and I'd like to change that to Artist = "Real Artist", Title = "Track Name". Thanks in advance for any suggestions, Paul. From br_y at yahoo.de Thu Sep 4 08:43:19 2003 From: br_y at yahoo.de (Birgit Rahm) Date: Thu, 4 Sep 2003 14:43:19 +0200 Subject: Arguments of function as out References: <bj499r$cio$02$1@news.t-online.com> <wzoey20yy4.fsf@nono.cs.uu.nl> <bj6l5v$3qg$06$1@news.t-online.com> <c3C5b.11574$hE5.408554@news1.tin.it> Message-ID: <bj7c1u$kal$05$1@news.t-online.com> Hallo Alex, I hope this posting is near to the netiquette. > Birgit, you do not seem to have *READ* the answer to which you are > replying. I dont understood this in the you described it. > >> * If there is more than one result value, all of them are packed into a > >> tuple, and this tuple is returned. I've read this, but I thought that this tuple is returned with the return statement. I am new to python and I never seen such a constract: > Very well then, > according to the Python language binding which Piet quoted to you, > from the point of view of the Python client code calling X, X is > returning a tuple which packs the three result values! > > So, you call it as: > > a, b, c = X() > > and that's all! Note you do NOT pass arguments corresponding to > out parameters (you DO pass arguments corresponding to in and inout > parameters, if any); you get result values corresponding to the > function's nonvoid return if any (none here) followed by all out > and inout parameters. I have had only the IDL and the py File from the IDL, were stand take *args and return the return value. In none of my python books such a construct is described. I'm sorry. Thanks for helping me, Birgit From sross at connectmail.carleton.ca Wed Sep 24 21:47:07 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Wed, 24 Sep 2003 21:47:07 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> Message-ID: <vNrcb.6695$yD1.1137011@news20.bellglobal.com> "Raymond Hettinger" <vze4rx4y at verizon.net> wrote in message news:95rcb.2002$yU5.1775 at nwrdny01.gnilink.net... > Please comment on the new PEP for reverse iteration methods. # from PEP 322 """ Rejected Alternative Ideas [snip] Add a builtin function, reverse() ... """ Do you mean add a function reverse() (or ireverse()) to the itertools library, or to __builtins__? From tvassila at siac.com Fri Sep 19 10:42:00 2003 From: tvassila at siac.com (Thanos Vassilakis) Date: Fri, 19 Sep 2003 10:42:00 -0400 Subject: Pythonic way of web-programming Message-ID: <OF18CA4E93.B5B1C10F-ON85256DA6.00504E7D-85256DA6.0050BCFE@nsmtp.siac.com> You should look at pso - truly OO and Python We generally develop our web services with pso using CGI. Then release in production under mod_python. PSO abstracts the service handling. You don't really need to learn about mod_python and some things are just much easier: 1) getting environment variables 2) setting and getting cookies, 3) file uploads 4) setting return status 5) redirection And a lot more see: user guide: http://www.scriptfoundry.com/modules/pso/doc/pso-guide.html sessions and mod_python: http://www.scriptfoundry.com/modules/pso/doc/session-modpython.html and the building a site: http://www.scriptfoundry.com/modules/pso/doc/pso-example.html thanos ----------------------------------------- This message and its attachments may contain privileged and confidential information. If you are not the intended recipient(s), you are prohibited from printing, forwarding, saving or copying this email. If you have received this e-mail in error, please immediately notify the sender and delete this e-mail and its attachments from your computer. From oren-py-l at hishome.net Fri Sep 12 07:07:39 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 12 Sep 2003 07:07:39 -0400 Subject: mixing for x in file: and file.readline In-Reply-To: <rowen-222487.13545311092003@nntp1.u.washington.edu> References: <rowen-222487.13545311092003@nntp1.u.washington.edu> Message-ID: <20030912110739.GA43783@hishome.net> On Thu, Sep 11, 2003 at 01:54:53PM -0700, Russell E. Owen wrote: > At one time, mixing for x in file and readline was dangerous. For > example: > > for line in file: > # read some lines from a file, then break > nextline = readline() # bad > > would not do what a naive user might expect because the file iterator > buffered data and readline did not read from that buffer. Hence the call > to readline might unexpectedly skip some lines. > > I stumbled across this the hard way, but am wondering if it's still > present in Python 2.3. Yes. After you start reading a file with 'for' or iter() the current file position is undefined unless you continue to the end of the file. This means that once you start you shouldn't use the read(), readline() or tell() methods unless you first seek() to a well-defined position. The readline() and read() methods use the buffered I/O operations supplied by the underlying C library. You can safely intermix read() and realine() as well as tell()ing and seek()ing around without encountering any unexpected behavior. You can even mix read operations on the same file from Python code and stdio calls from an extension module (after getting the FILE* object using PyFile_AsFile). File iteration uses its own buffering for performance. Guido has declared that "for line in fileobj:" should always be the fastest way to read an entire file line by line. You just can't do that with the crappy stdio implementations out there without adding your own buffering layer. Once you do that it is out of sync with the FILE* object's idea of the current file position. In Python 2.2 if you break in the middle of the loop the temporary iterator object (xreadlines) is lost along with its readahead buffer, leaving you at an unknown file position. The only things you can do are to close the file or seek. In Python 2.3 the file object IS an iterator (rather than HAS and iterator) so while the current file position is undefined from a read/readline/tell point of view the iterator state is still consistent so you can immediately use it in another for loop to continue from the same position or even call its next() method directly. > Anyone know if it's still an issue? If so, anyone have any idea how hard > it would be to fix? I'm willing to work on a patch, but would probably > need some help. And if experts have already determined it's too hard, > and are willing to expain, I'd love some idea of why that is. Really fixing it amounts to reimplementing the entire I/O layer of Python with a different strategy and thoroughly testing on multiple platforms. It's possible to hide the problem in most cases by making read and readline use the iteration readahead buffer if it's attached to the file object and stdio if it isn't. I don't think it's a good idea. It will require some hairy code and and seems susceptible to subtle bugs and corner cases. Another alternative it to make read and readline fail noisily after iteration starts (unless cleared by seek()) Oren From mpeuser at web.de Thu Sep 4 18:39:05 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 00:39:05 +0200 Subject: Optionmenu. References: <bj7j47$g5rpn$1@ID-108351.news.uni-berlin.de> <a7a67196.0309041253.7b35e02d@posting.google.com> Message-ID: <bj8ev9$1ei$07$1@news.t-online.com> "klappnase" <klappnase at web.de> schrieb im Newsbeitrag > > Hi, > > I'm not sure if that is your problem here, but I think you should not use pack() > and grid() inside the same window, otherwise strange things might happen. > Maybe with sofl.grid() it will work. > > Michael Yes of course that's it! I posted same advice some days ago. I overlooked it because it - strangely - worked on my machine. But there seems to be different behaviour with Tk 8.3 and 8.4 Kindly Michael P From aleax at aleax.it Wed Sep 3 03:52:49 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 03 Sep 2003 07:52:49 GMT Subject: artifical intelligence References: <mailman.1062522967.5523.python-list@python.org> Message-ID: <l5h5b.6636$hE5.222040@news1.tin.it> ajsiegel at optonline.net wrote: > >Arthur wrote: > ... > >> *Our* intelligence seems to give us a read as to where on the bell > >> curve a particular event may lie, or a least some sense of when we are > >> at an > >>Wrong: human beings are *eager* pattern-matching devices, extremely prone >>to detect "patterns" that just don't exist in statistically significant >>ways. There's quite a substantial body of literature, by now, on the >>general issue of frequent fallacies on reasoning about probabilities. > > I can accept a "poorly expressed". Not sure I can sign onto a "wrong". The single line of text following this one is one of the longest I've ever seen posted to Usenet - my compliments. Not sure why KDE's KNode showed it to me as a single line (with a left-right scrollbar to let me eventually view it all) but managed to fold it for reply purposes!-). > actual occurrrence of an "unlikely" occurrence. That sense that something > unlikely has occurred is not wrong. And it is hard to put a finger on > everything that goes into coming to such a conclusion. And therefore, I > would presume, difficult to program. Actually, I stick with our line from back in the '80s, when I was doing speech recognition with IBM Research on a strictly probabilistic basis: what we had on our T-shirts was P(A|B) = P(B|A)P(A)/P(B) and you know, there IS really nothing more to it than this formula from 1764... almost;-). And, it IS easy to program, if programmers were in fact humble enough to study and apply statistics and probability rather than looking for "artificial intelligence" silver bullets!-) One thing you do have to estimate heuristically, in order to be able to apply Bayes' theorem to many cases of practical use, is the probability at any time (given an existing body of observations) that the next thing (combination of features) you're going to observe is going to be one you never observed yet (as opposed to, one among the set you did observe). Turing formulated a good heuristic for that, and, I'm told, that heuristic is widely used in biometrics (trying to determine correlations between e.g. umpteen possible features of a butterfly -- long vs short legs, ditto antennae, coloring, wingshape details, ...). I think my own heuristic (a bit more prudent/pessimistic than Turing's) works even better (we did validate that in terms of prediction performance of recognition systems using either heuristic but otherwise identical, and I also have handwaving considerations to justify it). Turing's heuristic boils down to: number of different observations that were made ONCE, divided by total number of observations. So, if your observations so far have been: 1 2 1 3 5 3 5 4 7 7 ... having made 10 observations in total, of which two (items 2 and 5) were observed only once, Turing's heuristic would predict a probability of 0.2 for the next observation being "a surprise" (one never seen before, i.e. one not in the set {1,2,3,4,5,7}). My heuristic boils down to: number of _different_ observations, divided by total number of observations; so, my heuristic would predict a probability of 0.6 for the next observation being "a surprise" (6 different things observed in 10 observations). The difference in prediction is never as high in practical use cases (with MANY observations having been made -- ten isn't "many":-), and of course there's all sort of implicit hypotheses (e.g. practically-infinite alphabet of possible observations compared to the number of actual observations -- when each observation is a combination of many separate features, combinatorial explosion basically guarantees that:-). One could no doubt adjust either heuristic to work better for cases where these hypotheses may fail (e.g. after observing "4 3 1 2" both heristics predict a suprise probability of 1.0, as if repetition of any of the 4 observations already made, once each, was impossible -- that is clearly over-predicting surprises!-). Alex From colarte at telesat.com.co Mon Sep 29 21:31:31 2003 From: colarte at telesat.com.co (Camilo Olarte) Date: Mon, 29 Sep 2003 20:31:31 -0500 Subject: ANN Tkinter Calendar Widget Message-ID: <20030929203131.3eacfe21.colarte@telesat.com.co> If you ever need a calendar dialog in Tkinter , You can use mine: http://pythonical.sourceforge.net/pyTkCalendar.html Camilo Olarte From tim at remove_if_not_spam.digitig.co.uk Mon Sep 22 11:19:05 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Mon, 22 Sep 2003 16:19:05 +0100 Subject: None??? References: <EV6bb.1834$iT4.1283814@news1.news.adelphia.net> <m2he37549i.fsf@host-201.null.null.bellsouth.net> <3F6D68AA.9070603@aon.at> <eppstein-AAC3F1.11134721092003@news.service.uci.edu> Message-ID: <4l4umv4kl82d8t5td29in26cfb57ctb6h0@4ax.com> On Sun, 21 Sep 2003 11:13:47 -0700, David Eppstein <eppstein at ics.uci.edu> wrote: >Arguably, any code that uses / with integer arguments is now buggy, >because it will produce different results in different Python versions. >You should either use // (integer division) or force floating point >division (e.g. by changing the expression to income*percent/100.0). What's the behaviour of "from __future__ import division" on versions that are too old to know about the future of division? From nospamius at lundhansen.dk Sun Sep 7 03:49:51 2003 From: nospamius at lundhansen.dk (Bertel Lund Hansen) Date: Sun, 07 Sep 2003 09:49:51 +0200 Subject: Accessing a file with contents Message-ID: <11ollv853r5jcg977flacu8fl77smei67c@news.stofanet.dk> Hi all I have made some pages where PHP produces a menu and gets the contents from separate files. It works okay. But something I read made me wonder if there smarter ways to access the content file. At present I use include($content). Now I realize that this means that the conten file is PHP-parsed. I use that in some cases so I probably won't change it. If however I only needed to get the text and send it directly to the browser, is it true then that just I can use <? readfile($contents); ?> or <? file($contents); some_smart_way_of_printing_an_array(); ?> Can I trust that readfile() will send the contents to the browser without a specific print() command? I read a note about the new version of file_get_contents() not being very fast (since it got binarysafe). Do others agree with this? I did not see any particular difference in speed when I tried readfile() instead of include(). Does it matter? -- Bertel, Denmark From mark at hahnca.com Tue Sep 30 19:10:09 2003 From: mark at hahnca.com (Mark Hahn) Date: Tue, 30 Sep 2003 16:10:09 -0700 Subject: need help with PyXML Message-ID: <p3oeb.4606$hp5.3567@fed1read04> I am trying to parse HTML for the first time. I first installed 4Suite-1.0a3.win32-py2.3.exe and then realized I didn't need it. Then I installed PyXML-0.8.3.win32-py2.3.exe. Now when I try to execute this as the first line of my module ... from xml.dom.ext.reader import Sax2 ... I get this Exception ... Sequence index out of range: list index out of range Traceback (innermost last): File "<string>", line 1, in ? File "c:\codeshare\codeshare.py", line 4, in ? from xml.dom.ext.reader import Sax2 File "C:\Python23\Lib\site-packages\_xmlplus\dom\__init__.py", line 223, in ? from xml.dom.html import HTMLDOMImplementation File "C:\Python23\Lib\site-packages\_xmlplus\dom\html\__init__.py", line 445, in ? g_numCharEntityPattern = re.compile('&#(\d+);') File "C:\Python23\Lib\sre.py", line 179, in compile return _compile(pattern, flags) File "C:\Python23\Lib\sre.py", line 227, in _compile p = sre_compile.compile(pattern, flags) File "C:\Python23\Lib\sre_compile.py", line 469, in compile code = _code(p, flags) File "C:\Python23\Lib\sre_compile.py", line 453, in _code _compile(code, p.data, flags) File "C:\Python23\Lib\sre_compile.py", line 88, in _compile _compile(code, av[1], flags) File "C:\Python23\Lib\sre_compile.py", line 69, in _compile _compile(code, av[2], flags) File "C:\Python23\Lib\sre_compile.py", line 27, in _compile for op, av in pattern: File "C:\Python23\Lib\sre_parse.py", line 138, in __getitem__ return self.data[index] From tzot at sil-tec.gr Tue Sep 16 17:31:45 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 17 Sep 2003 00:31:45 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <ipicnag7OpxdLfyiRTvUpQ@speakeasy.net> <Hqk8b.382$BS5.239@newsread4.news.pas.earthlink.net> <V_mdnZ3eKoGjif6iRTvUpQ@speakeasy.net> <3F632226.2010607@earthlink.net> <lcydnasf88GLyP6iRTvUrg@speakeasy.net> <EIL8b.6564$ZB4.1083@reader1.news.jippii.net> <f575e202.0309151024.2b7981ea@posting.google.com> <mwo9b.242$B13.103@reader1.news.jippii.net> <mailman.1063660337.3320.python-list@python.org> <5CH9b.81$2k.16@reader1.news.jippii.net> Message-ID: <810fmvcc18e3apgp23mt3dqc7dsdgkm3gj@4ax.com> On Tue, 16 Sep 2003 20:22:41 +0300, rumours say that Harri Pesonen <fuerte at sci.fi> might have written: [snip description of alternative python multithreading mechanisms allowing riddance of the GIL] >It is more efficient to have one process and several threads, than >several processes each having one thread. Please define 'efficient' as used in your statement. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From tjreedy at udel.edu Mon Sep 8 10:16:11 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Sep 2003 10:16:11 -0400 Subject: "Python Redesign" (fwd) References: <mailman.1062982932.16437.python-list@python.org> <87fzj7cvbv.fsf@pobox.com> Message-ID: <TsmdnYgCScjFEsGiU-KYgw@comcast.com> "John J. Lee" <jjl at pobox.com> wrote in message news:87fzj7cvbv.fsf at pobox.com... > It seems fairly clear by now that the purpose of the mockup was to What we were directed to was *not* a mockup (model), but an image of a mockup. That mislabeling was a source of misunderstanding which generated part of the criticism. Please let us keep the useful distinction between a thing and an image of the thing. Terry J. Reedy From ulope at gmx.de Mon Sep 1 11:49:34 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 1 Sep 2003 17:49:34 +0200 Subject: Declaration of an array of unspecified size References: <m814lvc8h44vbd5g1m2iv05r33qg8ag9ta@news.stofanet.dk> <biu6k0$c8fs4$1@ID-67890.news.uni-berlin.de> <biv3jc$h3b$1@news.hccnet.nl> Message-ID: <bivpqf$dmj8a$1@ID-67890.news.uni-berlin.de> "Anton Vredegoor" <anton at vredegoor.doge.nl> schrieb im Newsbeitrag news:biv3jc$h3b$1 at news.hccnet.nl... > > You followed the OP into using "pop" as a name for an instance. > However "pop" is also a *method* of type list. While it's not as bad > as for example using the name "str" for a string ("str" is a build-in > function which is not reachable anymore if it's name is used this way) > this still makes my spider sense tingle. Whether it's because you > failed to mention this or just because it's dialectical I don't know Thanks. I missed that indeed (perhaps due to the time when i wrote that post ;). Cu Ulrich From jseb at cs.mcgill.ca Tue Sep 30 01:05:28 2003 From: jseb at cs.mcgill.ca (Jean-S?bastien Bolduc) Date: 29 Sep 2003 22:05:28 -0700 Subject: isNumber? check References: <vndo742ca2f10@corp.supernews.com> <C30548A9-F240-11D7-9145-003065F081D2@cs.brown.edu> <mailman.1064845475.29494.python-list@python.org> Message-ID: <56e1eff0.0309292105.bab5a2@posting.google.com> > > How do I check if a value is a number in Python? > > > > One way is (x == type(1)) and (x == type(1.2)) and (x == > > type(2387482734274)) and ... > > Why do you want to do so? Maybe, it is better in your > case to just run the piece of code using the number, and > if it fails, it fails. However, if you must, you need to > do type(x) is type(1) and ... etc., or isinstance(x, int) > and isinstance(x, float), etc. I used to use the latter approach suggested by Gerrit, but I recently found on the web an alternative, elegant approach that might work (sorry, I don't recall where I found it!): hasattr(x, '__int__') If the "__int__" method is defined for "x", it is a number. This will work for integer, long, float and complex types, as well as for custom classes that emulate numeric types. Regards, JSeb From essai1 at mci.local Sun Sep 7 13:19:05 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Sun, 7 Sep 2003 19:19:05 +0200 Subject: win32com: create email message in windows default app? References: <z9I6b.18545$n94.7236@fed1read04> Message-ID: <bjfpt5$l3s$1@news-reader4.wanadoo.fr> Hi ! But what is "windows default email application" ? In windows, with WSH, you can write : Dim str,objEmail Set objEmail = CreateObject("CDO.Message") objEmail.From = "toto at titi.fr" objEmail.To = "tata at tutu.com" objEmail.Subject = "Msg-try" objEmail.Textbody = "Corps (body) du (of) message." objEmail.Send Wscript.quit And run, without pb. Other way : use MAPI application (essentially outlook-express, or outlook), but the "default notion" is bad definition (why MAPI more than CDO or more than Python-library ? ) Windows give sockets and applications use sockets, without priority. Applications like yours, virus, trojan, anti-virus, python-scripts, etc. -sorry for my poor english- @-salutations -- Michel Claveau site : http://mclaveau.com From mertz at gnosis.cx Sun Sep 7 20:58:46 2003 From: mertz at gnosis.cx (David Mertz) Date: Sun, 07 Sep 2003 20:58:46 -0400 Subject: "Python Redesign" (fwd) Message-ID: <GR9W/kKkXwkD092yn@gnosis.cx> <tim at pollenation.net> wrote: |2) as an image created in fireworks, I expected line spacing to honor |html spacing. It doesn't however so I've fixed it. I don't know what 'fireworks' is, I suppose it must be some kind of design application. But I figured the image was a screenshot of a rendered page... if not, it indeed might appear a bit different as rendered in an actual browser. |1) it's an image You keep writing this; not just to me, but on c.l.py too. I can't quite figure out what relevance you perceive this fact to have. |2) images don't have font tags Nope... but screenshot images can be made of browsers displaying pages with font tags. I was guessing in the negative that your page was produced (indirectly) from such an HTML document; but perhaps no HTML was ever involved. |3) haven't got a clue what you mean about it fairing badly with css |dropped and fonts and colours changed. Name me a site that would. I don't remember a URL offhand, since those are--almost by definition --sites I do not visit more than once. But, for example, I find some pages choose absurdly small font sizes for various elements; which makes me very happy that I use Mozilla, which has an option for "minimum font size". It doesn't seem always to work, I still sometimes see tiny fonts (I dunno how they get by Moz exactly, maybe Javascript or something). But more often, once the fonts are forced to a readable size, the layout becomes almost unreadable. Sometimes different texts render on top of each other (I think because of the <layers> tag, but it could be something else). Or other times, a text box winds up with one word per line once a readable font is used. Your demo looks a lot like one of those types of sites. It's hard to be sure exactly how it might render if no HTML was ever involved in the design though. |2) The site has to reflect the expectations of commercial customers who |are used to the likes of peoplesoft and atg, etc. I suppose. I'm probably not a "commercial customer", whatever that is... on the other hand, I *am* probably the most widely read writer on Python topics, worldwide (a lot more people read free developerWorks articles than buy books; although a good number bought my book too). I suppose Andy Kuchling gets widely read with his "What's New in ..." and other articles, so maybe more read him. |3) it's an image. Images don't stretch. If I make it any bigger it would |not fit in 800 wide browsers. Then it should BE an image, not an HTML page that creates framing elements but embeds an image in the middle in a way that hides what's an image and what's HTML. If you had taken that more sensible approach, no one on c.l.py would have missed that fact they were looking at an image. I reckon you'd be a lot better off taking the near unanimous criticism of your design seriously than you will be indignantly protesting about the fact your design is an image. I think I'd recommend that even if I understood why you think the image thing is relevant. Yours, David... From tzot at sil-tec.gr Tue Sep 9 03:48:10 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 09 Sep 2003 10:48:10 +0300 Subject: os.listdir References: <2ce42702.0309081441.5c73a772@posting.google.com> Message-ID: <k11rlvk0mt25ulgdtauesgoq0s7crladch@4ax.com> On 8 Sep 2003 15:41:58 -0700, rumours say that pulapaka at ligo.caltech.edu (Hari) might have written: >What I wanted to know was, is it guaranteed that between 2 calls >os.listdir any files added to the directory are appended and the >earlier order is maintained? No, the order of filenames in os.listdir depends on underlying (file|operating) system. The easiest way to find differences would be to use sets. Example: check the /tmp directory for changes in 30 seconds time: >>> import os, time >>> import sets >>> os.chdir("/tmp") >>> files0 = sets.Set(os.listdir(".")) >>> time.sleep(30) files1 = sets.Set(os.listdir(".")) >>> >>> print files1 - files0 Set(['new-file']) ie shows only the file I created in another session for the purpose of this example. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From dkuhlman at rexx.com Mon Sep 8 13:31:04 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 08 Sep 2003 10:31:04 -0700 Subject: Comments on Python Redesign References: <mailman.1062969251.5905.python-list@python.org> <qU9W/kKkXURB092yn@gnosis.cx> <mailman.1062983352.15417.python-list@python.org> <qnY6b.42704$R32.1360114@news2.tin.it> Message-ID: <bjiec6$itc87$1@ID-139865.news.uni-berlin.de> Alex Martelli wrote: > Lulu of the Lotus-Eaters wrote: > >> "Tim Parkin" <tim.parkin at pollenationinternet.com> wrote >> previously: >> |Please could we move this discussion to one of the appropriate >> |lists as >> |well. I suggest python-marketing to begin with. >> >> A marketing list is just not an appropriate forum for discussing >> redesigning the main python website. The page www.python.org >> just simply should not be driven primarily, or even >> significantly, by "marketing" issues... it's us developers who >> use it, in the overwhelming majority. > > So, you're asserting that the target audience of the site IS and > SHOULD BE > "developers". Surprise, surprise: this assertion IS "a marketing > issue". Marketing BEGINS with the identification of target > audiences and the products and services that will best meet the > target audiences' need. > We're not, I believe, arguing about the target audience for Python. We're arguing about the target audience for http://www.python.org. Further more, saying that the choice of a target audience or that the choice of the service and product to be provided is a marketing issue begs the question. It just assumes that marketing should take over decisions about the direction of a company or a site. > Many techies think of "marketing" as a dirty word because it's so > often > misused as an inappropriate synonym for "selling". Using words > properly, marketing is a perfectly legitimate and important > activity: identify who you're addressing, address their needs > through appropriate products and services, communicate to them > that your products and services do address their needs, listen to > their feedback and adjust your products and services to meet their > needs even better, look for other audiences that might get their > needs met by your products and services possibily with some > modifications. These are all good suggestions for a Python promotion site or for a site for a company that sells Python services. No one is arguing that marketing and sales are illegitimate. David Mertz has already offered to sell "Python in a box with extras" for $299, possibly even for less if you say, "Guido sent me". But, please don't do it at http://www.python.org. I am on the side of those who say that the marketing and promotion should not be done at the Python home page, http://www.python.org. It does not seem to be the main focus at http://www.perl.org/ nor at http://java.sun.com/. What promotion is done at those sites (and the current Python home site) is done through helping developers and not through paid endorsements etc. The Java site, by the way, looks like they copied www.python.org, then polished it and edited it for Java. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From tjreedy at udel.edu Thu Sep 25 19:28:38 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 25 Sep 2003 19:28:38 -0400 Subject: RELEASED Python 2.3.1 References: <mailman.1064390741.20344.python-list@python.org> <bksi8l$5bce8$1@ID-130333.news.uni-berlin.de> <u172glc2.fsf@python.net> <bktgkc$5gk64$1@ID-130333.news.uni-berlin.de> <ad8tfdwv.fsf@python.net> <DdacnR-12Jpma--iU-KYvA@comcast.com> <smmkex9o.fsf@python.net> Message-ID: <CKCdnSDxdui65-6iXTWJhg@comcast.com> "Thomas Heller" <theller at python.net> wrote in message news:smmkex9o.fsf at python.net... > "Terry Reedy" <tjreedy at udel.edu> writes: > > I agree that a separate Windows run-only distribution (including .pyc > > instead of .py files) would be a good idea. > > Why would you distribute .pyc instead of .py files? Off the top-of-my-head thought: so they could be pre-zipped without interpreter having to write them. But I remember now discussion of turning off .pyc writes if desired. Anyway, such decisions are for the doers. >Most of the time > they are not even smaller, and tracebacks would be problematic. Tracebacks? Production consumer apps shouldn't have them, should they? :-) Terry J. Reedy From martin at v.loewis.de Fri Sep 19 00:52:00 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 19 Sep 2003 06:52:00 +0200 Subject: Unicode 4.0 updates to unicodedata? References: <opstad-79936B.15531718092003@news.inreach.com> Message-ID: <m3smmtgz2n.fsf@mira.informatik.hu-berlin.de> David Opstad <opstad at batnet.com> writes: > Anyway, on to the question. Now that Unicode 4.0 has been released (just > got my copy today), any guesses on how long before the unicodedata > module will be updated to include all the new names? It might happen for Python 2.4, but by the time Python 2.4 is released, the Unicode 4.0 database might get skipped, and Python might incorporate Unicode 4.2 (or some such) instead. The tricky part is that IDNA specifies Unicode 3.2 as the basis of international domain names, so some technology must be found to incorporate two versions of the database in Python, without adding too much overhead. > How do things like that work, anyway; is there somebody whose task > it is to update that, or are they awaiting volunteers to help out? In general, it would be somebody's task (i.e. mine) to incorporate a new version. However, since this is more than running the generator again (as actual code changes have to go with it), contributions are welcome. > And once the module is updated, is it generally usable on earlier > Python releases (I'm running the 2.2 that came with the OS X > developer package for Jaguar)? If you want to backport that database yourself, you could just as well create your own version of the Unicode 4.0 database. Just run the generator, and rename the unicodedata module to unicodedata40 (inside the module's source code). Python won't then use this database internally (for .is*, and .upper, ...), but you could readily invoke the unicodedata40 functions yourself. Regards, Martin From jjl at pobox.com Mon Sep 29 10:49:14 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Sep 2003 15:49:14 +0100 Subject: query References: <2003929-93022-80040@foorum.com> Message-ID: <87pthj3b11.fsf@pobox.com> drn <bmproj2003 at yahoo.com> writes: > sir/madam, Oops. Your subject line and this formal greeting makes your message look like spam. People rarely say anything more formal than 'hi' on USENET, and quite often nothing at all. And your subject line tells people almost exactly nothing (and why is that Re: there -- you're not replying to any message, are you?). > as we are going to develop a educational s/w for children at preprimary level > we are facing some problems in deciding what platform to choose and what s/w to > use. so please help. > -we have more of graphics work. What kind of graphics? I don't know the right questions to ask you here, but telling us whether it's 2D or 3D would be a start... > -we have two students working simutaneously on one system. > -we will be having 4-5 systems in total in one classroom. > > -----shall we go for one system as a linux sever with somewhat higher [...] This isn't a Python question. Try one of the comp.os.linux* groups, perhaps. > -----which lanuage do you suggest - c/c++ or any browser based software like > php/python. You need to give more information about your objectives. Certainly I'd strongly reccommend all newbies to avoid C and C++ like the plague until they know *exactly* why they need them (you may well not need them at all). Still, you might like to look at Pygame: http://pygame.org/ > please help and send your suggestions as soon as possible. > my email id is bmproj2003 at yahoo.com It's usually called an "email address", not an "email id". :-) John From daniel at dittmar.net Mon Sep 22 17:46:36 2003 From: daniel at dittmar.net (Daniel Dittmar) Date: Mon, 22 Sep 2003 23:46:36 +0200 Subject: Calling functions before that are def'ed In-Reply-To: <944840ff.0309221318.35d2f9cd@posting.google.com> References: <944840ff.0309221318.35d2f9cd@posting.google.com> Message-ID: <bknqk1$3qt$1@news.eusc.inter.net> Charles Larry wrote: > Is there a way to define functions after the main part of a Python > script? > > Example: > > #!/usr/local/bin/python > > # this code yields a NameError > > print_message("hello world") > > def print_message(msg): > print msg #!/usr/local/bin/python def main (): print_message("hello world") def print_message(msg): print msg if __name__ == "__main__": main () def statements are really executable statements and not declarations, so the order is important. Daniel From aleax at aleax.it Tue Sep 23 10:29:44 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 23 Sep 2003 14:29:44 GMT Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <SnObb.1581$PT3.257319@news20.bellglobal.com> <eppstein-E0F40C.21003222092003@news.service.uci.edu> <cthvmvk3uif5qt1hkftmp2hbdia74fjq3d@4ax.com> <bkp40c$j0o$1@news1.wdf.sap-ag.de> <_9Vbb.105320$hE5.3711223@news1.tin.it> <mailman.1064315851.23004.python-list@python.org> Message-ID: <sNYbb.148529$R32.4815673@news2.tin.it> Gerrit Holl wrote: > Alex Martelli wrote: >> >> Also, one extra feature is that the loop can be infinite (which range >> >> and xrange cannot achieve)... >> >> >> >> for i in int [0:] : >> >> No way, Jose -- now THAT would break things (in admittedly rare >> cases -- a method expecting a list and NOT providing an upper bound >> in the slicing). I'd vote for this to be like int[0:sys.maxint+1] >> (i.e., last item returned is sys.maxint). > > This one breaks the int/long unification. In an ideal unification > of ints and longs, sys.maxint would not exist any more, and the > upper bound would be seemingly random. If this is the "party line" -- that not providing an upper bound when indexing int should generate an infinitely looping iterator -- then I think the risk of nasty bugs would probably be too high, and I would reluctantly -1 the otherwise nice proposal. I'd rather have the missing upper bound be an error in this case (and rely on itertools.count for very explicit building of infinitely looping iterators) than "easily create infinities" in response to typos;-). Alex From bokr at oz.net Wed Sep 3 12:24:41 2003 From: bokr at oz.net (Bengt Richter) Date: 3 Sep 2003 16:24:41 GMT Subject: Location of bytecode files (pyc) References: <6f03c4a5.0309021745.3a79d951@posting.google.com> <m3ekyyjw0o.fsf@mira.informatik.hu-berlin.de> Message-ID: <bj54k9$tpl$0@216.39.172.122> On 03 Sep 2003 07:12:07 +0200, martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) wrote: >rimbalaya at yahoo.com (Rim) writes: > >> How can I control the location of the bytecode files? > >You currently can't. See PEP 304, though, at > >http://www.python.org/peps/pep-0304.html > >Comments on the PEP are encouraged: If you won't comment now on >whether the proposed change would solve your problem, it might be that >you find something useless got implemented later. > Personally, I am a minimalist when it comes to environment variables. IMO that name space has the same problems as any global namespace, and since a single default set of user's environment variables tends to presented to most programs s/he runs from a command window, the name space usage tends towards a hodgepodge and/or wrapping apps in setup scripts (which can work fine, but I still don't like it as a standard way to go). IMO the os.environ name space should be treated like a root directory name space, and not have application data per se in it (with reluctant exceptions where it is used wholesale as in CGI). Rather, IMO, and only if necessary in the first place, it should be used to specify location or search path info for config data, not *be* config data. And a user-set environment variable should not be able to cause a bypass of root/admin-defined config info where the distinction is necessary. (The PYTHONBYTECODEBASE variable does refer to a directory, but now that makes two variables, counting PYTHONPATH, and where will it end?) Provision for admin/root level config data separate from user preference and session state type config data should be made as necessary and desirable, but secondary/user config data search should be controllable by the primary/root/admin config data (which e.g. could say to ignore or use user-controlled/attempted-control environment variables etc.). This would seem to imply a standard place to look for root/admin level config data, not directed by env variable. E.g., a read-only file in the same directory as the python interpreter executable, with, say, .conf or .cfg appended to the name. *That* file can then specify how/whether to look for user config stuff etc., or specify password access to some features, etc. etc., if we wind up doing restricted exec stuff. A user config file overriding any other *user* config info could be specified by command line option, e.g., -cfg myConfigFile.conf, and whether this or other command line options were allowed could be (and should be able to be when control is necessary) specified in the root/admin config file. ... just my .02USD Regards, Bengt Richter From mertz at gnosis.cx Thu Sep 11 03:56:31 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Thu, 11 Sep 2003 03:56:31 -0400 Subject: OT: Americans love their guns References: <vkm8j0a086acd0@corp.supernews.com> <mailman.1061927168.7845.python-list@python.org> <c60rkvkpog2jabqkvbiaqnjm35vuf0iabk@4ax.com> <mailman.1062051665.5511.python-list@python.org> <l0nskvk7d2uptngokjl4al0bjqueielk2g@4ax.com> <mailman.1062103458.11215.python-list@python.org> <slrnblj40a.vc8.grey@dmiyu.org> <bjd8ov$93g$0@216.39.172.122> <slrnbllgu3.di8.grey@dmiyu.org> <m3k78j6v5e.fsf@tanelorn.bandersnatch.org> <vCu7b.201587$2x.57934@rwcrnsc52.ops.asp.att.net> <16223.15950.299463.959577@montanaro.dyndns.org> <mailman.1063251143.12678.python-list@python.org> <slrnbm08ud.d9.gstaniak@inka.zagiel.pl> <blCY/kKkXgGD092yn@gnosis.cx> Message-ID: <vqCY/kKkXEub092yn@gnosis.cx> Grzegorz Staniak <gstaniak at inka.zagiel.pl> wrote previously: |I think it's a mistake to cite Lott here. As an extreme libertarian he |has shown his own bias a couple of times. His famous "More guns, less |crime" findings has been challenged recently (see e.g. |http://www.jointogether.org/gv/news/alerts/reader/0,2061,562387,00.html As well as Lott's tendency to outright falsify data, which Staniak cites, Lott is pretty much an unabashed White Supremicist ideologue, e.g.: http://www.vpc.org/fact_sht/wholott.htm He's actually quite a nut in a lot of ways other than that, for example arguing that dioxin is harmless to people; or that wealthy people should not be punished for committing violent crimes, only poor people. Yours, Lulu... -- 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 tjreedy at udel.edu Thu Sep 4 09:22:16 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 4 Sep 2003 09:22:16 -0400 Subject: test References: <6QF5b.581$FJ5.34940@twister.columbus.rr.com> Message-ID: <pSadnZpJEJMUocqiXTWJkA@comcast.com> "Jamey Cribbs" <jcribbs at twmi.rr.com> wrote in message news:6QF5b.581$FJ5.34940 at twister.columbus.rr.com... > Please disregard this messag Please use misc.test to test-post: first open that newsgroup and 'catchup' (have newsreader mark all as read; then make test post with distinctive subject, then wait a bit, depending on your news source, then reopen misc.test (with ignore-read-messsages set) and look for post. Terry J. Reedy From gherron at islandtraining.com Fri Sep 19 11:50:47 2003 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 19 Sep 2003 08:50:47 -0700 Subject: Fsrit Propttoye: SCLABMRE In-Reply-To: <16232.24354.366003.171152@gargle.gargle.HOWL> References: <16232.24354.366003.171152@gargle.gargle.HOWL> Message-ID: <200309190850.47841.gherron@islandtraining.com> Wow! This otavbeiorsn is both aimznag and eaittnnnerig. I was trohugh the Sjceubt: line and into the fisrt senencte brefoe I even rleeiazd annhtiyg was odd. Tahkns, Gary Herron On Wednesday 17 September 2003 06:18 am, Frnak "Sealmbcrd Eggs" Lomax wrote: > I hvae jsut fhiseind rniedag a Shdlaost atrlcie from Mnoday, Sbepemetr > 15th, aobut an ingtriniug sdtuy from Cgbdirmae Uinevtrsiy, dciinesrbg > how wodrs with thier itienrors selmrbacd can siltl be rdbaleae. > Bcaeuse of the tioeznme that I lvie in, an initettrment dfceet in my > clbae medom, and the lneiignrg atfer-ecfefts of my lsat "mohsroum > salad exntarvzagaa", I am aaylws two days bhneid on the Web. > > So suentnd was I at the icoinatpimls of this study, taht I > cunlqtneesoy decedid to doetve my etrnie lfie and gtelray aeamssd > fnrtoue on cunitodcng ftrhuer rasreech and dnpeeelmvot into tihs > lifnsaevig tghlocnoey. As a cross-eeyd dxsiyelc, I konw that teshe > cilmas of svotailan are niehetr hlroyepbe nor bmobaistc > over-daaomtiazitrn. > > Pnseetred hree for your rveiew, aaovpprl and disiscsuon, is our > poyptotre sytsem, caelld SLABCRME for SeCren Rslmnebeig Aacrihc > Mnoaaluptiin of BetaoLd Ecuitolon. I have scnie bugen a meosdt > sutartp based in Aceicdnt Maarnlyd, and we will soon be reeianlsg an > Olutook puglin, anolg with a sftorwae devmoeelpnt kit, and oethr > digintoasc tloos. Smoe of our tlgeocnhoy wlil nallaruty be open > sruoce, but I do ietnnd and ecpext to frutehr etnxed my hoougmuns > wtaleh by sinlelg sftorawe lcseiens and srhink wrapped ratiel pocrudt. > Psaele cactnot us for more iomrfaiontn. > > I'm aslo in enpommelyt duicnssioss wtih the Tmboit; I ecepxt that he > can bosot the pmecarrofne of our pooyptrte's itmpeanetolmin > salreolefvd, at wcihh piont we will be pthincig emdbeded ssmeyts to > the mfntacuuearrs of ruoters, eiltncreoc trprwyeiets, psnreoal dtaiigl > astsntsais, eorctinlec cepmutor coltlerond tersotas, maet prbeos, RFC > 1149 digtail cemara pheons, and nxet gniaoetern wopehoe csionuhs. > > hinpog-to-be-deotersyd-by-moroscift-ly y'rs, > -fnark From yaipa at yahoo.com Wed Sep 10 03:54:26 2003 From: yaipa at yahoo.com (yaipa h.) Date: 10 Sep 2003 00:54:26 -0700 Subject: OT: Americans love their guns References: <vkm8j0a086acd0@corp.supernews.com> <mailman.1061927168.7845.python-list@python.org> <c60rkvkpog2jabqkvbiaqnjm35vuf0iabk@4ax.com> <mailman.1062051665.5511.python-list@python.org> <l0nskvk7d2uptngokjl4al0bjqueielk2g@4ax.com> <mailman.1062103458.11215.python-list@python.org> <slrnblj40a.vc8.grey@dmiyu.org> <mailman.1062872349.11430.python-list@python.org> Message-ID: <6e07b825.0309092354.158e6d45@posting.google.com> Lulu, Some how I get this feeling this is secretly YOUR plan to re-acquire the United States... Sometime after national "Jones Town Day in May." ;^) Cheers, --Alan Lulu of the Lotus-Eaters <mertz at gnosis.cx> wrote in message news:<mailman.1062872349.11430.python-list at python.org>... > Steve Lamb <grey at despair.dmiyu.org> wrote previously: > |If guns were such a overriding factor why is it the UK has as high > |if not higher rate of gun related violence than the US? > > I guess the answer is that this belief is absurdly far from the truth, > so it probably cannot be "explained" in that sense. > > The USA gun fatality rate is about 10.4 per 100k. The UK has a rate > considerably below 1 per 100k. It's true, however, that Guy Ritchie > made some violent films about brits, so maybe that's where the imagined > rates come from. > > For US rate, see: > > http://webapp.cdc.gov/sasweb/ncipc/mortrate10.html > > I nice comparison of various countries is at: > > http://www.dvc.org.uk/~johnny/dunblane/homemain.pdf > > In particular, look at the chart on p.4. Somewhat of an anomoly is that > Switzerland, which has nearly half the gun ownership rate of USA has > less than 1/4 the gun homicide rate (still, the Swiss with their lots > more guns than UK, thereby have lots more murders than UK). New Zealand > and Australia are lower in both rates, but the proportions are even more > skewed. > > So while the mere correlation between gun ownership and gun violence is > not perfect, all those countries with vastly lower gun ownership rates > have vastly lower homicide rates. > > Yours, Lulu... From zefram at wolverine.lohacker.invalid Mon Sep 29 19:23:02 2003 From: zefram at wolverine.lohacker.invalid (Emmanuele Bassi) Date: Mon, 29 Sep 2003 23:23:02 GMT Subject: centering a dialog in pygtk References: <mailman.1064585256.21158.python-list@python.org> Message-ID: <slrnbnhfls.9qn.zefram@wolverine.lohacker.net> * sjsmith3 at comcast.net [2003-09-26 16:06]: > Is there a way to center a dialog on a screen? This should be done by the window manager. Nevertheless, you could force the position of a window by using the gtk.Window::set_position method: w = gtk.Window(gtk.WINDOW_TOPLEVEL) w.set_position(gtk.WIN_POS_CENTER) Bye, Emmanuele. -- Emmanuele Bassi | [ http://digilander.libero.it/ebassi/ ] emmanuele.bassi(at)iol.it | Linux User #170621, http://counter.li.org GnuPG Key fingerprint = 4DD0 C90D 4070 F071 5738 08BD 8ECC DB8F A432 0FF4 From NO-MAIL at hotmail.com Tue Sep 16 15:25:05 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 19:25:05 GMT Subject: Tkinter: tooltips (Windows) Message-ID: <lsJ9b.13162$x21.6784@twister.southeast.rr.com> How can I have tooltips for buttons of a toolbar or for control items of a dialog? Does such feature exist at all? M-a-S From starbuck_ms at yahoo.com Wed Sep 17 23:59:45 2003 From: starbuck_ms at yahoo.com (Michael Sweeney) Date: 17 Sep 2003 20:59:45 -0700 Subject: convert ints in a range to strings References: <bkap6g$4o1$1@solaris.cc.vt.edu> Message-ID: <a4fa626b.0309171959.2ccdf688@posting.google.com> > Hi, > > I'm trying to do this: > > ------------------------------ > a="192." > b="168." > c="1." > r = range(256) > for r in r: > print a + b + c + r > ------------------------------ > You could try this: a="192" b="168" c="1" for d in range(256): print "%s.%s.%s.%s"%(a,b,c,d) 192.168.1.0 192.168.1.1 192.168.1.2 192.168.1.3 ... 192.168.1.255 - Mike From max at alcyone.com Mon Sep 22 18:26:17 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 22 Sep 2003 15:26:17 -0700 Subject: string.rstrip References: <731fc603.0309221414.78a92789@posting.google.com> Message-ID: <3F6F7709.5EA37011@alcyone.com> Hank wrote: > I have this problem with string.rstrip > > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import string > >>> mystr = "test.txt" > >>> mystr = string.rstrip(mystr, ".txt") > >>> print mystr > tes > > The last 't' was stripped. What you mean is the result is 'tes', which is correct. > Is this fixed or documented anywhere? it > works for other cases, but this one seems to give me a weird result. You're using .rstrip incorrectly. The second argument to string.rstrip is a list of characters, any one of which will be stripped if they are at the end of the string. So you're not saying, "remove .txt from the end of the string," you're saying, "remove any of the characters ., t, or x from the end of the string until you don't find anymore." Since you give it test.txt, that means it strips everything up to the s, since they're all one of those characters. It's documented in the library reference as well as the interpreter help facility. http://www.python.org/doc/current/lib/module-string.html help(''.rstrip) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Grab a club and join the chorus / Evolution is a state of mind \__/ Oleta Adams From SBrunning at trisystems.co.uk Mon Sep 22 10:22:39 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 22 Sep 2003 15:22:39 +0100 Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale re lated?)) Message-ID: <31575A892FF6D1118F5800600846864D014B294F@intrepid> > From: Peter Otten [SMTP:__peter__ at web.de] > Everytime that someone posts a naive list.sort(compare), the DSU pattern > is > proposed to improve execution speed. > > So maybe it's about time to change the sort() method to support a second > argument > > list.sort(compare=None, mapping=None) > > that, if provided, would perform the DSU magic. Or was that already > proposed > and rejected? Perhaps 'decorator' would be a better name than 'mapping'? Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- 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 jjl at pobox.com Wed Sep 3 08:58:00 2003 From: jjl at pobox.com (John J. Lee) Date: 03 Sep 2003 13:58:00 +0100 Subject: Writing solid code book References: <b15d2792.0309030339.3ac939e7@posting.google.com> Message-ID: <87wucqni5j.fsf@pobox.com> post400 at prontomail.com (post400) writes: > there is another famous book 'Writing solid code' but does it apply to > Python ? Or it's usable only by Microsoft C programmers ? The author > seems to be an ex-Microsoft guy ! Never read it, but from the blurb about and extract from it in my copy of Code Complete it certainly sounds pretty focused on C. The Python Cookbook is the first book I'd have on my list if I were learning Python now (O'Reilly, eds. Martelli & Ascher). John From jdhunter at ace.bsd.uchicago.edu Sun Sep 14 19:12:25 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 14 Sep 2003 18:12:25 -0500 Subject: Huh?!?!? What is it that I'm seeing here? In-Reply-To: <Mj59b.21551$dk4.670845@typhoon.sonic.net> (Don Bruder's message of "Sun, 14 Sep 2003 21:45:16 GMT") References: <Mj59b.21551$dk4.670845@typhoon.sonic.net> Message-ID: <m265jvx8va.fsf@mother.paradise.lost> >>>>> "Don" == Don Bruder <dakidd at sonic.net> writes: Don> if __name__ == '__main__': run(argv[1:]) You can safely ignore these in your conversion project. if __name__ == '__main__' This means if the text file "somefile.py" holding the module code is run as the main file, as in > python somefile.py or > ./somefile.py if the file has an executable bit set run(argv[1:]) This means "call the function run, passing command line arguments as arguments". Basically, the code at the bottom allows any python module to save the same purpose as the C/C++ function 'main'. Once you have converted the python module, and implemented the function "run" in your C/C++ code, you would do something like int main( int argc , char** argv ) { run(argv); } Cheers, John Hunter From fawcett at teksavvy.com Mon Sep 8 01:35:34 2003 From: fawcett at teksavvy.com (Graham Fawcett) Date: Mon, 08 Sep 2003 01:35:34 -0400 Subject: exec code with timeout? In-Reply-To: <Xns93EFE34728E26OKB@130.133.1.4> References: <Xns93EFD117DA30FOKB@130.133.1.4> <mailman.1062996311.6727.python-list@python.org> <Xns93EFE34728E26OKB@130.133.1.4> Message-ID: <3F5C1526.2040205@teksavvy.com> OKB (not okblacke) wrote: >Graham Fawcett wrote: > > > >>The RestrictedPython module in Zope may suit your needs; it was >>designed for a >>similar use scenario. Search the list, there was a discussion about >>RestrictedPython not long ago. >> >> > > Thanks. I looked at the page that was referenced from here, but it >says RestrictedPython "doesn't implement resource limitations, like >preventing scripts from eating up all available RAM or simply never >terminating". Preventing scripts from never terminating is exactly what >I am interested in. (This isn't a halting problem kind of thing -- I >just want to unceremoniously kill exec-ed code that doesn't terminate in >a given amount of time.) Also, it seems a bit heavyweight. The page >implies that it uses a modified compiler, etc.; I don't know how that >would work with running interactively edited code. > > > Hmm... well, again I'd suggest the PyThreadState_SetAsyncExc function. It shouldn't be that hard to wrap... I'd try it myself, but haven't made it to 2.3 yet. :( Or, if you're in Unix-land, how about forking? Let the user code run in the child fork, and let the other half take care of the timeout? It's easy to kill processes. -- G From gherron at islandtraining.com Wed Sep 10 18:03:34 2003 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 10 Sep 2003 15:03:34 -0700 Subject: Background image in toplevel In-Reply-To: <Xns93F2869B93CCFhowardeegsoftwarecom@64.164.98.51> References: <Xns93F2869B93CCFhowardeegsoftwarecom@64.164.98.51> Message-ID: <200309101503.34119.gherron@islandtraining.com> On Wednesday 10 September 2003 01:13 pm, Howard Lightstone wrote: > Is there any way to display a photoimage background in a toplevel/frame? > > I tried replacing my topmost widget with a canvas but the ripple effects on > placement and other widgets got too high. > > Is there some way to specify a transparent background on a frame? Then I > could overlay a (tranparent) canvas window over the photoimage on the basic > canvas but leave a frame widget (in the window) for position, placement, > etc. Python has a binding to *many* different GUI libraries. I'd guess you are asking about Tkinter, but you really ought to tell us that right up front. On top of that, I don't understand what you're trying to accomplish or what you mean by a "ripple effect". If you can be much more specific abour the GUI and problem, I (and probably others) will try to help. Gary Herron From buzzard at urubu.freeserve.co.uk Fri Sep 26 20:21:03 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 27 Sep 2003 01:21:03 +0100 Subject: Saving Numeric arrays to file? Message-ID: <bl2ktf$8lq$1@news6.svr.pol.co.uk> I am having problems saving arrays to file. e.g. >>> t1 array([30]) >>> t2 array([ 0, 0, 5, 5, 5, 10]) >>> t3 array([20, 5]) >>> t4 array([[ 0, 5, 10, 5, 0, 10], [ 0, 0, 0, 5, 0, 0]]) >>> f = file('c:\Data\IS_rounded.txt', 'w') >>> f.write(t1.tostring() + '\n') >>> f.write(t2.tostring() + '\n') >>> f.write(t3.tostring() + '\n') >>> f.write(t4.tostring() + '\n') >>> f.close() >>> >>> f = file('c:\Data\IS_rounded.txt', 'r') >>> Numeric.fromstring(f.readline().strip()) array([30]) >>> Numeric.fromstring(f.readline().strip()) array([0, 0, 5, 5, 5]) # missing final element >>> Numeric.fromstring(f.readline().strip()) Traceback (most recent call last): File "<pyshell#181>", line 1, in -toplevel- Numeric.fromstring(f.readline().strip()) ValueError: string size must be a multiple of element size >>> Anyone any idea where I'm going wrong? 2.3 on Win2k. Cheers. Duncan From http Mon Sep 15 17:33:16 2003 From: http (Paul Rubin) Date: 15 Sep 2003 14:33:16 -0700 Subject: Ways to improve this clock algorithm? References: <33fbf9ec.0309151302.462db544@posting.google.com> Message-ID: <7xoexl4u03.fsf@ruckus.brouhaha.com> jacobsmail at gmx.net (Jacob H) writes: > Hello all, > > I'm close to being a novice programmer and I never was good at math. > So I'm curious to know ways in which this following code can be made > more efficient, more elegant. The code just calculates and displays > elapsed wall clock seconds since initialization. > > class ExampleTimer: > def __init__(self): > self.start = time.clock() > > def run(self): > while 1: > now = time.clock() > allseconds = int(now) = int(self.start) I think you mean allseconds = int(now) - int(self.start) Now you can say hours = allseconds // 3600 minutes = (allseconds // 60) % 60 seconds = allseconds % 60 instead of counting up to allseconds. You could also use the divmod function for a fancier way to do the same thing, but the above is straightforward enough. From roy at panix.com Thu Sep 4 00:06:00 2003 From: roy at panix.com (Roy Smith) Date: Thu, 04 Sep 2003 00:06:00 -0400 Subject: Writing solid code book References: <b15d2792.0309030339.3ac939e7@posting.google.com> <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> Message-ID: <roy-0F3EF6.00055904092003@reader2.panix.com> Jules Dubois <bogus at invalid.tld> wrote: > My "Software Engineering" class votes again tomorrow on the language we use > for our group project. Tuesday's vote was Java (8 votes), Python (5), C++ > (3), and Smalltalk (1); Thursday's vote will be between Java and Python. I > get the opportunity to learn one or the other in a week. How many votes does a language need to get to be elected Governor of California? From jbperez808 at yahoo.com Mon Sep 22 12:22:02 2003 From: jbperez808 at yahoo.com (Jonathan P.) Date: 22 Sep 2003 09:22:02 -0700 Subject: Pythonic way of web-programming References: <mailman.1063982609.23755.python-list@python.org> Message-ID: <f57664b9.0309220822.66895246@posting.google.com> Giorgi said: > Recently I have started to make a Georgian language based > web-site for Python. It was a natural feeling not to use, say, > php or perl for web-content management. I have gone through > different approaches available in Python; namely: For those who like working with HTML-embedded scripting languages (ala PHP), Spyce (spyce.sf.net) gets my thumbs up vote - definitely Pythonic. From adalke at mindspring.com Fri Sep 19 20:53:06 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sat, 20 Sep 2003 00:53:06 GMT Subject: Passing data out of a Sax parser References: <fe5nmv0mno1ib23ifekntp3v3u2er5bstt@4ax.com> Message-ID: <SxNab.10403$BS5.7382@newsread4.news.pas.earthlink.net> Tim Rowe: > b. Add a parameter to the handler's __init__ method, that takes some > sort of mutable object, and put the answer into that object. Either that or have startDocument create the mutable object, as class MyHandler(xml.sax.handlers.ContentHandler): def startDocument(self): self.count = 0 def startElement(self, name, attrs): if name == "spam": self.count += 1 parser = xml.sax.make_parser() h = MyHandler() parser.setContentHandler(h) h.parse(input) print h.count Andrew dalke at dalkescientific.com From d2003xx at hotmail.com Sun Sep 21 20:15:37 2003 From: d2003xx at hotmail.com (d2003xx) Date: 21 Sep 2003 17:15:37 -0700 Subject: Help me choose a C++ compiler to work with Python References: <616fccba.0309210907.1e35b92d@posting.google.com> Message-ID: <3dd5593c.0309211615.747ba123@posting.google.com> rh4170056 at juno.com (rhmd) wrote in message news:<616fccba.0309210907.1e35b92d at posting.google.com>... > Just found Python and I love it. What an elegant language! > I would like to use it for various applications, but the > mathematical calculations are way too slow (a million sines 8 seconds > in Python vs. 2 seconds in Excel VBA), so was thinking of learning > enough C++ to do the number crunching in C++ and integrating the C++ > routines with Python. My question: > My question: > Which compiler works best with Python? > I use Windows XP and 98. Have very little experience with C++. Am > doing statistical and other simulations that require billions of > calculations (taking 1 to 2 hours in Excel VBA). GCC is free, MS > C++.Net is affordable The standard C/C++ compiler (no optimization) is included in .Net framework SDK, which is available for free in M$'s web-site. > at <$100 but supposedly has problems until the > next version (and I could only use it on my XP machine), older > versions of MS C++ are no longer for sale. What's the most robust > solution? I would also like to make .dll files that I can plug into > MS Excel. > Sorry for the vagueness of this question, but I'm sure many of you > have experience with this and any information, opinions, and even > prejudices about the various compilers are welcome. I guess gcc is the only choice.. If you don't mind that it takes forever to compile C++ source code, until version 3.4 is released (it will supports pre-compiled header). From p.useldinger at myrealbox.com Thu Sep 11 16:02:32 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Thu, 11 Sep 2003 22:02:32 +0200 Subject: ftplib question: how to upload files? References: <mailman.1063305377.21943.python-list@python.org> Message-ID: <r3l1mv0pc6cf9idm1qrs95b9457krn4j25@4ax.com> On Thu, 11 Sep 2003 14:35:32 -0400 (EDT), python at sarcastic-horse.com wrote: >What do I do to send files? I use this: f=file(fileName,'rb') conn.storbinary('STOR '+os.path.basename(fileName),f) -PU From maxm at mxm.dk Wed Sep 24 05:06:23 2003 From: maxm at mxm.dk (Max M) Date: Wed, 24 Sep 2003 11:06:23 +0200 Subject: Bottleneck? More efficient regular expression? In-Reply-To: <mailman.1064393134.9084.python-list@python.org> References: <3f7069db_4@corp.newsgroups.com> <oA6cb.1241$RW4.485@newsread4.news.pas.earthlink.net> <mailman.1064393134.9084.python-list@python.org> Message-ID: <3f715e81$0$97260$edfadb0f@dread12.news.tele.dk> Fredrik Lundh wrote: > the DOM API is designed for consultants, not for humans or > computers. :-D QOTW ? regards Max M From jepler at unpythonic.net Sun Sep 28 21:13:48 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 28 Sep 2003 20:13:48 -0500 Subject: Recursion In-Reply-To: <xjLdb.565$Vb3.450032@news1.news.adelphia.net> References: <xjLdb.565$Vb3.450032@news1.news.adelphia.net> Message-ID: <20030929011348.GB21627@unpythonic.net> > "Explanation From the Book Begins Here"++++++++++++++++++ > > >def factorial(n): > > if n == 0: > > return 1 > > else: > > recurse = factorial(n-1) > > result = n * recurse > > return result > > > > The flow of execution is as follows. > > If we call "factorial" with the value 3: > > > > Since 3 is not 0, we take the second branch and calculate the > > factorial of n-1... > > Since 2 is not 0, we take the second branch and calculate > > the factorial of n-1... > > Since 1 is not 0, we take the second branch and calculate > > the factorial of n-1... > > Since 0 is 0, we take the first branch and return 1 > > without making any more recusive calls. > > The return value (1) is multiplied by n, which is 1, > > and the result is returned. > > The return value (1) is multiplied by n, which is 2, and the > > result is returned. > > The return value (2) is multiplied by n, which is 3, and the > > result, 6, becomes the return value of the function that started > > the whole process. > "Example Ends Here"++++++++++++++++++++++++++++++++ > On Mon, Sep 29, 2003 at 12:48:29AM +0000, Jakle wrote: > I thought I understood what was going on untill "Since 0 is 0...", but after > that I get lost. Where are the variables being stored. Each separate invocation of 'factorial' has an associated value for a variable named 'n'. So on the 'Since 0 is 0' step, there are 4 invocations of 'factorial', one with n==0, one with n==1, etc. This is what 3.10 "Variables and parameters are local" intends to explain: | When you create a local variable inside a function, it only exists | inside the function, and you cannot use it outside. For example: | | def catTwice(part1, part2): | cat = part1 + part2 | printTwice(cat) | | This function takes two arguments, concatenates them, and then prints | the result twice. We can call the function with two strings: | | >>> chant1 = "Pie Jesu domine, " | >>> chant2 = "Dona eis requiem." | >>> catTwice(chant1, chant2) | Pie Jesu domine, Dona eis requiem. Pie Jesu domine, Dona eis requiem. | | When catTwice terminates, the variable cat is destroyed. If we try to | print it, we get an error: | | >>> print cat | NameError: cat | | Parameters are also local. For example, outside the function printTwice, | there is no such thing as bruce. If you try to use it, Python will | complain. So not only do catTwice and printTwice have different local names, each invocation of catTwice (or factorial) has its own values for local names. Jeff From _remove_jones57 at swbell.net Thu Sep 18 03:39:27 2003 From: _remove_jones57 at swbell.net (sj) Date: Thu, 18 Sep 2003 07:39:27 GMT Subject: Can Python Module Locate Itself? References: <VYR9b.1109$c17.866@newssvr24.news.prodigy.com> Message-ID: <Pidab.985$%X4.790@newssvr22.news.prodigy.com> Thanks all for the many useful suggestions. One of the reasons I placed the docs in comments is that I have a modified version of head which outputs the initial comment block of a file. Its smart enough to recognize c++, java, python and lisp commenting styles. On reflection I'm not sure this approach offers any advantage over the elegant and standard python doc string. Also it would be easy to to update the modified head program to look for any initial doc strings. From roberto at dealmeida.net Tue Sep 2 13:09:25 2003 From: roberto at dealmeida.net (Roberto A. F. De Almeida) Date: 2 Sep 2003 10:09:25 -0700 Subject: Which is the better way to parse this file? References: <10c662fe.0309020436.559d513d@posting.google.com> <au2dnSnl__hyPMmiU-KYgw@comcast.com> Message-ID: <10c662fe.0309020909.57817c13@posting.google.com> "Terry Reedy" <tjreedy at udel.edu> wrote in message news:<au2dnSnl__hyPMmiU-KYgw at comcast.com>... > I suspect that what you actually want to do is parse structures 'like' > the above, as defined be a grammar not shown ;-) Yes, you're right. :) The grammar is not complex, but I'm still struggling to process the result tree. > You did not specify whether you will get such files from an > uncontrolable external source or whether you control the input format. > If the later, there is no obvious reason for separate database, > sequence, and structure productions since all three result in > dictionaries with no functional difference. This is a Dataset Descriptor for the Data Access Protocol (http://www.unidata.ucar.edu/packages/dods/design/dap-rfc-html/), an API to access remote datasets. DAP servers describe their datasets using this grammar, and I'm developing a module to access DAP servers. > > I want to obtain a dictionary like this: > > > > >>> pprint.pprint(data) > > {'casts': {'experimenter': None, > > 'location': {'latitude': None, 'longitude': None}, > > 'time': None, > > 'xbt': {'depth': None, 'temperature': None}}, > > 'catalog_number': None} > > The values ('None') will be filled later. > > Using None as placeholders either tosses the type information or > requires that it be recorded elsewhere. Use the int and float type > objects instead. Note that standard Python cannot differentiate > between float and float64. Ok. One of the strong points of DAP is that data is retrieved only for your region/period of interest. I created a class and redefined __getitem__ so that data is only retrieved from the server when the object is sliced. >>> data = file("http://dods.gso.uri.edu/cgi-bin/nph-nc/data/fnoc1.nc") >>> print data.variables['lat'].shape (17,) >>> print data.variables['lat'][1:4] # only this subset is retrieved [ 47.5 45. 42.5 40. ] > I know nothing of SimpleParse (and therefore, of what would be > different). If the grammar is as simple as I infer from the sample -- > dataset and sequences containing sequences, structures, and types -- I > would reread about recursive-descent parsing and maybe try that. The > type_entry function would return a (name, typeobject) pair and the > structure, sequence, and database functions a (name, dict) pair. Yes, it's very simple. As you see, even a structure is identical to a sequence. The declarations are basically "types" or declarations containing "types". Do you think it can be done without 3rd party modules? > But as hinted above, I would think about simplifying the grammar > before worryinng about parsing. If you only have sequences of > sequences and type entries, parsing is trivial. I'll take a look in that. Thanks very much for the insights. Regards, Roberto From jjl at pobox.com Thu Sep 18 09:11:16 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Sep 2003 14:11:16 +0100 Subject: build python using mingw References: <bka775$3djvv$1@hades.rz.uni-saarland.de> <bkc3p9$b8c$1@ls219.htnet.hr> Message-ID: <87d6dy6y2z.fsf@pobox.com> "Marijan Tadin" <mtadin66 at yahoo.com> writes: > "Uwe Schmitt" <uwe.schmitt at procoders.net> wrote in message [...] > > Did anyone suceed in building Python + mingw ? [...] > AFAIK no, but some people are trying to do so. > Try Google with: > > build mingw group:comp.lang.python.* But don't let that put you off doing it yourself: IIRC, it's been on Gerhard's list for a long while, but he hasn't had sufficient 'round tuits' to finish it (assuming I recall correctly that it *was* Gerhard Haring). John From qual at tiscali.de Fri Sep 12 09:09:16 2003 From: qual at tiscali.de (Uwe Hoffmann) Date: Fri, 12 Sep 2003 15:09:16 +0200 Subject: looking for MOP documentation In-Reply-To: <oprvdsg7tl5j9jb9@news.tiscali.dk> References: <oprvdsg7tl5j9jb9@news.tiscali.dk> Message-ID: <bjsg2v$214s$1@ulysses.news.tiscali.de> kasper graversen wrote: > hello there. > > I've been searching the web (including the www.python.org :) but in vain > of finding recent documentation for the python MOP. I see some > information on python 1.5---is this the best and still valid information > today? > > sincerely > \kasper > http://www.python.org/2.2.3/descrintro.html#metaclasses http://www-106.ibm.com/developerworks/library/l-pymeta2 From zsh-users-help at sunsite.dk Tue Sep 2 11:45:09 2003 From: zsh-users-help at sunsite.dk (zsh-users-help at sunsite.dk) Date: 2 Sep 2003 15:45:09 -0000 Subject: ezmlm response Message-ID: <1062517509.3004.ezmlm@sunsite.dk> Hi! This is the ezmlm program. I'm managing the zsh-users at sunsite.dk mailing list. Acknowledgment: The address python-list at python.org was not on the zsh-users mailing list when I received your request and is not a subscriber of this list. If you unsubscribe, but continue to receive mail, you're subscribed under a different address than you currently use. Please look at the header for: 'Return-Path: <zsh-users-return-1234-user=host.dom at sunsite.dk>' The unsubscribe address for this user would be: 'zsh-users-unsubscribe-user=host.dom at sunsite.dk'. Just mail to that address, substituting user=host.dom for the real values, reply to the confirmation request, and you should receive a message that you're off the list. For some mail programs, you need to make the headers visible to see the return path: For Eudora 4.0, click on the "Blah blah ..." button. For PMMail, click on "Window->Show entire message/header". If this still doesn't work, I'm sorry to say that I can't help you. Please FORWARD a list message together with a note about what you're trying to achieve and a list of addresses that you might be subscribed under to my owner: zsh-users-owner at sunsite.dk who will take care of it. My owner is a little bit slower than I am, so please be patient. --- Administrative commands for the zsh-users list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: <zsh-users-subscribe at sunsite.dk> To remove your address from the list, send a message to: <zsh-users-unsubscribe at sunsite.dk> Send mail to the following for info and FAQ for this list: <zsh-users-info at sunsite.dk> <zsh-users-faq at sunsite.dk> Similar addresses exist for the digest list: <zsh-users-digest-subscribe at sunsite.dk> <zsh-users-digest-unsubscribe at sunsite.dk> To get messages 123 through 145 (a maximum of 100 per request), mail: <zsh-users-get.123_145 at sunsite.dk> To get an index with subject and author for messages 123-456 , mail: <zsh-users-index.123_456 at sunsite.dk> They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: <zsh-users-thread.12345 at sunsite.dk> The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: <zsh-users-subscribe-john=host.domain at sunsite.dk> To stop subscription for this address, mail: <zsh-users-unsubscribe-john=host.domain at sunsite.dk> In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at zsh-users-owner at sunsite.dk. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: <skip at mojam.com> Received: (qmail 2997 invoked from network); 2 Sep 2003 15:45:08 -0000 Received: from localhost (HELO sunsite.dk) (127.0.0.1) by localhost with SMTP; 2 Sep 2003 15:45:08 -0000 X-MessageWall-Score: 0 (sunsite.dk) Received: from [199.249.165.175] by sunsite.dk (MessageWall 1.0.8) with SMTP; 2 Sep 2003 15:45:8 -0000 Received: from montanaro.dyndns.org (titan.itcs.northwestern.edu [129.105.214.230]) by manatee.mojam.com (8.11.6/8.11.6) with ESMTP id h82Fj6M29955 for <zsh-users-uc.1062283803.okifnhokaldgjdaajooj-python-list=python.org at sunsite.dk>; Tue, 2 Sep 2003 10:45:07 -0500 Received: from montanaro.dyndns.org (localhost [127.0.0.1]) by montanaro.dyndns.org (8.12.9/8.12.2) with ESMTP id h82Fj7Gp013135 for <zsh-users-uc.1062283803.okifnhokaldgjdaajooj-python-list=python.org at sunsite.dk>; Tue, 2 Sep 2003 10:45:08 -0500 (CDT) Received: by montanaro.dyndns.org (8.12.9/8.12.2/Submit) id h82Fj7ZW013132; Tue, 2 Sep 2003 10:45:07 -0500 (CDT) From: Skip Montanaro <skip at pobox.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <16212.47875.511755.34065 at montanaro.dyndns.org> Date: Tue, 2 Sep 2003 10:45:07 -0500 To: zsh-users-uc.1062283803.okifnhokaldgjdaajooj-python-list=python.org at sunsite.dk Subject: Re: confirm unsubscribe from zsh-users at sunsite.dk In-Reply-To: <1062283803.7480.ezmlm at sunsite.dk> References: <1062283803.7480.ezmlm at sunsite.dk> X-Mailer: VM 7.14 under 21.5 (beta9) "brussels sprouts" XEmacs Lucid Reply-To: skip at pobox.com From hanzspam at yahoo.com.au Wed Sep 24 06:38:11 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 24 Sep 2003 03:38:11 -0700 Subject: Pre-PEP: reverse iteration methods References: <HA5cb.185$kD3.168@nwrdny03.gnilink.net> <f4b2nv8vs81v6egonckq7935jmh6a8gku6@4ax.com> Message-ID: <840592e1.0309240238.33c0a9@posting.google.com> Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:<f4b2nv8vs81v6egonckq7935jmh6a8gku6 at 4ax.com>... > >* Should enumerate() be included? It would only provide reverse iteration > > whenever the underlying sequence supported it. > > Why not... > > for i, j in enumerate (listname.iter_backwards ()) : > > in other words, as enumerate can handle the already-reversed > sequence/iteration, I don't see the point. That's not the same: >>> list(enumerate([10,11,12])) [(0, 10), (1, 11), (2, 12)] >>> list(enumerate([10,11,12].riter())) [(0, 12), (1, 11), (2, 10)] >>> list(enumerate([10,11,12]).riter()) [(2, 12), (1, 11), (0, 10)] Indices would also be reversed. From john at rygannon.com Mon Sep 15 13:33:02 2003 From: john at rygannon.com (John Dean) Date: Mon, 15 Sep 2003 17:33:02 GMT Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) Message-ID: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> Hi I would like to announce, for real this time, the release of BlackAdder V1.0.0. We have just finished our weekly conference during which I was give specific instructions by Shawn Gordon to make this announcement I have uploaded the demos to http://www.rygannon.com and to http://www.totalrekall.co.uk For all those who have already bought the beta release if you visit your download basket at http://www.thekompany.com you will find your copy of BA V1.0.0 ready and waiting For those who would like to buy a copy of BA V1.0.0 you too can visit http://www.thekompany.com/products/blackadder What is Blackadder? ----------------------------- BlackAdder is an application development environment that allows professional and hobbyist programmers alike to produce complex applications for the Windows and Linux platforms. BlackAdder brings together the Python programming language, the Ruby development language (Ruby is temporarily removed until the Qt bindings are updated to Qt3, currently in progress), the Qt graphical user interface (GUI) toolkit, ODBC database connectivity and an Integrated Development Environment (IDE) that includes an editor, a GUI designer, a debugger and an interactive Python interpreter. (A Ruby interpreter, debugger and ODBC support for Ruby are not yet available.) BlackAdder gives the programmer, in a single package, all they need to develop sophisticated applications. -- Best Regards John From joshway_without_spam at myway.com Mon Sep 8 17:46:47 2003 From: joshway_without_spam at myway.com (JCM) Date: Mon, 8 Sep 2003 21:46:47 +0000 (UTC) Subject: exec code with timeout? References: <Xns93EFD117DA30FOKB@130.133.1.4> Message-ID: <bjitc6$6s1$1@fred.mathworks.com> "OKB (not okblacke)" <BrenBarn at aol.com> wrote: > I am fiddling around with a Python-based MUD which allows users to > code MUD objects in Python. This code is executed from within the > server code with "exec". However, sometimes errors in user code can > result in infinite loops, which cause the MUD to hang. I am wondering > if there is a way to put a timeout on the exec, so that it returns > control to the main program if the user code doesn't return within a > certain amount of time. We've done exactly this for our own MUD project :) The way we got around the infinite loop problem was to have the main Python thread be the one that runs all unknown MUD-code. You can use signals (on unix) to raise an exception in the main thread. I don't remember offhand what function we used--maybe os.kill? From Scott.Daniels at Acm.Org Mon Sep 8 13:03:39 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 08 Sep 2003 10:03:39 -0700 Subject: CSV Module questions In-Reply-To: <mailman.1062980233.23100.python-list@python.org> References: <mailman.1062980233.23100.python-list@python.org> Message-ID: <3f5cb668$1@nntp0.pdx.net> John D. wrote: > I'm trying to understand how to use the "csv" module.... > Example (from the docs): > # Just some stupid dictionary with key same as value. > someiterable = {'john d': 'john d', 'fred': 'fred'} > > # make the writer. > writer = csv.writer(file("some.csv", "w")) > for row in someiterable: for row in someiterable.iteritems(): > writer.writerow(row) I suspect the problem is that you misunderstand dictionary iteration. Examine and understand: for row in someiterable: print repr(row) for row in someiterable.iteritems(): print repr(row) By the way, just use .items(), not .iteritems() if you have an older python (before 2.2, I believe). -Scott David Daniels Scott.Daniels at Acm.Org From dakidd at sonic.net Thu Sep 25 17:21:06 2003 From: dakidd at sonic.net (Don Bruder) Date: Thu, 25 Sep 2003 21:21:06 GMT Subject: Another Python rookie trying to port to C/C++ question. References: <GSGcb.24394$dk4.776543@typhoon.sonic.net> <bkvklh$e2i$02$1@news.t-online.com> Message-ID: <6%Icb.24427$dk4.777026@typhoon.sonic.net> In article <bkvklh$e2i$02$1 at news.t-online.com>, Peter Otten <__peter__ at web.de> wrote: > Don Bruder wrote: > > > A week or two ago, I asked here about porting Python to C. Got some good > > answers (Note 1) but now I've got another question. Actually, more a > > request for clarification of a topic that both the Python tutorial and > > docs leave a touch murky to my understanding. > > > > Dictionaries/"dict" types... > > As you seem to feel at home with C, you could have a look into > Objects/dictobject.c and Include/dictobject.h of the source distribution. I may just go poking around there for more details. Someone (via email) suggests that dicts are "supposed to be" (my synopsis, not his words) a bit "murky", because all that's supposed to be relevant is stuffing things into them, and pulling things out. That's fine, completely admirable, and fully acceptable. *IF* You're working directly in Python. I'm not. I'm working in a combination of C and C++, attempting to duplicate the functionality of a program originally written in Python. As such, the details *MUST* get clear if I'm to create equivalent functionality. If only because I need to read data that was written (presumably...) by a Python program. Hence, it becomes neccesary to get down "in the muck" and actually know what's going on behind the nice, tidy "dict.whosit.get()" (or whatever other operators might be involved) interface that Python provides. > > > Which part of "I don't care how good, bad, or indifferent Python is > > compared to C/C++, or any other language. I want this Python code to be > > written in C/C++, end of discussion." wasn't clear enough for those of > > Smart people use efficient tools and build on existing libraries. There's a statement that needed saying.... Not... > If you are > serious about the C++ part of your subject line, the Standard library aka > STL has a map template that resembles Python's dict and might enhance both > development and execution speed. I'm *REASONABLY* serious. This port started life as a "Do you really know as much about C++ as you think you do? Prove it! Take this Python program and make it C++!" sort of "mid-term" test in my self-taught C++ course. It's rapidly degenerating (due to some technicalities of C++ that I've never before encountered, and therefore had no expectation of trouble from) into "Let's just get the damn thing working in straight C, then worry about trying to turn it into C++ later." > > Off topic (or not): > A single person can start a discussion but not limit it, I think that's a > feature of newsgroups rather than an annoyance. Perhaps, and perhaps not. Guess it depends on your perspective. Having a stream of insult and invective dumped into your mailbox because you've made it plain that you don't consider somebody's "pet" language the be-all and end-all of computer programming is hardly what I'd call a "feature"... Be that as it may, fortunately I have a thick enough hide to figuratively "flip off" the jerk that was involved, and go on with life knowing full well that in at least one respect, I'm so far superior to him that words can't describe the gulf between us. Doesn't mean I'm not going to mention that I think he's a hopeless putz, but I'm sure not going to let it get me down to the point of giving up. -- Don Bruder - dakidd at sonic.net <--- Preferred Email - SpamAssassinated. Hate SPAM? See <http://www.spamassassin.org> for some seriously great info. I will choose a path that's clear: I will choose Free Will! - N. Peart Fly trap info pages: <http://www.sonic.net/~dakidd/Horses/FlyTrap/index.html> From andy at wild-flower.co.uk Wed Sep 17 15:40:06 2003 From: andy at wild-flower.co.uk (Andy Jewell) Date: Wed, 17 Sep 2003 20:40:06 +0100 Subject: Money data type In-Reply-To: <A128D751272CD411BC9200508BC2194D03382F8D@escpl.tcp.com.ar> References: <A128D751272CD411BC9200508BC2194D03382F8D@escpl.tcp.com.ar> Message-ID: <200309172039.41526.andy@wild-flower.co.uk> On Wednesday 17 Sep 2003 7:28 pm, Batista, Facundo wrote: > Can't find it. > > I mean something like: > >> m1 = Money(decimal=2) > >> m2 = Money(decimal=2) > >> m1.value = 3.20 > >> m2.value = 2.15 > >> print m1 + m2 > > 5.35 > > 5.35! Not 5.3500000000000001 neither 5.34999999999999999999. > > I think this is not a rare thing, but I can't find it in the standar > library neither the package index. > > Thanks! > > . Facundo Facundo, When you just print a raw float, it will be printed to its most accurate decimal representation. If you need /aritrary precision/ you are probably best off using long-integers, multiplying your result, say by 100 (e.g. for two decimal place precision) and then dividing down again when you need to print. Actually, though, I think what you need is: -----8<----- >>> m1=3.2 >>> m2=2.15 >>> print "%4.2f" % (m1+m2) 5.35 >>> print m1+m2 5.35 >>> # oops... lets try someting a little more difficult >>> m3=100.0/3 >>> m3 33.333333333333336 >>> print "%4.2f" % m3 33.33 >>> m3 33.333333333333336 >>> print "%4.2f" % (m3+m2) 35.48 >>> m3+m2 35.483333333333334 >>> -----8<----- hth, -andyj From __peter__ at web.de Thu Sep 25 16:52:53 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2003 22:52:53 +0200 Subject: Another Python rookie trying to port to C/C++ question. References: <GSGcb.24394$dk4.776543@typhoon.sonic.net> Message-ID: <bkvklh$e2i$02$1@news.t-online.com> Don Bruder wrote: > A week or two ago, I asked here about porting Python to C. Got some good > answers (Note 1) but now I've got another question. Actually, more a > request for clarification of a topic that both the Python tutorial and > docs leave a touch murky to my understanding. > > Dictionaries/"dict" types... As you seem to feel at home with C, you could have a look into Objects/dictobject.c and Include/dictobject.h of the source distribution. > Which part of "I don't care how good, bad, or indifferent Python is > compared to C/C++, or any other language. I want this Python code to be > written in C/C++, end of discussion." wasn't clear enough for those of Smart people use efficient tools and build on existing libraries. If you are serious about the C++ part of your subject line, the Standard library aka STL has a map template that resembles Python's dict and might enhance both development and execution speed. Off topic (or not): A single person can start a discussion but not limit it, I think that's a feature of newsgroups rather than an annoyance. Peter From __peter__ at web.de Tue Sep 30 16:07:26 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Sep 2003 22:07:26 +0200 Subject: printing to files in python References: <mailman.1064946050.8907.python-list@python.org> Message-ID: <blcnt0$mv$02$1@news.t-online.com> Matthew Wilson wrote: > Hi- > > I want to print stuff like: > >>>> "d1: %s, probability: %0.2f" % (d1, prob) > > to a file, but when I do: > >>>> str = "d1: %s, probability: %0.2f" % (d1, prob) >>>> outfile = open("out.txt", "w") >>>> outfile.write(str) > > I get errors. What am I missing? Apart from using str as a variable name, which is bad style, there is nothing wrong with the code you have posted. It would help, if you would also post the values of d1 and prob and cut and paste the actual traceback. Using the insufficient information you provide, prob could be an incompatible type, e. g. a string >>> "%f" % "123.4" Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: float argument required or you are ot allowed to write into the specified file: >>> file("out.txt", "w") Traceback (most recent call last): File "<stdin>", line 1, in ? IOError: [Errno 13] Permission denied: 'out.txt' >>> Or something completely different... Peter From mcherm at mcherm.com Tue Sep 23 14:31:03 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 23 Sep 2003 11:31:03 -0700 Subject: Thoughts on PEP284 Message-ID: <1064341863.3f709167864a8@mcherm.com> Stephen Horne writes: > True, it is mostly just an alternative notation for range or xrange. > But the integer for loops thing is something that never seems to go > away. PEP284 itself quotes four previous PEPs on broadly the same > issue. I am of the opinion that the introduction of enumerate() (in 2.3) will go a long ways toward reducing the desire for better integer loop syntax. I'm sure it will never go away completely, but if the demand seems to die down after a year or so, then I'd guess it was due to enumerate(). -- Michael Chermside From hpk at trillke.net Sun Sep 7 19:44:02 2003 From: hpk at trillke.net (holger krekel) Date: Mon, 8 Sep 2003 01:44:02 +0200 Subject: ANN: PyPy "Berlin" sprint (29th Sep - 4th Oct 2003) Message-ID: <20030908014402.F22698@prim.han.de> hello python developers, the fourth PyPy coding sprint will take place in Berlin (Germany) from (morning of) 29th of September to (evening of) 4th of October 2003. All Python developers are welcome to join the sprint. See below for participation details. What is PyPy? ------------- PyPy is a remimplementation of Python in the Python language itself. Simplicity and flexibilty are the foremost goals. With PyPy we want it to be easy to extend the language or generate a more minimal language implementation. One key technique to making this feasible is to specialize our abstract/general PyPy-Python implementation into native code (e.g. C-code). Eventually the concepts of PSYCO and Stackless are to be integrated into PyPy. There is, of course, much more to it so feel free to consult some documents especially our Oscon-2003 paper on this page: http://codespeak.net/pypy/index.cgi?doc We know that many areas and issues are still somewhat vague although PyPy can already run many python programs [*]. Fortunately, Python is pretty tolerant about expressing ideas in vague ways. After all, hacking at PyPy aims (and already proved!) to preserve the fun of hacking in Python. History, status and Berlin goals -------------------------------- The project started in Jan/Feb 2003 with an initiative from Christian Tismer, Holger Krekel and Armin Rigo. During the course many more developers joined our sprints and there are now between 5 and 15 people involved in developing PyPy. The three sprints resulted in a fully working interpreter, some development infrastructure and the "standard object space" which is an abstraction for operations on standard (CPython) objects. There is no public release yet, you more or less have to install a subversion-client and checkout the trunk. Here is our 'howtosvn' which contains up-to-date clients for multiple platforms along with some instructions how to get started: http://codespeak.net/pypy/index.cgi?doc/devel/howtosvn.html Main goals for the Berlin sprint are - integration/enhancement of a Python parser and the compiler package - generating native code from our Python interpreter/types implementations - enhancing/correcting/completing what we have (various tasks) How to participate in Berlin (29th of Sept. to 4th of October) -------------------------------------------------------------- If you are interested to participate please subscribe at our sprint organization list http://codespeak.net/mailman/pypy-sprint and please list yourself at http://codespeak.net/moin/pypy/moin.cgi/SprintAttendants so that we can organize accomodation and arrange details. Costs should be pretty low (except from travelling costs, of course). Currently nine people are scheduled to come. Btw, the sprint starts early on the 29th of september so it's best to arrive on sunday, 28th. Also we probably want to have one day off during the sprint week to do some sight (or cafe+pub) seeing. Actually it's much better to participate the whole week to better get into it. cheers, holger [*] and currently only 20-40 thousand times slower than CPython! which clearly shows that we are successfully follow the "premature optimization is the root of all evil" maxime. From DavidA at ActiveState.com Wed Sep 24 19:33:56 2003 From: DavidA at ActiveState.com (David Ascher) Date: Wed, 24 Sep 2003 16:33:56 -0700 Subject: Announcement: ActiveState acquired by Sophos In-Reply-To: <lIydnRkR4Ilwm--iU-KYgw@comcast.com> References: <mailman.1064426135.17091.python-list@python.org> <lIydnRkR4Ilwm--iU-KYgw@comcast.com> Message-ID: <3F7229E4.5030902@ActiveState.com> Terry Reedy wrote: > Do you have an ETA for Active Python 2.3? A few weeks for ActivePython 2.3.1 -- we have a few other releases to worry about, but now that Komodo 2.5 is out the door, it's way up there on the priority queue. Cheers, --david ascher From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Tue Sep 30 03:37:49 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Tue, 30 Sep 2003 11:37:49 +0400 Subject: meta classes In-Reply-To: <oprwajrpt3g9zfwx@news.tiscali.dk> References: <oprwajrpt3g9zfwx@news.tiscali.dk> Message-ID: <blbbsc$2vvu$1@news.peterlink.ru> Carlo v. Dango wrote: > hello there > > I'd like to take control over the method dispatching of every subclass > of a given python class. Currently I've redefined __getattribute__() so > i can find the right instance/method to dispatch to. This works fine, > albeit it may seem a bit hackish. Further I want to control the actual > dispatching, so that I can execute methods before, after or instead of > the actual method. I would prefer to do this with the least modification > of the source due to debug'ing issues. My best idea so far is to rename > every method who subclass the magic class X and then create new methods > in place of the renamed ones, which looks up in a list to execute > "before-methods", then execute the renamed method etc.. > > Only I don't know how to do this. I've found some MOP code which was > designed for python old-style objects... but this is not what I want. > Can anyone kindly give me some pointers for help or some actual code? > > many thanks in advance.. > > > --- > Really simple example: class Hooker(object): class __metaclass__(type): def __new__(cls, name, bases, members): def make_wrapper(f): def wrapper(self): print "before" f(self) print "after" return wrapper new_members = {} for n, f in members.iteritems(): if not n.startswith('__'): new_members[n] = make_wrapper(f) else: new_members[n] = f return type.__new__(cls, name, bases, new_members) class Child(Hooker): def foo(self): print "Child.foo" c = Child() c.foo() hth, anton. From syver at inout.no Mon Sep 22 05:51:46 2003 From: syver at inout.no (Syver Enstad) Date: 22 Sep 2003 11:51:46 +0200 Subject: thread question References: <bkmdp9$gvr$1@nets3.rz.RWTH-Aachen.DE> Message-ID: <uwuc12lsd.fsf@inout.no> Rolf Wester <wester at ilt.fraunhofer.de> writes: > Hi, > > I have an application that starts a second thread, that receives > messages via a socket-server and puts that messages into a queue. The > main thread is polling that queue for new messages. My problem is that > the main thread takes to much of the time polling the empty queue > while the socket-server thread doesn't get enough time for receiving > the messages. Is it possible to force the main threat to sleep for a > certain > amount of time or give the socket-server thread a higher priority? > Thanks in advance. The good answer to your question: Use a Queue.Queue instance as your queue. The queue instance has methods that block if the queue is empty. The direct answer to your question: import time time.sleep(5) # sleeps 5 seconds From fredrik at pythonware.com Fri Sep 19 08:34:16 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 Sep 2003 14:34:16 +0200 Subject: utf-8 encoding issue References: <petitmermet-D88C6A.13411819092003@pfaff2-rz-fast.ethz.ch> Message-ID: <bket4d$ngn$1@sea.gmane.org> Marc Petitmermet wrote: > In a web form, the user enters "?ttinger" and wants to search with this > search string. My idea is now to convert the search string (which also > could be e.g. some cyrillic text) into unicode and then to utf-8: > > unicode(search_string).encode('utf-8') > > This gives me the utf-8 encoded version of the string but not yet in the > correct representation. How can I get the correct one (is this the hex > version? I don't know the correct terminology.)? > > In short: how do I e.g. convert a sting containing a "?" into a string > containing a "%Ö"? that's not UTF-8, that's HTML/XML-style charrefs. if mysql translates the charref's to unicode characters, you can simply use: s = u.encode("ascii", "xmlcharrefreplace") where "u" is a unicode string. if you've stored charrefs as is in the database, you're in for some serious trouble. assuming that all charrefs are hexadecimal charrefs, you can use something like: def fixup(m): return "&#" + hex(int(m.group(1)))[1:] s = re.sub("&#(\d+)", fixup, u.encode("ascii", "xmlcharrefreplace")) to map all non-ASCII characters to charrefs, and then translate all charrefs to hexadecimal charrefs. decoding the charrefs *before* you add the strings to the database is a better idea, though. </F> From sylphaleya at hta.fhz.ch Tue Sep 9 10:38:17 2003 From: sylphaleya at hta.fhz.ch (Manuel Huesser) Date: Tue, 9 Sep 2003 16:38:17 +0200 Subject: minidom sample code (OT) References: <59e5b87.0309081251.32b31261@posting.google.com> <bjj39i$f6p$0@216.39.172.122> Message-ID: <20030909163817.50abac58.sylphaleya@hta.fhz.ch> >>> from xml.dom.minidom import getDOMImplementation It needs much more time to import this package than any other one. As much that it's perceptible compared to other packages. Because my main debugger is print i don't like if an application needs much more time. Is there a way around? Manuel From jjl at pobox.com Mon Sep 15 18:10:02 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Sep 2003 23:10:02 +0100 Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <oprvd7fyp7fhfgdd@news.chello.no> <mailman.1063381340.26766.python-list@python.org> <17d520f6.0309130704.7944c876@posting.google.com> <87znh89ufv.fsf@pobox.com> <slrnbm8l54.o3i.grey@dmiyu.org> <878yoqoudj.fsf@pobox.com> <slrnbmc97u.vpg.grey@dmiyu.org> Message-ID: <87vfrtd7ph.fsf@pobox.com> Steve Lamb <grey at despair.dmiyu.org> writes: > On 2003-09-15, John J. Lee <jjl at pobox.com> wrote: > > Steve Lamb <grey at despair.dmiyu.org> writes: > >> I run several GTK apps that don't touch Gnome: > >> Sylpheed-Claws > >> Pan > >> XChat > > >> GTK != GNOME. > > [...] > > > Yep: that's exactly what I don't understand! *Why* did you do that? > > What, run GTK apps that don't touch Gnome? Simple reason: Gnome > sucks. I run KDE. I wouldn't want to load the full gamut of gnome libs > but the GTK libs are ok. Sorry, misread that as saying you *wrote*, not *run*. John From newsgroups at jhrothjr.com Fri Sep 19 16:26:42 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 19 Sep 2003 16:26:42 -0400 Subject: How do I learn operator overriding? References: <mailman.1063995987.26144.python-list@python.org> <vmmn2u51gliad1@news.supernews.com> <3F6B6128.49680D2@alcyone.com> Message-ID: <vmmpkqp2f5oec2@news.supernews.com> "Erik Max Francis" <max at alcyone.com> wrote in message news:3F6B6128.49680D2 at alcyone.com... > John Roth wrote: > > > A new mass mailer worm hit the net at about 9:00 PM EST last night > > (at least, that's when I started getting the spam from it.) It seems > > to be > > using a really old hole in Windows, meaning that if you've kept up to > > date > > with your patches, you should be safe from infection. > > Being completely safe from infection doesn't mean that you won't get > hammered by the spam the worms generate. All you need to be is in the > address book of someone whose machine was compromised. (My machines > don't run Windows, so they certainly haven't bee compromised by a > Windows worm, but I'm seeing tremendous spam loads nevertheless.) I did say *infection*. John Roth > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE > / \ You and I / We've seen it all / Chasing our hearts' desire > \__/ The Russian and Florence, _Chess_ From aahz at pythoncraft.com Wed Sep 17 16:47:19 2003 From: aahz at pythoncraft.com (Aahz) Date: 17 Sep 2003 16:47:19 -0400 Subject: New style classes References: <3f68bf1b$0$42051$a1866201@newsreader.visi.com> <3F68C5C6.EEE50394@engcorp.com> Message-ID: <bkah8n$oc2$1@panix3.panix.com> In article <3F68C5C6.EEE50394 at engcorp.com>, Peter Hansen <peter at engcorp.com> wrote: >Grant Edwards wrote: >> >> Is it just me, or does the "new style american girlfriend" line >> from "Sixteen Candles" pop into anybody else's head when the >> see the phrase "new style classes" mentioned on a subject line? >> >> Ah. Just me? >> I was afraid of that. > >I treat the new style ones as objects. I like them better that way, >'cause the old ones weren't my type. I wish they all could be new-style objects... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From posman at eval.ca Mon Sep 15 12:03:46 2003 From: posman at eval.ca (Paul Osman) Date: Mon, 15 Sep 2003 12:03:46 -0400 (EDT) Subject: unique unions of several dict keys In-Reply-To: <59256.199.169.240.132.1063641087.squirrel@svr1.turboweb.net> References: <59256.199.169.240.132.1063641087.squirrel@svr1.turboweb.net> Message-ID: <Pine.LNX.4.53.0309151201090.32259@kernighan.eval.ca> On Mon, 15 Sep 2003 python at sarcastic-horse.com wrote: > Hi- > > > I have several different dictionaries. I want to make a unique list of > all the keys in all the dictionaries. What would be the best way of doing > that? > > > Thanks. > > well, I'm sure there's a number of ways, here's one: def unique(keys): unique = [] for i in keys: if i not in unique: unique.append(i) return unique a = {"name" : "paul", "age" : 22} b = {"name" : "paul", "location" : "toronto"} list = unique(a.keys() + b.keys()) print list I'm sure there's a better way, but you get the idea. play around with it. Cheers, -- Paul Osman posman at eval.ca http://perl.eval.ca "Idealists...foolish enough to throw caution to the winds...have advanced mankind and have enriched the world." - Emma Goldman From aahz at pythoncraft.com Wed Sep 10 11:41:30 2003 From: aahz at pythoncraft.com (Aahz) Date: 10 Sep 2003 11:41:30 -0400 Subject: FAQs in spanish References: <mailman.1063033454.25394.python-list@python.org> <bjmie1$67h$1@nsnmpen2-gest.nuria.telefonica-data.net> Message-ID: <bjngna$rdo$1@panix1.panix.com> In article <bjmie1$67h$1 at nsnmpen2-gest.nuria.telefonica-data.net>, =?ISO-8859-1?Q?Miguel_Hern=E1ndez_Martos?= <miguel.hernandez at icr-sa.com> wrote: >Batista, Facundo wrote: >> >> I searched for FAQs in spanish, and I didn?t found them. > >I think this is what you are looking for: >http://pyspanishdoc.sourceforge.net/ That doesn't appear to include the FAQs, particularly not the recently rewritten FAQs. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From corey.coughlin at attbi.com Fri Sep 12 13:54:09 2003 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 12 Sep 2003 10:54:09 -0700 Subject: dumb q: repeated inheritance in python? References: <a8623416.0309111319.14334945@posting.google.com> <Xns93F467BCD2CA5duncanrcpcouk@127.0.0.1> Message-ID: <a8623416.0309120954.7a7d3e01@posting.google.com> Thanks Duncan, that's exactly what I needed! I'm not very familiar with subclassing properties, I guess I'll play around with it and see if I can figure it out. But thanks again, it's great code! ------ Corey Duncan Booth <duncan at NOSPAMrcp.co.uk> wrote in message news:<Xns93F467BCD2CA5duncanrcpcouk at 127.0.0.1>... > corey.coughlin at attbi.com (Corey Coughlin) wrote in > news:a8623416.0309111319.14334945 at posting.google.com: > > > What I'd really like to do is inherit this same object > > twice, but the second time rename the objects so that I get 'name2' > > instead of 'name'. (And somehow rename the functions, and so on.) > > I'm not sure if I exactly understood what you want, but does this help? > I think you are asking for two properties that access differently named > attributes but perform the same type checking in each case. > > That sounds to me like you want a specialised property which can be done by > subclassing it: > > ---- begin test.py ---- > class Name(property): > def __init__(cls, attrname): > > def setnm(self, nm): > if isinstance(nm, str): > setattr(self, attrname, nm) > else: > raise TypeError("Name passed to %s isn't a string" % > self.__class__.__name__) > > def getnm(self): > return getattr(self, attrname) > > property.__init__(cls, getnm, setnm) > > > class TwoNamed(object): > def __init__(self, iname='', jname=''): > self.iname, self.jname = iname, jname > > name = Name('iname') > name2 = Name('jname') > > x = TwoNamed('ivalue', 'jvalue') > print "name, name2 =",x.name, x.name2 > > x.name = 'www' > x.name2 = 'xxx' > > print "name, name2 =",x.name, x.name2 > print "iname, jname =",x.iname, x.jname > > x.name = 42 # Blows up > print x.name # Never reached. > ----- end of test.py ---- From amundsen463 at yahoo.com Tue Sep 9 13:53:22 2003 From: amundsen463 at yahoo.com (Craig Amundsen) Date: 9 Sep 2003 10:53:22 -0700 Subject: MySQL-Python on OS X Message-ID: <b2fb3fa7.0309090953.7b277d7a@posting.google.com> Hi - I'm trying to build the MySQL-Python 0.9.2 module on OS X 10.2.6. I have installed the Fink version off MySQL (3.23.56-1) and the Fink version of Python (2.2.2). I have made the recommended changes to setup.py; I changed the mysqlclient = thread_safe_library and "mysqlclient_r" or "mysqlclient" line to mysqlclient = thread_safe_library and "mysqlclient" I changed thread_safe_library from YES to NO. In the darwin section I changed include_dirs.append('/sw/include') library_dirs.append('/sw/lib') to include_dirs.append('/sw/include/mysql') library_dirs.append('/sw/lib/mysql') When I run python setup.py build I get this error: line 1033, in gen_lib_options File "/sw/lib/python2.2/posixpath.py", line 65, in split i = p.rfind('/') + 1 AttributeError: 'int' object has no attribute 'rfind' It looks to me like p is supposed to be a string containing a path, but is instead an int. I have not in all my searching, found any mention of this build error. Does anyone have any hints on how to resolve this issue? TIA, - Craig From skip at pobox.com Mon Sep 29 17:05:40 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 29 Sep 2003 16:05:40 -0500 Subject: isNumber? check In-Reply-To: <16E3AA52-F2BE-11D7-9145-003065F081D2@cs.brown.edu> References: <20030929204143.GA8765@nl.linux.org> <16E3AA52-F2BE-11D7-9145-003065F081D2@cs.brown.edu> Message-ID: <16248.40612.944607.2651@montanaro.dyndns.org> >> if expr.strip("0123456789.e") == "": print "May be a number!" >> if expr.strip("0123456789") == "": print "Surely a number!" Rob> I don't like that solution for this particular project because, as Rob> you say yourself, if it says yes to the second question, it only Rob> *may* be a number. I want to know for sure. Expanding on my previous post, here are a couple *simple-minded* re's for matching ints and floats (really, fixed-point numbers) >>> import re >>> ipat = re.compile("([0-9]+)$") >>> fpat = re.compile("([0-9]+\.[0-9]*$)") >>> token = "123" >>> fpat.match(token) >>> print fpat.match(token) None >>> print ipat.match(token) <_sre.SRE_Match object at 0x40d6a0> >>> print ipat.match(token).group(1) 123 >>> token = "123.456" >>> print ipat.match(token) None >>> print fpat.match(token) <_sre.SRE_Match object at 0x487960> >>> print fpat.match(token).group(1) 123.456 Extension of this idea to useful definitions for your interpreter is left as an exercise for the reader. Skip From aleax at aleax.it Mon Sep 22 09:39:45 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 13:39:45 GMT Subject: pop3 email header classifier? References: <GmZAOKA6Uya$Ew2E@jessikat.fsnet.co.uk> Message-ID: <BYCbb.100868$hE5.3551705@news1.tin.it> <posted & mailed> Robin Becker wrote: > Hi, I'm getting vast numbers of fake upgrade emails containing some kind > of virus. My rather old client can be made to reject these based on some > patterns in the subject line. They're nearly all based on the word > 'New', 'Latest', 'Microsoft', 'Patch', 'Pack', ... etc etc. > > Is there a python tool that can be made to delete these from my POP3 > mail box rather than let my client reject? Quite a few seem to have > semi-valid return addresses so I get postmaster rejects from > xxx at microsoft.com etc. > > I know about spam-bayes etc, but these things are over 120k each and it > seems pretty pointless to download them (as well as taking about an > hour). I posted an "emergency script" to be used for the purpose -- it triggers SOLELY on mail size. I have now enhanced it with lots of options etc, but the basic idea remains that of size-only triggering -- risky but, it IS an emergency. BTW, the "postmaster rejects" are likely not connected to what you do with the "fake upgrade emails", alas -- rather, virus senders are now faking "From:" &c addresses, so everybody's getting lots of bounce msgs for mails they never sent. Alex From sperry at newcreations.us Sun Sep 28 20:16:34 2003 From: sperry at newcreations.us (Sperry Russ) Date: Sun, 28 Sep 2003 20:16:34 -0400 Subject: Home Environment Message-ID: <200309282016340839.000CF274@mail.blazingisp.net> Hello, I am a beginner in programming and to python. I am using it to learn programming. I am using Windows 2000 Pro. I installed Python 2.3.1 with the installer which installed it to: C:\Python23. When I run a script in Idle I get the following warning: Warning: HOME environment variable points to %USERPROFILE% but the path does not exist. What should I do to fix this? Thanks, Sperry -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20030928/fb5c6f11/attachment.html> From sholden at holdenweb.com Tue Sep 16 23:48:35 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 17 Sep 2003 03:48:35 GMT Subject: Duck Typing References: <221d8dbe.0309160101.4a09f2ad@posting.google.com> <mailman.1063720351.23661.python-list@python.org> <3gG9b.12137$3Y2.2543@news2.central.cox.net> <3F6732DB.F31A954E@engcorp.com> <DaH9b.12147$3Y2.9399@news2.central.cox.net> <3F6749B6.74601D54@engcorp.com> Message-ID: <nQQ9b.12808$3Y2.5792@news2.central.cox.net> "Peter Hansen" <peter at engcorp.com> wrote in message news:3F6749B6.74601D54 at engcorp.com... > Steve Holden wrote: > > > > "Peter Hansen" <peter at engcorp.com> wrote in message > > news:3F6732DB.F31A954E at engcorp.com... > > > Steve Holden wrote: > > > > > > > > exquacktly [ducks and runs] > > > ^^^^^ > > > > > > Steve, did you even _know_ you did this? You're sick! > > > > > > -Peter :-) > > > > Aah, I see, you think I'm stupid. > > No, I just knew Irmen was asleep at his keyboard. ;-) > > > Of course I knew - without the bracketed afterthought it would hardly have > > been worth posting. > > > > I'll send you a bill ;-) > > If you make it a twenty, would that be a "sawduck"? > You'll never beat me at this game. After all, I did write "Web Programming in Python" ;-) regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From pnu at ukfsn.org Thu Sep 25 11:25:18 2003 From: pnu at ukfsn.org (Peter Nuttall) Date: Thu, 25 Sep 2003 16:25:18 +0100 Subject: send email In-Reply-To: <pan.2003.09.25.13.51.03.520871@riquito.matrix> References: <D44DA9C0-EF06-11D7-8841-000393C2D67E@colorstudy.com> <mailman.1064486793.21084.python-list@python.org> <pan.2003.09.25.13.51.03.520871@riquito.matrix> Message-ID: <200309251625.19001.pnu@ukfsn.org> On Thursday 25 Sep 2003 2:51 pm, Riccardo Attilio Galli wrote: > On Thu, 25 Sep 2003 11:46:16 +0100, Peter Nuttall wrote: > > here is a program to send emails with python. It was writien quickly so > > it is not perfect. > > [SNIP] > > > > if anyone has any comments I would like to see them. <snip> > > peter, your program write 'e-mail' absolutely not rfc2822 compliant. <snip> > Ciao, > Riccardo Yeah, I thought It was not compliant. Thanks for the weblink. I have changed it based on the standard and what you said, but I have a few questions: 1. message-ID: I have written an few lines of code that have the date and time on one side of a @ and the computer's name of the other. is that OK? 2. is there a better way to make the date string that the loop that I have? 3. line length: Is having it set to 78 ok or is that 2 over the limit? Here is the new code: import smtplib from time import gmtime, strftime, localtime winth_of_email=78 message = '' print 'type message here:' end = 0 while end == 0: msg=raw_input() if msg=='': if new_line_1=='1': print 'end of message' end=1 else: new_line_1='1' message = message + '\r\n' else: new_line_1='' new_line_2='' lent=len(msg)/winth_of_email x=0 while x <= lent: chop=(x+1) * winth_of_email+x msg = msg[:chop] + '\r\n' + msg[chop:] x+=1 message = message +'\r\n'+ msg #adds headers to email fromaddr=raw_input('what is the from address ') toaddrs=raw_input('what is the to address ') subject=raw_input('what is the subject ') sever=raw_input('what is the smtp sever you are using ') timesend=strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) #msg-id maker #change lupin to the name of your computer setime=localtime() x=0 msg_id='' while x<5: msg_id=msg_id+str(setime[x]) x=x+1 msg_id = msg_id + '@lupin' finalmessage = 'From: '+fromaddr +'\r\n'+ 'To: '+toaddrs finalmessage = finalmessage +'\r\n'+ 'Subject: '+ subject +'\r\n' + 'Date: ' + timesend finalmessage = finalmessage + '\r\n' +'Message-ID: ' + msg_id + '\r\n' + '\r \n' +message print "Message length is " + `len(finalmessage)` print #code for sending email server = smtplib.SMTP(sever) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, finalmessage) server.quit() Thanks again Peter -- Someone esle can help you better than I can. Every time I think that perhaps we are an advanced race, I turn around and read ramblings on Slashdot, and realize I was wrong. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 13:40:13 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 18:40:13 +0100 Subject: Try/except vs. if/else References: <le2rmvser1i3e9gptd2ihq1d7p21r7el62@4ax.com> <bkk4h1$9ke$06$1@news.t-online.com> <mailman.1064154389.29357.python-list@python.org> <bkmd4q$t13$05$1@news.t-online.com> <DUCbb.100826$hE5.3550910@news1.tin.it> <mailman.1064245938.12315.python-list@python.org> <nA2dnd3VipjjEfKiXTWJlg@comcast.com> <3F70598E.8020500@bu.edu> <mailman.1064330017.10730.python-list@python.org> Message-ID: <95v0nvou5d26oe6ug22q0jftih0080fva8@4ax.com> On Tue, 23 Sep 2003 11:10:49 -0400, Shu-Hsien Sheu <sheu at bu.edu> wrote: >Hi, > >In my understanding, using try/except rather than if/else is more >pythonic. When to use an exception can be a difficult issue in any language. A common suggestion as to when to use them is 'only for errors' - but what exactly is an error? Really, its just a special case - and if you are handling that special case it isn't an error any more. For example, if your program runs out of memory and cannot complete a requested task, as long as it handles that special case by reporting that it run out of memory and not by crashing or whatever, it is probably doing what any decent requirements document would specify - in case of insufficient memory, report the problem and cleanly abort the tasks that cannot be completed without terminating or crashing. In terms of the requirements, no error has occurred - a special case has simply been handled exactly as per the requirements. Actually, I'm not really convinced by that argument either. I think I first read it in Stroustrup, though I can't be bothered checking ATM. Anyway, what I'm trying to express is that when to use an exception is more about intuitions and common sense than hard-and-fast rules. The nearest thing to a hard-and-fast rule, though, is that if you throw an exception the condition should really be exceptional - a special case as opposed to a normal case. try/except is not just an alternative to if/else, and neither is it an alternative to 'break' in loops (though Icon programmers may be tempted to use it that way). One major benefit of exceptions is that you don't have to keep checking 'has any error occured' in multiple if statements in a function. Any function that does anything even remotely complicated will have many different possible error conditions. Making sure that normal-case code is not run when a failure has already occurred can be a major headache. Enough of a headache that in C, many people think error handling is the only case where a 'goto' is acceptable (so an error can trigger a goto straight to the cleanup code at the end of a function, keeping the rest of the function clean). There are other issues, of course - exceptions allow your functions to cope properly with errors that you don't even know about in functions that you call, for instance. But basically, if you handle exceptional conditions by raising exceptions, your logic will get much clearer as for the most part it only has to deal with the normal case. The exceptional cases get handled by the exception handlers. But if you use try/except as an alternative to if/else, people who have to read your code may well take up dark magics purely so they can curse you more effectively ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From eppstein at ics.uci.edu Mon Sep 22 13:57:52 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 22 Sep 2003 10:57:52 -0700 Subject: Playing with dictionaries References: <10c662fe.0309220907.a84bea5@posting.google.com> Message-ID: <eppstein-2C8472.10575222092003@news.service.uci.edu> In article <10c662fe.0309220907.a84bea5 at posting.google.com>, roberto at dealmeida.net (Roberto A. F. De Almeida) wrote: > Suppose I have a dictionary containg nested dictionaries. Something > like this: > > >>> pprint.pprint(dataset) > {'casts': {'experimenter': None, > 'location': {'latitude': None, > 'longitude': None}, > 'time': None, > 'xbt': {'depth': None, > 'temperature': None}}, > 'catalog_number': None, > 'z': {'array': {'z': None}, > 'maps': {'lat': None, > 'lon': None}}} > > I want to assign to the values in the dictionary the hierarchy of keys > to it. For example: > > >>> dataset['casts']['experimenter'] = 'casts.experimenter' > >>> dataset['z']['array']['z'] = 'z.array.z' > > Of course I would like to do this automatically, independent of the > structure of the dictionary. Is there an easy way to do it? def makehierarchy(dataset,prefix=''): for key in dataset: if dataset[key] is None: dataset[key] = prefix + key elif isinstance(dataset[key], dict): makehierarchy(dataset[key], prefix + key + ".") else: raise ValueError, "Unexpected data type in makehierarchy" >>> makehierarchy(dataset,'dataset') >>> pprint.pprint(dataset) {'casts': {'experimenter': 'casts.experimenter', 'location': {'latitude': 'casts.location.latitude', 'longitude': 'casts.location.longitude'}, 'time': 'casts.time', 'xbt': {'depth': 'casts.xbt.depth', 'temperature': 'casts.xbt.temperature'}}, 'catalog_number': 'catalog_number', 'z': {'array': {'z': 'z.array.z'}, 'maps': {'lat': 'z.maps.lat', 'lon': 'z.maps.lon'}}} -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From mfranklin1 at gatwick.westerngeco.slb.com Tue Sep 30 15:43:17 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 30 Sep 2003 20:43:17 +0100 Subject: [PMW] Rename a notebook's page - how? In-Reply-To: <3f79b621@news.swissonline.ch> References: <3f798986@news.swissonline.ch> <mailman.1064934294.5084.python-list@python.org> <3f79b621@news.swissonline.ch> Message-ID: <1064950996.1139.15.camel@m-franklin> On Tue, 2003-09-30 at 17:59, F. GEIGER wrote: > Thank you Martin, > > but I've still troubles, because the tab has the new name now, but the page > is in PMW still known with the old name. > > I see this because I've registered for the raisecommand event: > > def _onSelect_(self, pageName): > Proxy.DataProxy().containerSelect(pageName) > return > > And here pageName is the old name despite the fact that the new name is > displayed on the tab. > > Kind regards > Franz GEIGER > > > "Martin Franklin" <mfranklin1 at gatwick.westerngeco.slb.com> schrieb im > Newsbeitrag news:mailman.1064934294.5084.python-list at python.org... > > On Tue, 2003-09-30 at 14:49, F. GEIGER wrote: > > > Hi again, > > > > > > I'd like to rename a page of a notebook. Deleting the page and adding a > new > > > one is not really an option, because the page is filled with other > controls > > > already. So I looked into Pmw.Notebook. There are quite a few lists and > > > dicts which were to be changed and I wasn't successful in the first try. > > > > > > However, if nobody has ever done this, I'd have to rebuild the whole > page > > > after deleting/adding. I really hope there's an other way to go. > > > > > > Kind regards > > > Franz GEIGER > > > > > > > > > > > > > > > You need to get hold of the "tab" widget and change it's text. > > > > nb = Pmw.NoteBook(root) > > nb.pack() > > > > > > nb.add("Page1") > > nb.add("Page2") > > nb.add("Page3") > > > > > > tab = nb.tab("Page1") > > tab["text"]= "Martin1" > > I've been trying to 'get round' this..... without much success internally the NoteBook keeps track of it's pages using both a list of names and a dictionary of name : page attributes so I thought you could mess around with these... notebook._pageAttrs[newname] = notebook._pageAttrs[oldname] notebook.tab(oldname)["text"]=newname notebook._pageNames[index]=newname del notebook._pageAttrs[oldname] However when you try to raise your newly renamed page it fails :-( because the callback that lifts the page to the top has the page name stuck in it like so: if self._withTabs: # Create the button for the tab. def raiseThisPage(self = self, pageName = pageName): self.selectpage(pageName) tabOptions['command'] = raiseThisPage Where pageName is the name given at the time the page was created (the above code is from the insert method in PmwNotebook) So you would have to do quite a lot of messing around.... replacing the above callback with your own at least... This is where I stopped trying... So in order to keep it simple I would (in your own code) keep a dictionary of old vs new page names or something simple like that. So you above method would look something like this:- def _onSelect_(self, pageName): realPageName = self.myPageDict[pageName] Proxy.DataProxy().containerSelect(realPageName) return Or failing that convert the pageName into a page index (an integer) using the notebook.index(pageName) method. HTH Martin P.S Most people on this list do not top post. (I'm not saying this is good _or_ bad ;-) -- Martin Franklin <mfranklin1 at gatwick.westerngeco.slb.com> From claird at lairds.com Mon Sep 1 09:28:49 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 01 Sep 2003 13:28:49 -0000 Subject: Python Documentation? References: <LQydncwLlNp2UM-iXTWJkA@comcast.com> <Xns93E975FCE1E58godlarz@62.243.74.162> <vl6dmm8jutl140@corp.supernews.com> <3f533f3d$0$32467$edfadb0f@dread16.news.tele.dk> Message-ID: <vl6ichsnqa7dfa@corp.supernews.com> In article <3f533f3d$0$32467$edfadb0f at dread16.news.tele.dk>, Dan Thrue <rummanddan_nospam at hotmail.com> wrote: >Cameron Laird wrote: >> . >> . >> . >> Python already has a structure--and much content!--for >> comparable collaboration in <URL: http:// >> www.python.org/cgi-bin/moinmoin/ >. Moreover, as several . . . >Thank for your feedback, i personally uses pydoc when im in need of >documentation, but sometimes i have been in such situations where code >snippets was necessary for me. The background for this project is to >gain a great database public of snippets hooked in a structure that is >easily for all to use, novice as well as expert. . . . I apologize for muddling my message. I completely agree that a public knowledge store of code fragments and re- lated matters, that is easy for all to access, is a great blessing. That's the aim of the Wiki. Or were you judging the Wiki a failure in that, but too polite to make it explicit? -- Cameron Laird <Cameron at Lairds.com> Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From ngps at netmemetic.com Tue Sep 16 04:58:07 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 16 Sep 2003 08:58:07 GMT Subject: was: Re: looking for MOP documentation References: <oprvdsg7tl5j9jb9@news.tiscali.dk> <3F62123C.F671D058@engcorp.com> <oprvfiy8i15j9jb9@news.tiscali.dk> <3F6319E9.4C7BAA0F@engcorp.com> Message-ID: <bk6jav$p0k$1@mawar.singnet.com.sg> According to Peter Hansen <peter at engcorp.com>: > kasper graversen wrote: > > On Fri, 12 Sep 2003 14:36:44 -0400, Peter Hansen <peter at engcorp.com> wrote: > > >> Erm, what's "MOP" mean? > > what has all this talk to do with documentation of the MOP??? > Er, if you'll look back, you'll see that Anthony asked what MOP > meant Meta Object Protocol. -- Ng Pheng Siong <ngps at netmemetic.com> http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From martin at v.loewis.de Fri Sep 12 01:50:46 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 12 Sep 2003 07:50:46 +0200 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <3F60B545.6030100@sci.fi> <mailman.1063306316.30786.python-list@python.org> <m3smn3t5xx.fsf@mira.informatik.hu-berlin.de> <mailman.1063320739.26865.python-list@python.org> Message-ID: <m37k4e7dxl.fsf@mira.informatik.hu-berlin.de> Shane Hathaway <shane at zope.com> writes: > - Copy the "1" object into shared memory before passing it to > L.append(). This would be nice and transparent, but also a little > DWIM. That might work for the object 1, but some object simply couldn't be copied, e.g. file objects, _tkinter objects, and so on. > - Create special object types just for shared memory. That might be feasible, but would not be valuable. You would have to duplicate entire type hierarchies, and it would not convenient for users to use this duplication. > As it turns out, POSH (see Jeremy's link) takes the second strategy, > apparently quite successfully! Anyone who has concerns about the GIL > should take a long, hard look at POSH. It just might solve the > problem for lots of people. It's an interesting approach, but it remains to be seen whether it really solves problems in real life. Regards, Martin From carel.fellinger at chello.nl Tue Sep 16 12:44:00 2003 From: carel.fellinger at chello.nl (Carel Fellinger) Date: Tue, 16 Sep 2003 18:44:00 +0200 Subject: Datetime utility functions In-Reply-To: <mr6emv8p5dkckghrr3imk79djtvj3ti0m5@4ax.com> References: <182bcf76.0309150707.3a8c0482@posting.google.com> <vmbopdqfn1ri59@news.supernews.com> <brtl7s6v.fsf@yahoo.co.uk> <mr6emv8p5dkckghrr3imk79djtvj3ti0m5@4ax.com> Message-ID: <20030916164400.GA3062@mail.felnet> On Tue, Sep 16, 2003 at 05:19:50PM +0300, Christos TZOTZIOY Georgiou wrote: ... > I sent my own version without having seen your own --and mine might seem > obfuscated, compared to yours. you both use the same indirect way of getting to the end of the month. why not do what datetime.c does, like: _days_in_month = [ 0, # unused; this vector uses 1-based indexing */ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] def _is_leap_year(year): return year % 4 == 0 and (year % 100 !=0 or year % 400 == 0) def days_in_month(year, month): if month == 2 and _is_leap_year(year): return 29 else: return _days_in_month[month] def end_of_month(d): date(d.y, d.m, days_in_month(d.y, d.m)) -- groetjes, carel From rebel at removethis.rebel.com.au Tue Sep 9 23:37:15 2003 From: rebel at removethis.rebel.com.au (Chris) Date: Wed, 10 Sep 2003 03:37:15 GMT Subject: Embedded Perl or Python (XPost) References: <c907a3eba2b531449c8dc7a212285911@news.teranews.com> <g_Y5b.25276$R32.778757@news2.tin.it> <74e674c13888643bf15a72e800c9d8ed@news.teranews.com> <Fxf6b.20653$hE5.755579@news1.tin.it> <3f5c61cb@shknews01> Message-ID: <e7a06f4833be928e72e1ac8ec9f61bc2@news.teranews.com> "Kerim" <my at mail.ru> wrote in news:3f5c61cb at shknews01: > "Alex Martelli" <aleax at aleax.it> wrote in message > news:Fxf6b.20653$hE5.755579 at news1.tin.it... >> Chris wrote: >> >> > LOL >> > >> > thanks for the heads up on Boost >> >> really got the hang of it, while Boost and pyste are a snap to use >> (for Python, which coversa basically all I need). >> > > And you don't consider boost::python too slow? > > Kerim > > > I havent managed to find the time to run a few trials, I have to learn python first, but I will keep that in the back of my mind Thanks for the warning Chris From martin at v.loewis.de Mon Sep 1 17:22:21 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Sep 2003 23:22:21 +0200 Subject: Update to Python 2.3 on Red Hat Linux 9 References: <8242f4a7.0308282240.4c87f997@posting.google.com> <m3ptimpoaw.fsf@mira.informatik.hu-berlin.de> <bitni9$icp$0@216.39.172.122> <m3k78tzft2.fsf@mira.informatik.hu-berlin.de> <bitvlv$69t$0@216.39.172.122> <m3he3xkq5s.fsf@mira.informatik.hu-berlin.de> <bivvnl$uim$0@216.39.172.122> Message-ID: <m3u17wp5ki.fsf@mira.informatik.hu-berlin.de> bokr at oz.net (Bengt Richter) writes: > How about automating the prerequisites part ? Assuming an individual > solves the problem for her/his platform, is there a mechanism for > contributing a script that does all the work [1] (assuming a working > core installation with standard libs) of making directories and > gathering 3rd party pieces together from the net and checking > versions and dates and md5's etc. and building and installing it? I can't think of an easy solution, given that the prerequisites part might involve inserting a CD-ROM or DVD into the drive, and/or downloading stuff. So the first person figuring out an automated way would also have to contribute that. I doubt anybody is willing to do that. > [1b] Is there a budding collection somewhere already? On python.org? What does "budding" mean? If you are asking whether there is a place where such information should be collected: Certainly, the Wiki on python.org. > So I am wondering if there could be porting scripts in the future, > downloadable from python.org Anything is possible if somebody does the hard work. And trust me: there is a lot of hard work needed here. Regards, Martin From aahz at pythoncraft.com Mon Sep 29 17:50:36 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Sep 2003 17:50:36 -0400 Subject: FTP access to starship.python.net? References: <d7fcf8b4.0309271341.72304331@posting.google.com> <7h3fzif1yi8.fsf@pc150.maths.bris.ac.uk> Message-ID: <bla9fc$v3$1@panix3.panix.com> In article <7h3fzif1yi8.fsf at pc150.maths.bris.ac.uk>, Michael Hudson <mwh at python.net> wrote: >samschul at pacbell.net (Samuel Schulenburg) writes: >> >> Who should I contact about accessing my account on Starship. I need to >> obtain a new password and access process. >> >> I think i am having a memory lapse as it has been over a year sense I >> have had a need to access my files. > >I think emailing <your username>-starship at python.net will lead to >enlightenment. Hmmmm. I tried that, and I haven't been enlightened. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From syver at inout.no Thu Sep 4 04:09:21 2003 From: syver at inout.no (Syver Enstad) Date: 04 Sep 2003 10:09:21 +0200 Subject: Code complete electronic version ? References: <b15d2792.0309030332.364532d1@posting.google.com> <vqOdnRuMAaBofMiiRVn-hg@giganews.com> <Gtmdnc6WsOhQaciiRTvUrg@speakeasy.net> <3f566672.342116427@news.blueyonder.co.uk> Message-ID: <u4qzt2cwe.fsf@inout.no> alan.gauld at btinternet.com (Alan Gauld) writes: > On Wed, 03 Sep 2003 09:03:57 -0500, "A.M. Kuchling" <amk at amk.ca> > wrote: > > On Wed, 03 Sep 2003 13:40:48 +0100, > > > If it's too much, buy it second-hand. It's a good book, and although > > > plenty of it is just common sense, it's the type of common sense that's > > > easy to miss :) > > > > Isn't it mostly concerned with C, though? > > Not really, he gives examples in BASIC, ADA, Pascal and Fortran > as well as C./C++ The latter pair dominate as a reflection on > where the industry was in 1992. But the basic tenets apply > regardless of language - code layout, variable naming, control > structures etc. > > Code Complete is essential reading for any prpfessional > programmer IMHO, but it may not be essential for non pros... I agree that Code Complete is a very good book, but I also think it is getting somewhat long in the tooth. For once it doesn't cover object-orientation. On the topic of coding I wonder if people are not better off buying Refactoring by Martin Fowler and Kent Beck. On the topic of project managment and development practices I would think that the XP white book would be more up to date. From Mike at DeleteThis.Geary.com Tue Sep 2 13:51:05 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Tue, 2 Sep 2003 10:51:05 -0700 Subject: win32all for 2.3 References: <mailman.1062503284.25172.python-list@python.org> Message-ID: <vl9m4ahdibhf60@corp.supernews.com> Gerhard Venter wrote: > I need to get *win32all* for 2.3 quite urgently. It should be at > http://starship.python.net/crew/mhammond/win32/Downloads.html > However, the starship site seems to have disappeared, even from DNS. Is > there any other way I could get the file? Starship is up, but it seems to have dropped out of DNS. Try the IP address instead: http://217.160.219.194/crew/mhammond/win32/Downloads.html And win32all-155 (for Python 2.3) is here: http://217.160.219.194/crew/mhammond/downloads/win32all-155.exe -Mike From jjl at pobox.com Mon Sep 1 16:37:49 2003 From: jjl at pobox.com (John J. Lee) Date: 01 Sep 2003 21:37:49 +0100 Subject: Advice to a Junior in High School? References: <Ivw2b.1305$Ce2.314@clmboh1-nws5.columbus.rr.com> <3d6c6fc3.0308261246.32db39d5@posting.google.com> <a86143fb.0309010829.1432737d@posting.google.com> Message-ID: <87bru4p7mq.fsf@pobox.com> pcolsen at comcast.net (Peter Olsen) writes: > soundinmotiondj at yahoo.com (Stan Graves) wrote in message news:<3d6c6fc3.0308261246.32db39d5 at posting.google.com>... [...] > Master it. Use it with precision. As Stan wrote, read Shakespeare. > Read Churchill for his prose. Read poetry. (I like Robert Service, > plain though he may be.) [...] Poor guy -- all he asked was what programming language to learn next, and he gets deluged with everybody's Lessons in Life ;-) John From max at alcyone.com Tue Sep 2 17:52:59 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 02 Sep 2003 14:52:59 -0700 Subject: cli arguments References: <3f5506d5$0$8546$ba620e4c@reader0.news.skynet.be> Message-ID: <3F55113B.AA5A5C8C@alcyone.com> Geiregat Jonas wrote: > What is the module called that's made to dael with cli argument's like > --foo-bar -c -blabla ? Try the getopt module. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Divorces are made in Heaven. \__/ Oscar Wilde From tim at remove_if_not_spam.digitig.co.uk Mon Sep 22 10:36:48 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Mon, 22 Sep 2003 15:36:48 +0100 Subject: Passing data out of a Sax parser References: <fe5nmv0mno1ib23ifekntp3v3u2er5bstt@4ax.com> <SxNab.10403$BS5.7382@newsread4.news.pas.earthlink.net> Message-ID: <942umvsv7etuu9qr104jivkc1bassh556e@4ax.com> On Sat, 20 Sep 2003 00:53:06 GMT, "Andrew Dalke" <adalke at mindspring.com> wrote: >Tim Rowe: >> b. Add a parameter to the handler's __init__ method, that takes some >> sort of mutable object, and put the answer into that object. > >Either that or have startDocument create the mutable object, as > >class MyHandler(xml.sax.handlers.ContentHandler): > def startDocument(self): > self.count = 0 > def startElement(self, name, attrs): > if name == "spam": > self.count += 1 > >parser = xml.sax.make_parser() >h = MyHandler() >parser.setContentHandler(h) >h.parse(input) >print h.count Ah! Of course! Thanks, I should have thought of that. As others have pointed out, startDocument can create any sort of an object there, not just a mutable, of course; it was my solution that required a mutable. From afriere at yahoo.co.uk Tue Sep 30 22:52:46 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 30 Sep 2003 19:52:46 -0700 Subject: Question: Inheritance from a buil-in type References: <mailman.1064911662.9559.python-list@python.org> Message-ID: <38ec68a6.0309301852.66cf1b7b@posting.google.com> "Pettersen, Bjorn S" <BjornPettersen at fairisaac.com> wrote in message news:<mailman.1064911662.9559.python-list at python.org>... > > Shart answer: you should call super as "super(MyTuple, self)". > Oops! Of course I should! From peter at engcorp.com Tue Sep 23 13:07:55 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Sep 2003 13:07:55 -0400 Subject: a little OT: how to handle this email list? References: <mailman.1064323412.13237.python-list@python.org> Message-ID: <3F707DEB.1961C7D@engcorp.com> Matthew Wilson wrote: > > I subscribe to the python mailing list with an IMAP mailbox. I use > squirrelmail to check my mail. This is a great list, but it is definitely > high volume. My python folder fills up with several hundred emails every > day. How do the rest of you handle all the traffic on this list? Do you > delete everything at the end of every day? As Skip pointed out, use a "thread kill" feature. If you don't have that with this newsgroup/mailing list, you're probably screwed! :-) I tend to read with my finger on the "k" key more than on the "n" (for "next") key. Relatively few threads survive the first posting. Some few that do, I tend to hit "n" rapidly to skip past updates except those made by folks who've shown they have a clue. If no interesting posts are made after a while, even the formerly interesting threads will get encounter the "k" key of death... -Peter From newsgroups at jhrothjr.com Fri Sep 26 12:40:01 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 26 Sep 2003 12:40:01 -0400 Subject: Reduce need of backslash References: <h4Ycb.75236$PD3.4793080@nnrp1.uunet.ca> <Xns9402A53AD8C02duncanrcpcouk@127.0.0.1> Message-ID: <vn8r00p0brg98c@news.supernews.com> "Duncan Booth" <duncan at NOSPAMrcp.co.uk> wrote in message news:Xns9402A53AD8C02duncanrcpcouk at 127.0.0.1... > Nicolas Fleury <nid_oizo at yahoo.com_remove_the_> wrote in > news:h4Ycb.75236$PD3.4793080 at nnrp1.uunet.ca: > > > I was wondering if the need for \ could be reduce in the language. For > > example, could a line ending with = or + could be automaticly considered > > incomplete? > > You very rarely need \ as it is. Any parenthesised expression may be split > across lines without problems. And you can parenthesize a surprisingly large number of places. One that I learned just recently was that the entire operand string of the print statement can be put into parenthesis. John Roth > > -- > 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 hans at zephyrfalcon.org Tue Sep 2 13:10:41 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 02 Sep 2003 13:10:41 -0400 Subject: **kwds behavior? In-Reply-To: <924a9f9c.0309020652.212c54eb@posting.google.com> References: <924a9f9c.0309020652.212c54eb@posting.google.com> Message-ID: <3F54CF11.6080904@zephyrfalcon.org> Paradox wrote: > Why does the following attempts to pass in keywords arguments not > work. It would be alot cooler if there was a way to not have to have > the function defined with the variable name. It really seems to me > that the 3rd function should work. Does anyone know how to accomplish > something like this. "this" apparently means, that you want to create local variables (within in the function) with the same names as the keyword arguments. > def testKeywords1 (**kwds): > print x > > def testKeywords2 (**kwds): > locals().update(kwds) > print x > > def testKeywords3 (**kwds): > locals().update(kwds) > def testNested(): > print x > testNested() As people already pointed out, modifying locals() like this doesn't work. There is a solution, but before using it you should stop and ask yourself why you want this. Is there a reason why leaving the values in the dict isn't sufficient? (Or putting them in a special class, like one poster suggested.) Creating variables on-the-fly is usually a bad idea. Now, on to the yucky solution: >>> def g(**kwargs): for key, value in kwargs.items(): exec "%s = %s" % (key, repr(value)) # test test... print x >>> d = {} >>> d['x'] = 5 >>> g(**d) 5 HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From andrew-twisted at puzzling.org Sun Sep 14 01:43:30 2003 From: andrew-twisted at puzzling.org (Andrew Bennetts) Date: Sun, 14 Sep 2003 15:43:30 +1000 Subject: Web server with Python In-Reply-To: <6o24mvcmksid33t4s9b8cbsrnctl5n2o6m@4ax.com> References: <tnr1mvgnt45urvu6n4q6dso3eto73hfr1m@4ax.com> <sx68b.29387$Hb.450091@news4.e.nsc.no> <bjr3ea$m5rr9$1@ID-139865.news.uni-berlin.de> <gvs2mvcgmji0s536475c14oa5tm7cigk13@4ax.com> <mailman.1063352060.32640.python-list@python.org> <6o24mvcmksid33t4s9b8cbsrnctl5n2o6m@4ax.com> Message-ID: <20030914054330.GA899@frobozz> [CC'ing the Twisted mailing list] On Fri, Sep 12, 2003 at 08:05:59PM +0200, Patrick Useldinger wrote: > On Fri, 12 Sep 2003 17:33:34 +1000, Andrew Bennetts > <andrew-pythonlist at puzzling.org> wrote: > > >> Does Twisted work well with Python 2.3? > > > >Yes, current versions support 2.3 without any problems. > > Version 1.0.6 refuses to install, though, complaining it requires Python > 2.2. Eek! Does 1.0.7 (just released) work any better? Also, what platform are you using, and are you installing from the source .tar.gz or something else? -Andrew. From uce at ftc.gov Sun Sep 21 17:10:24 2003 From: uce at ftc.gov (Gordon Airport) Date: Sun, 21 Sep 2003 17:10:24 -0400 Subject: Mutable strings - symetry with list types In-Reply-To: <mailman.1064086468.9586.python-list@python.org> References: <xhCdnSW6Do2IDPGiU-KYvQ@comcast.com> <mailman.1064086468.9586.python-list@python.org> Message-ID: <zHadnfwvu-UmjvOiU-KYhw@comcast.com> Andy Jewell wrote: > > Mutable strings are one thing that I missed, initially, when I first started > using Python. After a while, as the "Pythonic" way of doing things sank in, > I realised that Python doesn't *need* mutable strings. > Well...it doesn't /need/ the simple expressions that were given to alot of things. > Python strings (and integers and floats) are all immutable for a very good > reason: dictionaries can't reliably use mutable objects as keys. And I'm not suggesting doing away with immutable strings. > At first, > this seemed rather like "the tail wagging the dog"... however, once I fully > understood the % (percent) string operator, and the ability to efficiently > convert strings into lists and back, my anxiety went away. These cover most > usage of strings that might convince you you need mutability. > Yeah, you /can/ do everything, it's a question of clarity. You see how often ' '.join( blah ) is the answer to people's questions here, it's not obvious and it looks like a hack, IMO. Plus you can't do somestring = '%s %s %s' % [ 'nine', 'bladed', 'sword' ] The extra steps in list(somestring) ... ''.join( somestring ) are what could be removed I guess. > As for the suggestion that the kind of quote used should determine whether or > not a string is mutable, I sort of /half/ agree. On one hand, making (say) > the apostrophe mean mutable and the double quote mean immutable would break > thousands of existing applications - for end users, "a simple search and > replace" is simply not feasable! I'm less sure about that now, but the important point is that you would know that all old string delimiters would be changed to the immutable one. I'll try to come up with a regex. Furthermore, the meaning of the following > snippet would be subtly (and possibly dangerously) changed: > > ----8<----- > s1="this is an 'immutable' string" > s2='this is a "mutable" string' > > s3=s1.replace("'",'"')+" and "+s2.replace('"','"') # replace quotes with > # apostrophes and vice-versa > > > d1={s3:(s1,s2)} > ----8<----- > > Q1) What type will s3 be? > Q2) What happens to s2? As it's mutable, shouldn't it do the replacement > "in-line"? > Q3) Will the assignment of d1 succeed? If it fails, wouldn't that be > confusing? > I think these problems can be avoided if you just escape both symbols within both types of string. This complicates the code conversion, of course. > On the other hand, Python already has this type distinction for raw and > unicode strings (r"..." and u"...", respectively). If it were to be adopted, > I would be ok with an m"..." type of string, which could be barred from being > a dictionary key. This would open up a can of worms wrt the other immutable > types, too: would we end up with: > > ----8<----- > a=1234567m # a mutable integer > b=1234567.89m # a mutable float > c=123456789012345678901234567890Lm # a mutable long integer > d=123+456jm # a mutable complex number > e=m(1,2,3,4,5,6,"a","b","c") # a mutable tuple !!! :-p > ----8<----- I don't understand what a mutable numeric type would be. I just want a string type that I can directly treat as an array of characters; numeric types aren't indexable. > > This could start a flame-war/heated debate on the scale of the ternary > operator PEP! Viva la ?:! ;-) > > Maybe there's a project for you (and a good introduction to a practical > application for new-style Python classes to boot)! > > I'm sure people have written this type of thing in the past - and in some > situations, it's bound to be useful, but I think it should be kept as a > separate module, so that you have to *declare* your usage of this /strange/ > behaviour to the reader; "explicit is better than implicit". Think of it as a symetry with the mutable and immutable list types we already have. It is kind of strange, but we learn their applications and deal with it. What's the balance of what shows up in code? I suspect that in gross terms there's more (mutable) list use than (immutable) tuple; mutable strings would have their place likewise. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 01:30:07 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 06:30:07 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <m2eky8dtny.fsf@mycroft.actrix.gen.nz> <eppstein-6C690F.21531522092003@news.service.uci.edu> Message-ID: <j0mvmvg7sro9lq03ujb1isg940mgvsr43j@4ax.com> On Mon, 22 Sep 2003 21:53:15 -0700, David Eppstein <eppstein at ics.uci.edu> wrote: >In article <m2eky8dtny.fsf at mycroft.actrix.gen.nz>, > Paul Foley <see at below.invalid> wrote: > >> > There may be some hint towards PEP284 (integer for loops) in a review >> > of ideas from other languages, but I'm damned if i can figure it out. >> > I spent some time thinking about it and couldn't find anything that >> > would cover the issue. >> >> > All I came up with was the recognition that some other languages have >> > 'for' and 'foreach' loops. But Python went down the route of using >> > 'for' for looping over lists/iterators a long time ago. Maybe a new >> > keyword or combination could help, such as... >> >> > for range i in 0 <= i < 10 : > >The idea behind the specific syntax of PEP284 was simply the following >observation: one way of reading "for i in iterator" is that it loops >over the values for which the expression "i in iterator" is true. >What types of expressions other than the "in" operator could be >substituted in the same context and do something useful? OK - that makes sense, but I don't think I'd naturally read '0 <= i < 10' as an iterator without a good deal of prompting. Even with the explanation, I still feel the need for a different (or extra) keyword to emphasise the difference. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From amk at amk.ca Sun Sep 7 16:13:12 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sun, 07 Sep 2003 15:13:12 -0500 Subject: Comments on Python Redesign References: <mailman.1062934990.9290.python-list@python.org> <3F5B8C51.6462BC38@alcyone.com> Message-ID: <AtKdnWv20dXFDMaiRTvUqQ@speakeasy.net> On Sun, 07 Sep 2003 12:51:45 -0700, Erik Max Francis <max at alcyone.com> wrote: > Could someone remind me what need there is for a redesign in the first > place? Of all the Python-related efforts that one could put time into, Because the current site is unattractive, jumbled, hard to navigate, and sucks dead bunnies through a straw? --amk From tayss_temp at yahoo.com Mon Sep 8 21:36:20 2003 From: tayss_temp at yahoo.com (Tayss) Date: 8 Sep 2003 18:36:20 -0700 Subject: Making mock (was Re: "Python Redesign" (fwd)) References: <mailman.1062982932.16437.python-list@python.org> <TsmdnYgCScjFEsGiU-KYgw@comcast.com> <bjif13$ou8$1@panix3.panix.com> <5XmdnSsEgZVGSsGiU-KYvw@comcast.com> <bjiosp$g7c$1@panix3.panix.com> Message-ID: <5627c6fa.0309081736.5fbc0d2b@posting.google.com> As I understand, people were unhappy he gave us a prototype. However, some developers even talk about paper prototypes. http://www.joelonsoftware.com/news/20030516.html Not everyone gets to use a language where the prototype is the working implementation. ;) - Tayssir John Gabbour From kaede.news at online.ru Thu Sep 11 15:28:45 2003 From: kaede.news at online.ru (Eugene Morozov) Date: Thu, 11 Sep 2003 23:28:45 +0400 Subject: JPEG comments and PIL Message-ID: <87ekynnmz6.fsf@tanya.home.spb> Hello! Is it possible to manipulate JPEG comments using PIL? I didn't find corresponding methods in the PIL library. I just want to write yet another image viewer and editor (similar to gthumb only crossplatform and with better comment editing interface and web album generation feature ;)) which stores comments in the JPEG images themselves. Eugene -- Email: <jmv at online.ru> From lupan at zamek.gda.pl Fri Sep 19 06:45:35 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Fri, 19 Sep 2003 12:45:35 +0200 Subject: string objects... References: <e84f5d12.0309182143.3807af0e@posting.google.com> Message-ID: <87k7853vlc.fsf@psi.lupan.zamek.gda.pl> mynews44 at yahoo.com (google account) writes: > I know that string.letters and string.digits are all the letters and > numbers, is there a string.???? that is a subset of all the ascii > characters that are available on a US English Keyboard without going > to special characters (like ? or ?) > > I couldnt see anything that was explaining this stuff on the > python.org site. > > I think what I want is soemthing like string.printable - > string.whitespace but that doesn't seem to work like string.letters + > string.numbers... > Minus does not work on string, as there is now obvious meaning of this: cut from the end, or a set like minus you would be happy this time You may use list comprehension to filter out all whitespace from printable and than join the list with empty separator: >>> import string >>> ''.join([c for c in string.printable if c not in string.whitespace]) '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' -- =*= Lukasz Pankowski =*= From aleax at aleax.it Thu Sep 25 09:00:14 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Sep 2003 13:00:14 GMT Subject: Help me choose a C++ compiler to work with Python References: <616fccba.0309210907.1e35b92d@posting.google.com> <3dd5593c.0309211615.747ba123@posting.google.com> <3F6E4D02.7868D52C@easystreet.com> <616fccba.0309230137.586ddea5@posting.google.com> <bkt9ct$71h$1@peabody.colorado.edu> Message-ID: <yFBcb.119348$hE5.4103433@news1.tin.it> Fernando Perez wrote: ... >> e.g. generating billions (with a B) of random numbers with the >> Mersenne Twister algorithm > > Off the top of my head I don't know which rng RandomArray (part of > Numeric) uses, but its speed is not that bad: ... > The scaling is pretty linear, so for a billion terms you'd need about 2 > minutes. Similar orders of magnitude for the built-in random number generator, which IS a Mersenne Twister in Python 2.3 -- at least on my old trusty Athlon box (no doubt today's CPU's would easily take 3 or 4 times less): [alex at lancelot python2.3]$ python timeit.py \ > -s "from random import random" \ > -s "times=[None]*1000" > "for x in times: random()" 1000 loops, best of 3: 380 usec per loop 380 microseconds for 1,000 calls to random.random(), and here, too, very linear scaling, suggests about 380 seconds for a billion calls, i.e., about 6 or 7 minutes, on this old machine. Alex From skip at pobox.com Sat Sep 13 10:58:42 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 13 Sep 2003 09:58:42 -0500 Subject: Flash Remoting in Python? In-Reply-To: <oprvc7dcpg5ctagx@shawnews> References: <7712111.0309111357.3be3b591@posting.google.com> <2E78b.1002$8g2.829@news1.central.cox.net> <E5WcnXLOoPRMiPyiXTWJiQ@comcast.com> <VV88b.1024$8g2.587@news1.central.cox.net> <oprvc7dcpg5ctagx@shawnews> Message-ID: <16227.12450.504046.510291@montanaro.dyndns.org> >> I will note, however, that Flash's XML parser is slow, and WDDX is >> more compact than XML-RPC (although it isn't, in itself, an RPC >> protocol, unlike XML-RPC). Jordan> God, is it ever slow. I'm working on a remote playlist editor Jordan> (Flash talking to Python XML-RPC), and when sending a list of Jordan> ~1000 entities across the wire, performance was increased nearly Jordan> a hundred times simply by sending one delimited string element Jordan> instead of 1000 XML elements. Of course, XML adds quite a bit Jordan> of bloat, but all the time was consumed in CPU, not on the wire. Have you tried installing sgmlop, which pushes most of the XML parsing into C? http://www.pythonware.com/products/xml/sgmlop.htm Skip From steve at ferg.org Sun Sep 28 21:37:37 2003 From: steve at ferg.org (Stephen Ferg) Date: 28 Sep 2003 18:37:37 -0700 Subject: Python mascot? How about a Pythoneer? Message-ID: <b16e4ef7.0309281737.46423a88@posting.google.com> I've been thinking that a good Python mascot might help in raising public awareness of Python. The problem with a snake as a mascot is that it is not anthropomorphic enough. An effective mascot has to have something approximating two arms, two legs, and a head, so that he can be put into various interesting situations and adventures. (At the very least, he has to be able to work a keyboard and a mouse!) Good examples can be found in some of the imaginative things that have been done with Linux's Tux. So a snake is out. So are Terry Gilliam's wonderful cartoons for the Flying Circus. While wonderful, I just don't think they lend themselves to mascot-hood. With the snake and the flying circus eliminated, we haven't got much left. Clearly, it is time to think out of the box. In that spirit, I propose the development of a figure representing Python -- the Pythoneer. He'd be loosley based on Dave Stevens' Rocketeer (which became the Disney movie, "The Rocketeer") and/or on the Rocketman figure of the old Republic serials -- Commando Cody, King of the Rocketmen, and so on. But he'd have a big "P" on his chest, like Guido has in the second picture on http://www.python.org/~guido/pics.html With a helmet, the Pythoneer's features are simplified enough to lend themselves to small images, cartoons, and even (in the hands of skilled artists) the expression of emotions. The rocket pack suggests the power of Python and the power that Python gives to developers. See for example http://goldenscore.free.fr/images/rocketeer.jpg The rocket pack also offers a useful means for getting/putting the Pythoneer into interesting situations and adventures. At first I liked the idea of a Pythoneer modelled on Dave Stevens' Rocketeer, but after thinking about what I assume is a copyright on the Rocketeer figure -- and also thinking that the riding pants get a bit old after a while -- I have warmed to the clunky charms of the original Rocketman figure with his bullet-like helmet. So now the idea/proposal has been thrown into the comp.lang.python arena. Is the idea for a Python mascot a good one, or a stupid one? Is the idea of a Pythoneer a good one? Or are there other, better, Python mascots just waiting to emerge? -- Steve Ferg ================================================== Here are some reference materials The Rocketeer ------------- http://home.mindspring.com/~graphic_illusion/rocket.jpg http://www.filmwise.com/visual/cutout_03/image_02a.jpg The Rocketman ------------- http://www.superherophotos.net/serials/cc.jpg http://www.geocities.com/Heartland/Garden/3622/ccsmou.htm http://www.geocities.com/Heartland/Garden/3622/moreimages.htm http://users.erols.com/cdmalin/CommCody.jpg The Rocketeer and Rocketman --------------------------- (This page proves that Jennifer Connelly would also make a great Python mascot... I'm sure her presence would boost attendance at the IPCs.) http://www.superherophotos.net/serials/rocket.htm http://www.rocketmania.com/images/two%20rockets.jpg Tux ----------------------- Finally,here are some things that have been done with Tux. The original drawing by Larry Ewing: http://www.isc.tamu.edu/~lewing/linux/ Collections of Tuxes: http://www.linux.org/info/logos.html http://tunes.org/~do/penguindex.html From martin at v.loewis.de Sun Sep 14 18:02:57 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 15 Sep 2003 00:02:57 +0200 Subject: Python / Chinese Encodings References: <bjv5vk$6cu$03$1@news.t-online.com> Message-ID: <m31xujdo4u.fsf@mira.informatik.hu-berlin.de> "Achim Domma" <domma at procoders.net> writes: > I need to convert Big5 or GB encoded chinese strings to unicode. It would > be also nice to be able to detect the encoding of the original string. > Search with groups.google.com I found some links to different projects but > they all look not very active. Can somebody give me a short overview of the > status of processing chinese texts with python? The very short summary: Use the CJK codecs package; it supports all encodings you might encounter, and it is actively maintained. As for detecting the encoding of the original string: Forget it. Tell your communication partners to always properly declare the encoding. Regards, Martin From tzot at sil-tec.gr Thu Sep 4 13:18:43 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 04 Sep 2003 20:18:43 +0300 Subject: Tkinter Text widget getting too slow References: <ba1e306f.0309030713.ef2ec4a@posting.google.com> <bj5b4g$jtg$1@news.hananet.net> Message-ID: <eoselvguf3hvie3s95kjndhtuno0jiu09s@4ax.com> On Thu, 4 Sep 2003 03:15:16 +0900, rumours say that "Changjune Kim" <juneaftn at REMOVETHIShanmail.net> might have written: >(I'm interested to see his "extremely fast" text widget, too) Notice that Michael Peuser described an "extremely fast" "binary editor"; I assume a dual view (hex / chars) one. This is not a text widget --you don't have to account for line feeds and variable width characters :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From uwe.schmitt at procoders.net Wed Sep 17 13:55:49 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 17 Sep 2003 17:55:49 GMT Subject: build python using mingw Message-ID: <bka775$3djvv$1@hades.rz.uni-saarland.de> Hi, I tried to build python 2.3 on a windows 2k machine using mingw. configure works fine, but when compiling Module/posixmodule.c I get lots of warnings, one is 'SIGCHLD undeclared' (first use in this function). Did anyone suceed in building Python + mingw ? Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt http://www.procoders.net schmitt at procoders.net "A service to open source is a service to mankind." From aleax at aleax.it Mon Sep 22 08:31:58 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 12:31:58 GMT Subject: Mutable strings References: <xhCdnSW6Do2IDPGiU-KYvQ@comcast.com> <mailman.1064086468.9586.python-list@python.org> <6e990e29.0309220251.51fa648d@posting.google.com> Message-ID: <2ZBbb.100213$hE5.3539928@news1.tin.it> Hans-Joachim Widmaier wrote: ... >> I realised that Python doesn't *need* mutable strings. > > Mutable strings come to *my* mind whenever I have to play with huge > binary data. Working with tens of megabytes is inherently somewhat > slow. But mutable strings are not the best place to keep "huge binary data". Lists of smaller blocks, arrays of bytes, and lists of arrays can be much more appropriate data structures. >> Python strings (and integers and floats) are all immutable for a very goo >> d >> reason: dictionaries can't reliably use mutable objects as keys. > > All understood. But then, I don't want to use my 32-MB binary blob as > a key. Since you don't in fact need to use it in any of the ways typically applicable only to strings, it doesn't need to be a string. >> convert strings into lists and back, my anxiety went away. These cover >> most usage of strings that might convince you you need mutability. > > Converting said blob 'efficiently' to a list is something that I > certainly would not call 'efficiently' - if not for the conversion > itself, then for the memory consumption as list. A typical case might be one where the blob is, e.g., in fact made up of 65K sectors of 512 bytes each. In this case, the extra memory consumption due to keeping the blob in memory as a list of 65K small strings rather than one big string is, I would guess, about 1%. So, who cares? And similarly if the "substrings" are of different sizes, just as long as you only have a few tens of thousands of such substrings. It's quite unusual that the "intrinsic structure" of the blob is in fact one big undifferentiated 32MB thingy -- when it is, you're unlikely to need it in memory, or if you do you're unlikely to be able to apply any processing mutation to it sensibly; and for those unusual and unlikely cases, arrays of bytes are often just fine (after all, C has nothing BUT arrays of bytes [or of other fixed entities], yet it's quite suitable for some such processing). > I don't think strings are immutable because they ought to be that way > (e.g. some CS guru teaches that "mutable strings are the root of all > evil"). They're immutable because they allow them to be used as > dictionary keys. And it was found that this doesn't affect the > usefulness of the language too much. Wrong. Consider Java, even back from the very first version: it had no dictionaries on which string might be keys, yet it still decided to make its strings immutable. This should make it obvious that the interest of using keys as dict keys cannot possibly be the sole motivation for the decision to make strings immutable in a language. Rather, the deeper motivation is connected to wanting strings to be ATOMIC, ELEMENTARY types, just like numbers; and to lots of useful practical returns of that choice. All you lose is the "ability" to "confuse" (type-pun) between strings and arrays of bytes in many situations, but that's an ability best lost in many cases. It's not an issue of "evil" -- a close-to-the-hardware low-level language like C has excellent reasons to choose a different, close-to-HW semantics -- but in a higher-level language I think Python's and Java's choice to have strings immutable works better than (e.g.) Perl's and Ruby's to have them mutable. > Still, I can see a use for mutable strings. Or better, mutable binary > data, made up of bytes. (where 'byte' is the smallest individually > addressable memory unit blabla, ... you get the meaning. Just to not > invite nit-pickers on that term.) Just "import array" and you have your "mutable binary data made up of bytes". So, what's the problem? Type-punning between THAT type, and strings, is just not all that useful. >> "explicit is better than implicit". > > Yes, definitely: Let there be another type. But, there IS one! So, hat's wrong with it...?! Alex From bokr at oz.net Thu Sep 4 16:49:37 2003 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2003 20:49:37 GMT Subject: Open Source leader? (was Re: Celebrity advice) References: <mailman.1061927168.7845.python-list@python.org> <yra3b.6546$Jh2.2048@newsread4.news.pas.earthlink.net> <23891c90.0308280317.ac68b38@posting.google.com> <Kv-cnVDMbb1qmdOiRTvUqg@speakeasy.net> <biqve2$qp0$1@panix1.panix.com> <87y8x6x2op.fsf@pobox.com> <mailman.1062541744.4844.python-list@python.org> Message-ID: <bj88h1$b2n$0@216.39.172.122> On Tue, 2 Sep 2003 15:27:57 -0700, Geoff Gerrietts <geoff at gerrietts.net> wrote: >Quoting John J. Lee (jjl at pobox.com): >> aahz at pythoncraft.com (Aahz) writes: >> >> > In article <Kv-cnVDMbb1qmdOiRTvUqg at speakeasy.net>, >> [...] >> > OTOH, Perens is also (like me ;-) a self-described asshole. When I saw >> > him at the Waterside Conference earlier this year, he basically claimed >> > that only assholes could make significant progress in the Open Source >> > community. >> [...] >> >> Why? > >I think the sentiment is just a variant on the "politicians always >lie" theme. Open source is socio-political, and so it's the >charismatics that succeed. "Asshole" is one manifestation of a strong >personality. I don't believe that. IMO the most obnoxious manifestations of "asshole"-ness are due to *weak* personalities using powerful positions to over-compensate ;-/ An assertive maverick is not necessarily an "asshole" in my book, though those threatened by such a personality will often be quick with that label. (Note that assertiveness != bullying. Bullying is a hallmark behavior of "asshole"-hood). Regards, Bengt Richter From g_alleon at yahoo.fr Wed Sep 3 08:00:39 2003 From: g_alleon at yahoo.fr (guillaume) Date: 3 Sep 2003 05:00:39 -0700 Subject: reading large file Message-ID: <9bd0dd3f.0309030400.7fa2dc0f@posting.google.com> I have to read and process a large ASCII file containing a mesh : a list of points and triangles. The file is 100 MBytes. I first tried to do it in memory but I think I am running out of memory therefore I decide to use the shelve module to store my points and elements on disks. Despite the fact it is slow ... Any hint ? I think I have the same memory problem but I don't understand why since my aPoint should be removed by the gc. Have you any idea ? Thanks Guillaume PS : here is the code for your info import string import os import sys import time import resource import shelve import psyco psyco.full() class point: def __init__(self,x,y,z): self.x = x self.y = y self.z = z def SFMImport(filename): print 'UNV Import ("%s")' % filename db = shelve.open('points.db') file = open(filename, "r") linenumber = 1 nbpoints = 0 nbfaces = 0 pointList = [] faceList = [] line = file.readline() words = string.split(line) nbpoints = string.atoi(words[1]) nbtrias = string.atoi(words[0]) print "found %s points and %s triangles" % (nbpoints, nbtrias) t1 = time.time() for i in range(nbpoints): line = file.readline() words = string.split(line) x = string.atof(words[1].replace("D","E")) y = string.atof(words[2].replace("D","E")) z = string.atof(words[3].replace("D","E")) aPoint = point(x, y, z) as = "point%s" % i if (i%250000 == 0): print "%7d points <%s>" % (i, time.time() - t1) t1 = time.time() db[as] = aPoint print "%s points read in %s seconds" % (nbpoints, time.time() - t1) bd.close() t1 = time.time() t2 = time.time() for i in range(nbtrias): line = file.readline() words = string.split(line) i1 = string.atoi(words[0]) i2 = string.atoi(words[1]) i3 = string.atoi(words[2]) faceList.append((i1,i2,i3)) if (i%100000 == 0): print "%s faces <%s>" % (i, time.time() - t1) t1 = time.time() print "%s points read in %s seconds" % (nbpoints, time.time() - t2) file.close() def callback(fs): filename = fs.filename UNVImport(filename) if __name__ == "__main__": # try: # import GUI # except: # print "This script is only working with the new GUI module ..." # else: # fs = GUI.FileSelector() # fs.activate(callback, fs) print sys.argv[0] SFMImport(sys.argv[1]) From bobnotbob at byu.edu Mon Sep 15 10:28:02 2003 From: bobnotbob at byu.edu (Bob Roberts) Date: 15 Sep 2003 07:28:02 -0700 Subject: better use of os.system() References: <c4e6b17d.0309140835.3408fc52@posting.google.com> <181d118be52ffabbbeaa120340c3f759@news.teranews.com> Message-ID: <c4e6b17d.0309150628.40bc0a34@posting.google.com> Fooman <fee at fee.com> wrote in message news:<181d118be52ffabbbeaa120340c3f759 at news.teranews.com>... > > lower: not found > > > > I want it to run "lower" just like it would if I typed "lower" at the > > bash prompt. How can I do that? > > The problem is that the 'lower' script is not in the path that > the python interpreter knows about. You can do: > > os.system("/my/nonstandard/pathto/lower") > > or, if you are using Linux, or similar, you can try > making sure that your $PATH variable is getting set to > include the path to your script in the environment that > the python interpreter gets launched in. > > So, what platform are you running under, and what is the > path to your 'lower' script, and what are the contents > of your $PATH variable? I am running under cygwin (it acts like linux in many respects), using the cygwin-built version of python. The path to "lower" is ~/bin/lower, and ~/bin is in my $PATH. From jepler at unpythonic.net Mon Sep 29 11:26:55 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 29 Sep 2003 10:26:55 -0500 Subject: isNumber? check In-Reply-To: <C30548A9-F240-11D7-9145-003065F081D2@cs.brown.edu> References: <vndo742ca2f10@corp.supernews.com> <C30548A9-F240-11D7-9145-003065F081D2@cs.brown.edu> Message-ID: <20030929152649.GS32482@unpythonic.net> First, whatever test you use, you should probably encapsulate it in a function, so that if you need to update the definition you can do it at one site instead of many: def isnumeric(x): return isinstance(x, (int, long, float)) You could have a registry of numeric types: _numeric_types = () def register_numeric_type(t): global _numeric_types if t in _numeric_types: return _numeric_types += (t,) for value in (0, 0., 0l, 0j): register_numeric_type(type(value)) def isnumeric(x): return isinstance(x, _numeric_types) Now, if someone wants to write a vector type, it merely needs to be registered. You could test that common numeric operations work: def isnumeric(x): try: if x*1 == x and x+0 == x: return 1 except TypeError: pass return 0 You could just run your code and let the eventual TypeError speak for itself.. instead of def f(x): if not isnumeric(x): raise TypeError, "can't f() a %s" % type(x) return x*x just write def f2(x): return x*x The difference in the quality of the error message is not large: >>> f("") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in f TypeError: can't f() a <type 'str'> >>> f2("") Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in f2 TypeError: unsupported operand type(s) for *: 'str' and 'str' Jeff From p at trick.lu Sat Sep 20 15:42:16 2003 From: p at trick.lu (Patrick Useldinger) Date: Sat, 20 Sep 2003 21:42:16 +0200 Subject: raw string References: <petitmermet-7E9286.21104520092003@pfaff2-rz-fast.ethz.ch> Message-ID: <q7bpmv4ipank993i81u7c1nfa67ri7qdv3@4ax.com> On Sat, 20 Sep 2003 21:10:46 +0200, Marc Petitmermet <petitmermet at mat.ethz.ch> wrote: >I can do the following replacement: > >r"kr\xdf6;ger".replace('\\','&#') >-> 'kr෶ger' > >But how can I do this using a variable which contains the above string? >Obviously, the following code returns not the string with replacement >but the name of the variable itself: > >name = "kr\xdf6;ger" >r"name".replace('\\','&#') >-> 'r"name" name = r"kr\xdf6;ger" (the r goes here) name.replace('\\','&#') (the name of the object must not be in quotes) -PU From tebeka at cs.bgu.ac.il Mon Sep 29 02:26:16 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 28 Sep 2003 23:26:16 -0700 Subject: write a file "copy" program in Python for Unix and Windows... References: <rmMdb.366088$2x.112007@rwcrnsc52.ops.asp.att.net> Message-ID: <33803989.0309282226.3bf2fb5f@posting.google.com> Hello Ben, > I need to write a program to "copy" files and preserved the files' > atime, mtime, ctime, file permissions. I also need to have this > program working in Unix and Windows, where the "Archive" > attribute on the file also has to be preserved (any more > Windows idiosyncrasies?). http://www.python.org/doc/current/lib/module-shutil.html HTH. Miki From blunck at gst.com Mon Sep 1 23:26:13 2003 From: blunck at gst.com (Christopher Blunck) Date: Mon, 01 Sep 2003 23:26:13 -0400 Subject: TKinter is driving me crazy! References: <mailman.1062445743.2958.python-list@python.org> Message-ID: <pan.2003.09.02.03.26.13.240018@gst.com> On Mon, 01 Sep 2003 15:46:41 -0400, tjlan wrote: > Okay now im pretty sure this is really easy and pretty stupid but i need > to create this. To make it simple ill use another program as an example. A > guessing game that has an input field and button and an output field that > can display w/e. I know this is really easy in c++ but it needs ot be done > in python. Can anyone start me off here or give me a skeleton structure on > this is supposed to be arranged. Thanx in advance. My advice: Drop $50 at the local bookstore and buy a copy of Python and Tkinter Programming. I was in your exact shoes a couple of weeks ago, and finally threw up my hands in disgust looking for help. The web had little info. The book as good examples. I highly recommend it. -c From jepler at unpythonic.net Tue Sep 16 08:00:24 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 16 Sep 2003 07:00:24 -0500 Subject: (no subject) In-Reply-To: <Law15-F26k5s6yonjH50001492d@hotmail.com> References: <Law15-F26k5s6yonjH50001492d@hotmail.com> Message-ID: <20030916120019.GA32713@unpythonic.net> It is possible on the Tk end on X11. Here's how you do it: from Tkinter import * import os t = Tk() f = Frame(t, container=1, width=300, height=300) f.pack() frame_id = f.winfo_id() os.system("/usr/X11R6/lib/xscreensaver/gears -window-id 0x%x &" % frame_id) t.mainloop() The idea is this: You create a frame with -container and the desired size for your app. Then, you create the other app but tell it to use the specific window-id as parent, instead of the root window. Your task is to figure out how to specify the equivalent of xscreensaver's -window-id or Tk's Toplevel(use=) with PyGame. If you're using Windows, I have no idea how or if this works. Jeff From alanmk at hotmail.com Tue Sep 23 14:42:17 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 23 Sep 2003 19:42:17 +0100 Subject: problem using urllib2: \n References: <7cb14f9.0309230800.8d3a28b@posting.google.com> Message-ID: <3F709409.6BC7B6F9@hotmail.com> [bmiras at yahoo.com wrote] > Here is an exemple of the piece of code I use: > > import urllib2 > #Proxy handler > proxy_handler = urllib2.ProxyHandler({"http" : > "http://proxyuser:proxypassword at myproxy:8050"}) Might you need to change that URL? It looks like this URL indicates that the proxy is running on port 8050 on host "myproxy". Unless the host on which the proxy is running is named "myproxy", try changing the proxy URL to one of the following values http://proxyuser:proxypassword at localhost:8050 http://proxyuser:proxypassword at 127.0.0.1:8050 HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From corey.coughlin at attbi.com Wed Sep 10 20:06:05 2003 From: corey.coughlin at attbi.com (Corey Coughlin) Date: 10 Sep 2003 17:06:05 -0700 Subject: My future Python IDE article References: <mailman.1061920192.21278.python-list@python.org> Message-ID: <a8623416.0309101606.37152c17@posting.google.com> As for me, I'm currently using Emacs, but I'd love to find a nice IDE. I can't even use IDLE at work, sadly, some arcane problem with upgrading Tcl/Tk on Solaris 5.3 machines, very annyoing. But generally, it seems like it would be a little pointless to review IDLE. Since it's included, everyone can try it at their leisure. The same pretty much applies for X/Emacs, it's been around so long now that by this time anyone who is going to try it is probably already using it. Sure, have a paragraph about standard editing solutions and mention them, but don't focus on them. I'd prefer to see some reviews of the other, less standard editors out there, especially ones with GUI editors, that sounds kind of cool. Emphasis on cross-platform solutions would also be good, as I said I'm using Solaris here at work, but Windows and Linux at home. I'd love to find a great editor for all three environments. I look forward to seeing the article! From hildegarde_roth at yahoo.de Tue Sep 23 09:42:36 2003 From: hildegarde_roth at yahoo.de (Hilde Roth) Date: 23 Sep 2003 06:42:36 -0700 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <bk80n3$rsb$03$1@news.t-online.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <bk9sfo$55q$06$1@news.t-online.com> <95b4b9ac.0309171233.21f4c07@posting.google.com> <bkblav$u63$03$1@news.t-online.com> <95b4b9ac.0309180950.30b44d89@posting.google.com> <jMmab.507800$uu5.85683@sccrnsc04> Message-ID: <95b4b9ac.0309230542.78a5882a@posting.google.com> > Only if all the sublists are of the same length, which is guaranteed for > a multi-dimensional array, but not for a list of lists. This is a red herring. > What do you expect a[;1] to return if a = [[], [1, 2, 3], [4], 5]? Whatever error python returns if you ask, e.g., for (1,2,3)[4]. Hilde From aleax at aleax.it Tue Sep 23 06:15:27 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 23 Sep 2003 10:15:27 GMT Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> <AqQab.40174$NM1.1797@newsread2.news.atl.earthlink.net> <S6Tab.2$eb4.0@twister.southeast.rr.com> <bkicq0$vl5$0@216.39.172.122> <tyfvfrjhmsb.fsf@pcepsft001.cern.ch> Message-ID: <33Vbb.146289$R32.4736926@news2.tin.it> Jacek Generowicz wrote: ... > Or, you could let _any_ (keywordless) function benefit from its own > experience: This "_any_ (keywordless) function" is a substantial overbid. The following implementation: > # General memoizer: takes a function as returns another function which > # has the same semantics as the original, but caches previously > # calculated values > def memoize(callable): > cache = {} > def proxy(*args): > try: return cache[args] > except KeyError: return cache.setdefault(args, callable(*args)) > return proxy only works for a "PURE" function (e.g., not random.random() nor time.time(), even though both ARE obviously part of the "any keywordless function" set!-) *WITHOUT* unhashable arguments (e.g., not the new built-in 'sum', even though it IS pure when called with a list argument -- because when it tries to index cache with the list as part of the key, you'll get a TypeError). Basically, it's fine if arguments (if any) are numbers, strings, or hashable tuples, but it would be pushing your luck A LOT to use it in any other case -- it's particularly dangerous, because you will get a silent misbehavior, in a case such as: class Foo: def __init__(self, x=0, y=0): self.x=x self.y=y def xplusy(somefoo): return somefoo.x + somefoo.y f = Foo() print xplusy(f) f.x = 23 print xplusy(f) # so far so good, but now...: xplusy = memoize(xplusy) print xplusy(f) # still LOOKS fine, but, check this out...: f.y = 100 print xplusy(f) # OOPS! xplusy's "memory" is now subtly incorrect...!!! Unfortunately f "is hashable" (because it doesn't define a __cmp__) but is NOT immutable, and xplusy, while pure, DOES depend on some attributes of its (mutable) argument. The resulting behavior may be rather unexpected, and, indeed, a subtle bug indeed to find... Alex From R.Brodie at rl.ac.uk Fri Sep 26 04:54:52 2003 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 26 Sep 2003 09:54:52 +0100 Subject: Turning Strings into Functions References: <46610d4e.0309251516.45a8eb01@posting.google.com> Message-ID: <bl0usu$j5g@newton.cc.rl.ac.uk> "Freddy" <freddycooper01 at yahoo.com> wrote in message news:46610d4e.0309251516.45a8eb01 at posting.google.com... > How do you turn a string into a callable function? I'm writing a > program which takes user input and then looks up the associated > function to run from a shelved dictionary. I see you have an answer already, so I'll give you a question. Is there any particular reason why you are storing the name of the function in the dictionary rather than the function itself? i.e. myDict["Case1"] = {"desc":"This is Case1", "func1": Handler1} etc From xucs007 at yahoo.com Wed Sep 17 08:40:12 2003 From: xucs007 at yahoo.com (Xu, C.S.) Date: 17 Sep 2003 05:40:12 -0700 Subject: How to make URLLIB .urlopen(url1) .urlopen(url2) session related ? References: <8f41cfd.0309130423.22054528@posting.google.com> <3F631C0C.2AAA08CF@engcorp.com> <87vfrw9u23.fsf@pobox.com> <Xns93F62417D43ADJanC@213.118.75.228> Message-ID: <8f41cfd.0309170440.caa80ff@posting.google.com> ClientCookie works great with ebay, and a few other sites I'm interested. I'd like to donate a few bucks for the author to buy several cups of coffee during writing more interesting python modules. Where should I send the money to? Paypal, or check? ClientCookie will save me a lot time, guaranteed! From donn at drizzle.com Tue Sep 23 02:26:23 2003 From: donn at drizzle.com (Donn Cave) Date: Tue, 23 Sep 2003 06:26:23 -0000 Subject: Mailbox cleaner on an IMAP basis? References: <3f6f2cfb@news.swissonline.ch> <vmuhsrr68tlj27@news.supernews.com> <3f6fdd8e@news.swissonline.ch> Message-ID: <1064298380.225028@yasure> Quoth "F. GEIGER" <fgeiger at datec.at>: | I've stopped here, because I could not figure out how to get at the ids of | mails with attachments. And if I had that missing link, I'd run into the | next hindrance: How can I delete a single message? IMAP4::delete() deletes a | whole mailbox, not just a single mail. | | So my code really is only a few lines so far: | | i = IMAP4(myDomain) | i.login(myUser, myPassword) | i.select() # Select INBOX | r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])") # Check 1st mail | | Seems I have to get a book about IMAP and how to use it... The IMAP4rev1 RFC of course covers these things, with examples. 2060, I think it is. A message takes two steps to delete: first, set a \Deleted flag on it, and then invoke expunge on the folder, which will remove all delete-flagged messages in the folder. Donn Cave, donn at drizzle.com From jepler at unpythonic.net Sat Sep 13 20:37:25 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 13 Sep 2003 19:37:25 -0500 Subject: stripping a string In-Reply-To: <C497480353EF904FBF7A8B0851E5422C9F7BB1@MAIL002.AD.MLP.COM> References: <C497480353EF904FBF7A8B0851E5422C9F7BB1@MAIL002.AD.MLP.COM> Message-ID: <20030914003725.GB7424@unpythonic.net> If you want to remove all digits from the string, then use str.translate, not regular expressions: import string identity_transformation = string.maketrans('', '') def remove_digits(s): return s.translate(identity_transformation, string.digits) >>> s = 'ANL LN32' >>> remove_digits(s) 'ANL LN' If you want to remove digits from the end of the string, then use str.strip(), not a regular expression: >>> s.rstrip(string.digits) 'ANL LN' Jeff From wt at nic.fi Mon Sep 15 01:57:25 2003 From: wt at nic.fi (Timo Virkkala) Date: Mon, 15 Sep 2003 08:57:25 +0300 Subject: Encoding problems with DCOracle2 In-Reply-To: <bk2n9b$jsk$07$1@news.t-online.com> References: <ro49b.6833$ZB4.4248@reader1.news.jippii.net> <bk2n9b$jsk$07$1@news.t-online.com> Message-ID: <Utc9b.6898$ZB4.1368@reader1.news.jippii.net> Peter Otten wrote: > Timo Virkkala wrote: >>I'm having some trouble with Python2.2 and DCOracle2. I'm successfully >>executing a query, and getting the result I'm hoping for - with an added >>bonus of some interesting encoding. The beginning of the result set I >>get looks like this: >> >>[['\x00A\x001', '\x00M\x00i\x00k\x00e\x00 >>\x00P\x00o\x00r\x00t\x00n\x00o\x00y', None, None, >>'\x00d\x00r\x00u\x00m\x00s'], ... > > Seems you are getting unicode from the db. Here's how to convert it to > latin1: > > >>>unicode('\x00P\x00o\x00r\x00t\x00n\x00o\x00y', 'utf-16-be').encode('latin1') > 'Portnoy' Thanks, that solved it! Now, it feels like I'm treating a symptom here, not the cause. Is there a way to set the database (Oracle 9i) to send me something else than Unicode? -- Timo Virkkala | wt at nic.fi "In the battle between you and the world, bet on the world." From alanmk at hotmail.com Thu Sep 25 09:57:59 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 25 Sep 2003 14:57:59 +0100 Subject: "for" with "else"? References: <bkuqmu$ajv$1@ctb-nnrp2.saix.net> Message-ID: <3F72F467.191601A7@hotmail.com> [Invalid User wrote] > While trying to print a none empty list, I accidentaly put an "else" > statement with a "for" instead of "if". Here is what I had: >From the Python Language Reference """ The for statement for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] The expression list is evaluated once; it should yield a sequence. The suite is then executed once for each item in the sequence, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates. """ http://www.python.org/doc/current/ref/for.html A quick glance through the archives confirms that this has been the case since at least python 1.4:- http://www.python.org/doc/1.4/ref/ref7.html#HDR2 regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From grante at visi.com Tue Sep 16 19:17:59 2003 From: grante at visi.com (Grant Edwards) Date: 16 Sep 2003 23:17:59 GMT Subject: App development for Sharp Zaurus PDA using QTopia? References: <3f6751fc$0$162$a1866201@newsreader.visi.com> <mailman.1063750224.23114.python-list@python.org> Message-ID: <3f679a27$0$173$a1866201@newsreader.visi.com> In article <mailman.1063750224.23114.python-list at python.org>, Phil Thompson wrote: >> I see there's a Python binary package available for the Sharp >> Zaurus PDA. Has anybody deleloped an app for that platform? >> I'm wondering if the resource requirement of Python are a >> problem on that platform. > > http://www.riverbankcomputing.co.uk/zaurus/download.php Yup. That's the package to which I was referring. I was wondering if anybody had any experience with it which they would like to relate -- especially regarding the memory footprint of a python app. -- Grant Edwards grante Yow! MY income is ALL at disposable! visi.com From selwyn at home.net.nz Fri Sep 5 20:35:42 2003 From: selwyn at home.net.nz (selwyn) Date: Sat, 06 Sep 2003 12:35:42 +1200 Subject: Packaging? In-Reply-To: <abc3fdd3.0309051611.6dd16bf7@posting.google.com> References: <abc3fdd3.0309051611.6dd16bf7@posting.google.com> Message-ID: <dX96b.4178$cg.203950@news02.tsnz.net> Kris Caselden wrote: > Particularly in Windows, how do create installation packages for > python scripts? I've noticed that PyOpenGL and PyGame use a pretty > nice installer, and some games I've seen install and run without even > needing python installed. How is this done? First you need to create an executable, which gets around the need for a separate python installation - check out py2exe: starship.python.net/crew/theller/py2exe/ For an easy and free installer try Inno Setup: http://www.jrsoftware.org/isinfo.php From my at mail.ru Wed Sep 3 08:26:00 2003 From: my at mail.ru (Kerim) Date: Wed, 3 Sep 2003 16:26:00 +0400 Subject: test passed Message-ID: <3f55ddda@shknews01> Kerim From uce at ftc.gov Sat Sep 20 13:40:39 2003 From: uce at ftc.gov (Gordon Airport) Date: Sat, 20 Sep 2003 13:40:39 -0400 Subject: Mutable strings Message-ID: <xhCdnSW6Do2IDPGiU-KYvQ@comcast.com> Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently interchangeable in all circumstances (as long as they're paired) so there's no overloading to muddy the language. Of course there could be some interesting problems with current code that doesn't make a distinction, but it would be dead easy to fix with a search-and-replace. And which would be the default return type for functions returning strings... It looks like there are ways of handling this by digging around in the modules for more basic types, but it would be much nicer to have it available at 'user level'. From __peter__ at web.de Wed Sep 10 03:49:00 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 Sep 2003 09:49:00 +0200 Subject: How to instatiate a class of which the name is only known at runtime? References: <mailman.1063135996.15871.python-list@python.org> Message-ID: <bjml1l$fd9$00$1@news.t-online.com> Marco Herrn wrote: > 1. How to do the import? I didn't find a way to give a string to the > import statement. > > 2. How to write such code to instantiate? Off topic: This thread like some others is spread over a few toplevel entries in my newsreader (KNode 0.7.2). Is this a bug? Anyway, putting it all together: import sys def getClass(classname, modulename): try: module = sys.modules[modulename] except KeyError: module = __import__(modulename) return getattr(module, classname) print getClass("WichmannHill", "random") print getClass("WichmannHill", "random")() Peter From interstar at postmaster.co.uk Sun Sep 21 09:09:38 2003 From: interstar at postmaster.co.uk (phil) Date: 21 Sep 2003 06:09:38 -0700 Subject: python cgi problem with method = post References: <d7825a3e.0309191202.dc02042@posting.google.com> Message-ID: <d7825a3e.0309210509.75748d8e@posting.google.com> (hopefully) any answers? ... interstar at postmaster.co.uk (phil) wrote in message news:<d7825a3e.0309191202.dc02042 at posting.google.com>... > This is a quick plea on something that has me stumped. > > I have a python script importing "cgi" > > I developed my script on a local machine using method = get for > uploading form data. > > My code worked locally and on the hosting service I'm using. > > I changed to using method = post > > On my local machine this change works transparently. > > On my hosting service's machine, all the values that the form returns > to the script are now empty. > > So, I don't expect anyone to be able to answer this ... but what > *kind* of thing should I be looking for? Is it to do with versions of > python (2.1.3 locally, 2.2 remotely) or "cgi"? Or the webserver (I'm > using Apache on Debian locally, I suspect my host is Apache on Red Hat > 7.1) > > Is it something I haven't thought of? > > cheers > > phil jones From pnu at ukfsn.org Thu Sep 25 11:55:44 2003 From: pnu at ukfsn.org (Peter Nuttall) Date: Thu, 25 Sep 2003 16:55:44 +0100 Subject: send email In-Reply-To: <003101c3836b$56b72b90$1603a8c0@pc22> References: <338366A6D2E2CA4C9DAEAE652E12A1DEBF99AB@au3010avexu1.global.avaya.com> <003101c3836b$56b72b90$1603a8c0@pc22> Message-ID: <200309251655.44478.pnu@ukfsn.org> On Thursday 25 Sep 2003 2:45 pm, Alberto Vera wrote: > Thanks for your reply. > > I'd like to explain the problem to get a better idea about this. > > A python program check every minute if a value is 0 in a register on a > database. In this case using Python, it'll send an email. > I am not sure how to do the checking part but the email part would look like this: # this module is for sending email import smtplib #this module is needed for making message-IDs #change message string to the message you want #no longer than 78 letters message = 'test message' #adds headers to email #change these to what you want fromaddr=raw_input('what is the from address ') toaddrs=raw_input('what is the to address ') subject=raw_input('what is the subject ') sever=raw_input('what is the smtp sever you are using ') timesend=strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) #msg-id maker #change lupin to the name of your computer setime=localtime() x=0 msg_id='' while x<5: msg_id=msg_id+str(setime[x]) x=x+1 msg_id = msg_id + '@lupin' finalmessage = 'From: '+fromaddr +'\r\n'+ 'To: '+toaddrs finalmessage = finalmessage +'\r\n'+ 'Subject: '+ subject +'\r\n' + 'Date: ' + timesend finalmessage = finalmessage + '\r\n' +'Message-ID: ' + msg_id + '\r\n' + '\r \n' +message #code for sending email server = smtplib.SMTP(sever) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, finalmessage) server.quit() this code is chunky and will need changing to just what you want. look at the smtplib docs, the rfc2822 standard (email), and what Riccardo Galli had to say about my email program pete -- Someone esle can help you better than I can. Every time I think that perhaps we are an advanced race, I turn around and read ramblings on Slashdot, and realize I was wrong. From peter at engcorp.com Wed Sep 17 09:32:15 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Sep 2003 09:32:15 -0400 Subject: tuples vs lists References: <bk7eo9$g4g$1@bagan.srce.hr> <9egemvkhp2s55horjr9dfveml22158d62g@4ax.com> <bk7lfj$v5p$1@bagan.srce.hr> <3F67606B.C9A89EF3@engcorp.com> <bk7nlb$5jp$1@bagan.srce.hr> <3F676AAB.92479235@engcorp.com> <bk9h4m$q3p$1@bagan.srce.hr> Message-ID: <3F68625F.984871CE@engcorp.com> Ivan Voras wrote: > > Peter Hansen wrote: > > Ivan Voras wrote: > > >> I know that. I was just wandering if they also behave faster. Lists > >> are only interesting to me in case I need mutability. > > > > I'd suggest you have that backwards. Lists should _always_ be > > interesting > > to you. Tuples should be interesting only in the case where you need > > *immutability*. > > I disagree. :) I would always use tuples except when I explicitely need > mutability. That doesn't meen that I would intentionaly (badly) restructure > code just to use tuples, only that in many cases my structures don't need to > be modified. That's your personal choice, I suppose, and I won't try any more to dissuade you any more except to point out that most Python programmers, I believe, do not see tuples as their first choice, but use them only in certain special cases. I could be wrong. It happens. ;-) -Peter From p at d.com Fri Sep 12 07:50:13 2003 From: p at d.com (pd) Date: Fri, 12 Sep 2003 12:50:13 +0100 Subject: Web server with Python In-Reply-To: <tnr1mvgnt45urvu6n4q6dso3eto73hfr1m@4ax.com> References: <tnr1mvgnt45urvu6n4q6dso3eto73hfr1m@4ax.com> Message-ID: <1063367412.97175.0@lotis.uk.clara.net> How about skunkweb? I haven't used this, in fact I'm only just getting into python at the moment. Perhaps someone with experience can comment on this app... To quote the site, skunkweb ... "is an extensible, scalable and easy to use application server written in Python" hth Paul. p3d AT yahoo dot co dot uk Patrick Useldinger wrote: > Hi all, > after my unsuccessful try to run Apache 2 with mod_python and Python > 2.3, I am looking for an alternative approach. > My aim is to write a small web-based application: > > Python > - the solution must be based / usable on Python 2.3 > > Portability > Targeted plaforms are > - Windows 2000 Server > - Windows XP Pro > - AIX 5.1 > > Webserver: > - supporting up to 50 concurrent client connections > - must be able to use Python 2.3 to create dynamic pages > I can think of 3 alternatives to Apache: > - Medusa > - Twisted > - Zope > Which one is the easiest to work with? Which one is known to work on an > AIX 5.1 platform, for instance? > > Persistent storage > - Is ZODB easily usable from outside Python, i.e. to produce reports > without reverting to programming? > - Is MySQL with Python a good combination? > > > Regards, > -PU From lk at digicart.hu Fri Sep 19 04:55:02 2003 From: lk at digicart.hu (Ladvánszky Károly) Date: Fri, 19 Sep 2003 08:55:02 GMT Subject: Access to Win API Message-ID: <d541d61d12758a2b45ea1de78809beac@news.meganetnews.com> What is the best way to access Win API functions that are not present in the various extension packages. Is writing a C extension the only solution? Thanks for any help. K?roly From mpeuser at web.de Thu Sep 4 16:06:42 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 4 Sep 2003 22:06:42 +0200 Subject: Tkinter Text widget getting too slow References: <ba1e306f.0309030713.ef2ec4a@posting.google.com> <bj5b4g$jtg$1@news.hananet.net> <eoselvguf3hvie3s95kjndhtuno0jiu09s@4ax.com> Message-ID: <bj861h$hh5$06$1@news.t-online.com> "Christos TZOTZIOY Georgiou" <tzot at sil-tec.gr> schrieb im Newsbeitrag news:eoselvguf3hvie3s95kjndhtuno0jiu09s at 4ax.com... > On Thu, 4 Sep 2003 03:15:16 +0900, rumours say that "Changjune Kim" > <juneaftn at REMOVETHIShanmail.net> might have written: > > >(I'm interested to see his "extremely fast" text widget, too) > > Notice that Michael Peuser described an "extremely fast" "binary > editor"; I assume a dual view (hex / chars) one. This is not a text > widget --you don't have to account for line feeds and variable width > characters :) Exactly! Most of the time of general text edit or table widgets stays in .font.measure() You will get an immediate speed up if you use fixed size fonts and just use the string length for computations. I am looking for a postable short version of my editor (I remember I started with something less 100 lines. It grew of course ;-) Maybe I even should install a nice homepage - if I had the time... Kindly Michael P From wweexxsseessssaa at telus.net Sun Sep 7 11:56:07 2003 From: wweexxsseessssaa at telus.net (John Hall) Date: Sun, 07 Sep 2003 15:56:07 GMT Subject: Comments on Python Redesign References: <mailman.1062938172.20708.python-list@python.org> <87vfs4mxgg.fsf@voodoo.fake> Message-ID: <v4lmlvkav0fui6trcj39khbevvm9u1u8eh@4ax.com> On Sun, 07 Sep 2003 17:26:23 +0200, Lawrence Oluyede <raims at dot.com> wrote: >Zeldman's post about the new version: >http://zeldman.com/daily/0803a.shtml#validator When I view _this_ site in IE6, it has low-contrast text in a small size, which "view|text size" cannot change. -- John W Hall <wweexxsseessssaa at telus.net> Cochrane, Alberta, Canada. "Helping People Prosper in the Information Age" From job at webde-ag.de Wed Sep 17 10:25:16 2003 From: job at webde-ag.de (Joerg Beyer) Date: Wed, 17 Sep 2003 14:25:16 +0000 (UTC) Subject: ANN: script to visualize python profiling data with kcachegrind References: <bk9kok$7nh$2@news.web.de> <87k787zely.fsf@pobox.com> Message-ID: <bk9qsc$8ol$1@news.web.de> John J. Lee <jjl at pobox.com> wrote: > Much more important, we can now generate lots of pretty graphics from > our Python code ;-) my graphs dont fit on a single page of paper - if you find a nice way to print the graphviz graphs on many pages, please let me know. Joerg -- Simplicity is prerequisite for reliability. Edsger W. Dijkstra From cartermark46 at ukmail.com Thu Sep 25 04:49:31 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 25 Sep 2003 01:49:31 -0700 Subject: getting a value from a web-page References: <mailman.1064454334.1269.python-list@python.org> Message-ID: <d3c9c04.0309250049.2f06b7d5@posting.google.com> > Is it possible to get a row from a text-file? This text-file is located > in a web page. I'm not sure exactly what it is you are trying to achieve, but you might be able to use the urllib() module to download the file. I recall the existence of a module which can efficiently extract specified rows from a text file - but, alas, I don't recall its name. But it wouldn't be strictly necessary, anyway. > And a value from an excel located in a web-server? (Sheet1!cell A1) Do you mean an excel file located on your server, or somebody else's server? If it is on your server, you could manipulate the file directly using Mark Hammond's excellent win32all: http://starship.python.net/crew/mhammond/ A typical piece of python code to manipulate Excel is: # this example starts Excel, creates a new workbook, # puts some text in the first and second cell # closes the workbook without saving the changes # and closes Excel. This happens really fast, so # you may want to comment out some lines and add them # back in one at a time ... or do the commands interactively from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 xlApp.Workbooks.Add() xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!' xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!' xlApp.Close(SaveChanges=0) xlApp.Quit() del xlApp # raw_input("press Enter ...") From lk at digicart.hu Thu Sep 18 08:30:52 2003 From: lk at digicart.hu (Ladvánszky Károly) Date: Thu, 18 Sep 2003 12:30:52 GMT Subject: Closures in python References: <9caba98e.0309180208.692e9b68@posting.google.com> Message-ID: <c62bb15f8a159c4bd7d96c5f1a5d96e7@news.meganetnews.com> Try this. def f(n): return n*2 def t(fnc_prm, n): return fnc_prm(n) t(f, 2) I hope it helps. K?roly "Kasper B. Graversen" <kbilsted at it-c.dk> az al?bbiakat ?rta a k?vetkezo h?r?zenetben: 9caba98e.0309180208.692e9b68 at posting.google.com... > Having played with Smalltalk for the past month, I'm getting used to > passing code as arguments to methods... how easy is it to do this in > python? I haven't seen any recent postings on this subject here... > > \kasper From rganesan at myrealbox.com Fri Sep 5 04:27:42 2003 From: rganesan at myrealbox.com (Ganesan R) Date: Fri, 05 Sep 2003 13:57:42 +0530 Subject: newbie question about dictionnary ? References: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Message-ID: <ouoexzbpxd.fsf@andlx-anamika.cisco.com> >>>>> "Sophie" == Sophie All?on <alleon at club-internet.fr> writes: > for doing this I thought the dictionary was excellent but the key is a > string while I want it > to be the 2 points forming the edge ? How to do it ? The key can be any immutable object. So key can be a tuple. For example you can do ------------------------------ mydict = {} mydict[((1,2),(2,3))] = ... ------------------------------ You can even use your own class as a key. So to make it more readable, you can do something like --------------------------------------- class Edge: def __init__(self, point1, point2): self.point1 = point1 self.point2 = point2 p1 = (1,2) p2 = (2,3) e = Edge(p1, p2) mydict[e] = ... --------------------------------------- You get the idea :-) Ganesan -- Ganesan R From dave at nullcube.com Tue Sep 30 23:50:44 2003 From: dave at nullcube.com (Dave Harrison) Date: Wed, 1 Oct 2003 13:50:44 +1000 Subject: "for" with "else"? In-Reply-To: <f%reb.10797$NX3.1826@newsread3.news.pas.earthlink.net> References: <bkuqmu$ajv$1@ctb-nnrp2.saix.net> <bkuru4$532$1@news.wrc.xerox.com> <vn61legdn9jf56@news.supernews.com> <2c9knv86m1il4ajng85655dm7u5j5b992i@4ax.com> <vnkds7nbjf8420@news.supernews.com> <f%reb.10797$NX3.1826@newsread3.news.pas.earthlink.net> Message-ID: <20031001035043.GA2564@dave@alana.ucc.usyd.edu.au> Andrew Dalke (adalke at mindspring.com): > John Roth: > > I don't see what exceptions have to do with it. There are three > > special ending cases: with break, empty sequence and sequence > > exhausted. Empty sequence is the only one that isn't handled easily. > > Could you give an example of when you would actually use an > 'empty_sequence' in the real world? It's never been a problem > for me (that I can recall) where that distinction was important. Mmm, I think I agree with Andrew here. In the event that you want to specifically check whether a sequence is empty wouldn't you want to simply make that an explicit discovery call ? eg. if (len(seq) > 1): for ... else: print 'No items in sequence' It makes more sense to me to have an explicit discovery of a lack of items, rather than have a situation where we have the implication that to loop over an empty sequence is incorrect. Dave From bogus@does.not.exist.com Wed Sep 10 15:37:38 2003 From: bogus@does.not.exist.com () Date: Wed, 10 Sep 2003 21:37:38 +0200 Subject: How to instatiate a class of which the name is only known at runtime? In-Reply-To: <200309091256.25160.gherron@islandtraining.com> References: <20030909193530.GA2218@darkstar.localdomain.fake> <200309091256.25160.gherron@islandtraining.com> Message-ID: <20030910193738.GB2136@darkstar.localdomain.fake> Hi, On Tue, Sep 09, 2003 at 12:56:25PM -0700, Gary Herron wrote: > The imp module has what you want. I already found the imp module and thought it was what I was searching for, but it didn't work to me as I expected. > find_module(name[, path]) > Try to find the module name on the search path path. That didn't work, because I didn't know how to specify the path. It always said something about "ImportError: No frozen submodule". > load_module(name, file, filename, description) > Load a module that was previously found by find_module() I also tried this, but didn't know how to use it. I didn't know what the parameters mean and the doc wasn't verbose enough to me. But the way Nick and Chad pointed to me are totally perfect in my case. So I will use these. Marco -- Ein fester Satz an Vorurteilen ist ausgesprochen praktisch. Er erspart einem das Nachdenken. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From lists at webcrunchers.com Sun Sep 7 19:42:54 2003 From: lists at webcrunchers.com (John D.) Date: Sun, 7 Sep 2003 16:42:54 -0700 Subject: Python web site redesign -thoughts Message-ID: <v03110702bb816e29759d@[192.168.0.2]> After reading all the posts about the web site redesign I have some thoughts on ways to reduce the stresses here. The web site has at least three very different components: Appearance Content Coding The skill sets are different enough they might best be done by three different groups with expertise in each. The artists are in the first, the planners who decide what the site should contain in the second, and the people who decide how much CSS/XHTML/script/etc. go in it in the third group. To grasp what the site should be like, I'd ask: what groups should it serve? Developers/programmers? Media? Curious people not yet using Python? Bug reporters? What do each of these groups seek? What do people actually visit the site for? I use the Python web site frequently, almost always to use the online manuals (which I often find frustrating), and occasionally to download the language. "Opinions are like assholes -everyone has one." From FBatista at uniFON.com.ar Fri Sep 5 15:34:20 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 5 Sep 2003 16:34:20 -0300 Subject: Why python??? Message-ID: <A128D751272CD411BC9200508BC2194D03382EBD@escpl.tcp.com.ar> #- I don't think so much Python will improve our world. There #- are strong forces #- (not only $$$) enforcing the use of other languages like #- Java (the COBOL of #- the 21st century), C++, C# (both quite similar to Java), a #- little bit PHP 4 #- here and there and - of course! - still C (the machine #- independent assembly #- language). #- #- If you ever want to use your programming skills to earn #- money, become expert #- in one of those. I seem to hear somebody talking about Linux back in 1993... . Facundo From shane at zope.com Thu Sep 11 14:50:02 2003 From: shane at zope.com (Shane Hathaway) Date: Thu, 11 Sep 2003 14:50:02 -0400 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <3F60B545.6030100@sci.fi> References: <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <3F60B545.6030100@sci.fi> Message-ID: <3F60C3DA.6070409@zope.com> [Moved to python-list at python.org, where this thread belongs] Harri Pesonen wrote: > But my basic message is this: Python needs to be made thread safe. > Making the individual interpreters thread safe is trivial, and benefits > many people, and is a necessary first step; making threads within > interpreter thread safe is possible as well, at least if you leave > something for the developer, as you should, as you do in every other > programming language as well. Lately, I've been considering an alternative to this line of thinking. I've been wondering whether threads are truly the right direction to pursue. This would be heresy in the Java world, but maybe Pythonistas are more open to this thought. The concept of a thread is composed of two concepts: multiple processes and shared memory. Supporting multiple simultaneous processes is relatively simple and has proven value. Shared memory, on the other hand, results in a great number of complications. Some of the complications have remained difficult problems for a long time: preventing deadlocks, knowing exactly what needs to be locked, finding race conditions, etc. I don't believe we should force the burden of thread safety on every software engineer. Engineers have better things to do. At the same time, shared memory is quite valuable when you're ready to take on the burden of thread safety. Therefore, I'm looking for a good way to split a process into multiple processes and share only certain parts of a program with other processes. I'd like some form of *explicit* sharing with a Pythonic API. Imagine the following Python module: import pseudothreads data = pseudothreads.shared([]) def data_collection_thread(): s = get_some_data() data.append(s) for n in range(4): pseudothreads.start_new_thread(data_collection_thread) In this made-up example, nothing is shared between threads except for the "data" global. The shared() function copies the list to shared memory and returns a wrapper around the list that prevents access by multiple threads simultaneously. start_new_thread() is a thin wrapper around os.fork(). Each pseudothread has its own global interpreter lock. I wonder whether others would consider such a thing valuable, or even feasible. :-) Shane From sholden at holdenweb.com Thu Sep 11 16:15:44 2003 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 11 Sep 2003 16:15:44 -0400 Subject: FIFO problems In-Reply-To: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624506@stpmsg00.corp.fairisaac.com> Message-ID: <CGECIJPNNHIFAJKHOLMAAEJKGPAA.sholden@holdenweb.com> > -----Original Message----- > From: Pettersen, Bjorn S [mailto:BjornPettersen at fairisaac.com] > Sent: Thursday, September 11, 2003 3:33 PM > To: Steve Holden; python-list at python.org > Subject: RE: FIFO problems > > > > From: Steve Holden [mailto:sholden at holdenweb.com] > > > > "Duncan Booth" <duncan at NOSPAMrcp.co.uk> wrote ... > > > "Steve Holden" <sholden at holdenweb.com> wrote in > > > news:tJZ7b.67$o71.53 at news2.central.cox.net: > > > > [...] > > > > > > > > while 1: > > > > line = serverIn.readline() > > > > if not line: > > > > break > > > > del line[:-1] > > > > if line == "bla": > > > > do something incredibly interesting > > > > else: > > > > print line > > > > > > Untested is right. Your 'del' statement is a little bit too > > > destructive, or at least it would be if strings were mutable. > > > > > :-) Well, I can only remind myself that "the person who never > > made a mistake never made anything". > > > > > Here's my (equally untested) alternative: > > > > > > for line in serverIn: > > > line = line[:-1] > > > if line == "bla": > > > do something incredibly interesting > > > else: > > > print line > > > > > > > Unfortunately this doesn't include the end-of-file test [...] > > .. the iterator doesn't? > No, my brain doesn't. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Interview with GvR August 14, 2003 http://www.onlamp.com/python/ From jroznfgre at jngpugbjreQBGbet.cy Mon Sep 15 07:13:33 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Mon, 15 Sep 2003 13:13:33 +0200 Subject: caching the sql queries References: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> <mailman.1063623379.20087.python-list@python.org> Message-ID: <ql7bmvonghumdt5qkcn06bigpaa4g7m6rm@4ax.com> On Mon, 15 Sep 2003 12:55:15 +0200, "Luca Calderano" <calderano at sgaspa.it> wrote: >>Is there any equivalent of caching sql queries for Python like ADOdb >>for PHP? (For those who did not hear about ADODb and its feature : >>http://phplens.com/adodb/caching.of.recordsets.html) > >The Only way is using Com What do you mean? -- JZ From newsgroups at jhrothjr.com Mon Sep 8 20:42:47 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 8 Sep 2003 20:42:47 -0400 Subject: Python Port to Swiss Ephemeris (swe_houses) Bug Report/Workaround References: <734b753f.0309081421.1a1e180@posting.google.com> Message-ID: <vlq8gbru2981c8@news.supernews.com> The problem appears to be in the _wrap_swe_houses function. In the following routine (about halfway down the function) if (myhsys==71) ohcusps=PyList_New(37); else ohcusps=PyList_New(13); for (i = 0; i < myhsys; i++) { PyObject *otmp = PyFloat_FromDouble(myhcusps[i]); PyList_SetItem(ohcusps,i,otmp); } the if statement is incorrect. It will iterate 71 times, while it should iterate either 13 or 37 times, depending on the value of the house system paramter. This will overlay memory, causing all kinds of not very interesting problems. You need to report this to the author. John Roth "Dave" <bluheaven2 at yahoo.com> wrote in message news:734b753f.0309081421.1a1e180 at posting.google.com... > ======================================================== > Python Port to Swiss Ephemeris (swe_houses) Bug Report/Workaround > ======================================================== > > I don't know if anyone else has had programming problems with > the Python Port to the Swiss Ephemeris in the vault, but I have > just encountered an 'index error' bug caused by using the > swe_houses function. I did everything I possibly could think of > to figure out why I was getting an 'index error' in one of my loops > which happened to immediately follow the use of the swe_houses > function. After trying everything under the moon, I discovered that > when I deleted the house calculation that preceded the loop, it > worked fine. It didn't even matter whether the loop had anything > to do with the swe_house calculation or data that it returned. > The use of that function in the program completely disabled the > use of any loop following the use of the function by invoking an > 'index error' saying the list assignment is not possible. > > I wondered if it was a Python language bug, so I removed my > Python 2.2.2 and upgraded to 2.2.3, and the bug still existed. > Then I spent the better half of a day trying everything under > the sun to get around the error. The first very early on solution > to the problem was quickly discovered since the problem > apparently goes away as soon as you try to figure out what is > going wrong with your loop. Any programmer's first inclination > when debuging a loop would be to throw a few print statements > in there to view the values of the variables. Well, it turns out, > just the simple use of a print statement causes the bug to go > away in >IDLE<. I have no idea why, and it boggles my mind > why including the statement "Print '' " somewhere after the > swe_house calculation would stop the bug. > > Anyway, so, the typical programmer using the Python Port > and IDLE will quickly solve this apparent 'index error' problem > when they go throwing in print statements to figure out what > is causing the problem. > > BUT, if you however want to run your script at the command > prompt using the DOS window, the print statement won't solve > the problem, and you will continue getting an 'index error' > after your house calculation. After trying every possible > combination of things to do in a loop to try to work around > the bug for the command prompt, I discovered that there is > nothing you can do to reformat the loop to make it work like > a normal loop. > > The immediate problem in an astrological program doesn't > have to do with the fact that it disables the use of a loop > after using the function. The immediate problem is shown > when you attempt to manipulate or compare the data returned > from the swe_houses calculation. Not only does it disable the > use of a loop after house calculation, but the data that it returns > appears 'corrupt' in that when you attempt to compare it to > values to determine the degrees & signs, it will give you the > same index error again. > > For example, here is a simple house calculation: > > HouZodDegs = swe_houses(julday, lat, lng, 'k') > <A loop after this statement will produce below error> > "IndexError: list assignment index out of range" > > So, not only do you have problem with a loop after this > calculation, but when you try to evaluate the returned data, > you will also get this error (even if you're not manipulating > or evaluating any lists at the time). > > I also found out that you CAN compare the apparently > corrupt house degrees returned in the function as long as > your comparison is LESS THAN the returned zodiac degrees. > Otherwise, it will give you the index error. For example, > if you put these statements after your calculation: > > if HouZodDegs[0] < 0: Signs.append('ar') > if HouZodDegs[0] < 360: Signs.append('ar') > > you won't get an error for the first one, but you will get > an error for the second. Why? *shrug* These are just > the facts I'm reporting, and it's up to someone else to > figure out what is causing the problem (if they want to > spend the time). > > So, any statement evaluating the data returned from the > swe_houses function must be LESS THAN the zodiac > degrees returned. And since the results will vary from > anywhere within 360 degrees... some quite small and > some quite large, there is no way to evaluate the data > without getting the error. > > So, where is the precious workaround you said you found? > Well, after a day of reformatting the loops and reformatting > the evaluations, I figured out there is no format that will > not produce the error. In order to calculate the houses > in a program, you will of course need to compare the > values of the results with other numbers, and in the course > of doing this, the results will always eventually be LESS > THAN a certain value you specify. There is no workaround > to this to prevent it from erroring. > > SO, once I figured out that the error was inevitable, I started > experimenting with the TRY command... and trying to handle > the error as it happens in the program. I then figured out that > it was possible to figure out what sign the HouZodDegs was > in based upon where it errored in a list of evaluations. If > it errored on a certain interval, you could then determine > which sign was on the house cusp. It worked! > > Then I found out that I don't even need to really use this loop > for the meat of what I was doing. I found out that the way > to "beat the bug" was to just acknowledge it, let it go, and > then go on with the program. So, I figured out that all you > need to do is put the following code after your house > calculation statement: > > firstdegree = HouCspDegs[0] > try: > if firstdegree < 361: bug = 1 > except: bug = 0 > > The above code assigns the first house cusp degree to the > variable 'firstdegree'. Then it trys to evaluate it against a > value which it most definitely will be less than (361). If it > can do this, it assigns 'bug' to 1, but if it can't do it (it won't > be able to do it!) then it will assign 'bug' to 0. Now that you > have assigned 'bug' to 0, you will not have any more index > errors, and you can manipulate/evaluate the rest of the > house results. This workaround works in both IDLE and the > command prompt. The print workaround only will work > in IDLE. As to why these workarounds work, I have no idea, > but they do. I would like to hear from anyone who have had > similar problems using the Python Port to the Swiss > Ephemeris... or anyone else who would like to explain why > these workarounds work. Or finally anyone who actually > knows a way to get rid of the bug altogether. Thanks, > and I hope I saved someone a day of debugging with > this post. -Dave From sylphaleya at hta.fhz.ch Tue Sep 9 10:20:09 2003 From: sylphaleya at hta.fhz.ch (Manuel Huesser) Date: Tue, 9 Sep 2003 16:20:09 +0200 Subject: Unicode Newbie Message-ID: <20030909162009.0247ce9d.sylphaleya@hta.fhz.ch> The unicode function implies that you only can use 2 ** 16 chars (unichr supports only this range) but with a given encoding e.g. unicode(",,,", "utf-8") i should be able to encode up to 2** 31 chars. "\xfc\x12\x12\x12\x12\x12\x12" is an example for a 7 byte utf-8 string. But on encoding i get the following error: UTF-8 decoding error: unsupported Unicode code range Is there any possibility to do the job? Manuel From hans at zephyrfalcon.org Mon Sep 29 16:43:45 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Mon, 29 Sep 2003 16:43:45 -0400 Subject: write to log file In-Reply-To: <bla3fj$5ee$1@news.uni-kl.de> References: <bla3fj$5ee$1@news.uni-kl.de> Message-ID: <3F789981.5060508@zephyrfalcon.org> Tom wrote: > Hi, > I have a log file and of course I want to add the new information to the > end of that log file. Unfortunately I always delete the old information > and only append the current info. > > Right now I do it like this: > I call a module which consists of a class and a function. It actually > doesn't matter, but I just included it for the sake of completeness. > The module looks like this: > > class log_C: > def errorlog(self, filename, Data, d): > LogFile = file(filename, 'w') > ErrorInfo = Data[d+1] > LogFile.write(ErrorInfo) > LogFile.close() > > How can I add the new info without deleting the old info? > I tried the modes 'a' and 'a+' but they both didn't work. Actually the > data was totally unreadable! It was kind of messed up. I don't know why. The following works for me: >>> f = open('c:/temp/test.txt', 'w') >>> for x in ('fee', 'fi', 'fum', 'fo'): ... print >> f, x ... >>> f.close() >>> g = open('c:/temp/test.txt', 'a+r') >>> print >> g, 'slag-blah' >>> g.close() >>> file('c:/temp/test.txt').readlines() ['fee\n', 'fi\n', 'fum\n', 'fo\n', 'slag-blah\n'] HTH, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From jepler at unpythonic.net Tue Sep 30 12:10:04 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 30 Sep 2003 11:10:04 -0500 Subject: Is this is bug or something change in Python 2.3 In-Reply-To: <200309300854.42105.spatel@landrum-brown.com> References: <200309300854.42105.spatel@landrum-brown.com> Message-ID: <20030930161004.GB12344@unpythonic.net> To expand on my earlier post, here's the entry from the NEWS file about this change: What's New in Python 2.3 alpha 2? ================================= *Release date: 19-Feb-2003* Core and builtins ----------------- [...] - sys.path[0] (the directory from which the script is loaded) is now turned into an absolute pathname, unless it is the empty string. (SF patch #664376.) However, the part about 'is the empty string' seems to be false, or was perhaps modified by a later change: $ python2.2 x.py '' $ python2.3 x.py '/net/filesrv1/sd3a/users/jepler' Jeff From newsgroups at jhrothjr.com Mon Sep 8 16:52:38 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 8 Sep 2003 16:52:38 -0400 Subject: Why the 'self' argument? References: <slrnblh5ru.nd5.gstaniak@inka.zagiel.pl> <vlh7otscuo8gb1@news.supernews.com> <3f58a2bd$0$156$a1866201@newsreader.visi.com> <vlhba85atlte07@news.supernews.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <vlhidvcpq9a980@news.supernews.com> <qpOW/ks/KnRV089yn@the-wire.com> <vlhtm1bmc7m295@news.supernews.com> <fc08a59c.0309060830.623d31c7@posting.google.com> <Ucp6b.3992$ZB4.3874@reader1.news.jippii.net> <3f5a2260$0$166$a1866201@newsreader.visi.com> <TRr6b.4056$ZB4.1410@reader1.news.jippii.net> <vlpeq9jko1l6b0@news.supernews.com> <7T47b.4753$ZB4.113@reader1.news.jippii.net> Message-ID: <vlpr14kfehrn46@news.supernews.com> "Harri Pesonen" <fuerte at sci.fi> wrote in message news:7T47b.4753$ZB4.113 at reader1.news.jippii.net... > John Roth wrote: > > > "Harri Pesonen" <fuerte at sci.fi> wrote in message > > news:TRr6b.4056$ZB4.1410 at reader1.news.jippii.net... > > > >>Grant Edwards wrote: > >> > >>>In article <Ucp6b.3992$ZB4.3874 at reader1.news.jippii.net>, Harri Pesonen > > > >>Also I think that the class members should be explicitly declared. In > >>general, it would be nice to have an option (like Option Explicit in > >>Visual Basic) so that you can't assign to variables that have not been > >>declared. It would probably make Python less error prone. > > > > I believe that is what __slots__ is for. That's run time rather than > > compile time, but at least it gives you the error on the statement > > that attempts to do an invalid assignment. > > Thanks guys, I hadn't heard of __slots__ before. Perhaps I am reading a > too old book. Of course, a compile time check would be better... __slots__ came in with 2.2 new style classes, and it's definitely an advanced feature. There's also some thought that it may not be the best way to do the job. > >>Also if > >>variable declarations could have the type, again some errors could be > >>detected at compile time. > > > > It's quite possible to add run time type checking to Python, at a > > significant cost in performance. See the descriptors material. > > I think that Python already has run time type checking. It does not > allow "a" + 1, for example. Actually, it doesn't. It has run time strong typing, which is a different thing. To me, at least, "type checking" implies a meta-operation, that is, something that is outside of the operation itself insuring that the correct types are used. In languages with static typing, that something is the compiler. Runtime type checking means that there is additional code somewhere that checks that the object you are trying to bind is of an allowable type; that code is basically supervisory in nature. > > There's been quite a bit of work on a compile time type checking > > system over the years, but it has never resulted in a proposal that could > > be agreed on. > > It would be quite simple to have "option explicit" like in Visual Basic, > I believe. Like the following: > > option explicit > var a = "asdf" > b = 1 # error at compile time > a = 123 > (var b, var c, var d) = (1, 2, 3) > e = "asdf" # error at compile time Things are not so simple. To do compile time type checking, the compiler has to know the actual type of the result of the expressions on the right hand side of the assignments. In a dynamic language like Python, that's not possible without very fundamental changes to the nature of the language. It's not a simple thing to do, and the fact that ML family languages manage to do it without having to have explicit type declarations (well, most of the time anyway) is a major achievement, IMO. The fact that Bicycle Repair Man manages to do it as well as it does for Python is an even more impressive achievement. John Roth > > Harri > From newsgroups at jhrothjr.com Sat Sep 27 11:08:53 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 27 Sep 2003 11:08:53 -0400 Subject: pythonwin from dos References: <3f731176.33482654@powernews.libero.it> <vn66jje743n725@news.supernews.com> <3f7591fe.1890578@powernews.libero.it> Message-ID: <vnba0l1m9ec50d@news.supernews.com> "Alberto Mantovani" <alberto.mantovaniNOSPAM at bologna.marelli.it> wrote in message news:3f7591fe.1890578 at powernews.libero.it... > On Thu, 25 Sep 2003 12:40:10 -0400, "John Roth" > <newsgroups at jhrothjr.com> wrote: > > > > > > >"Alberto Mantovani" <alberto.mantovaniNOSPAM at bologna.marelli.it> wrote in > >message news:3f731176.33482654 at powernews.libero.it... > >> hi, > >> how is it possible to run a python script in the pythonwin > >> environment from dos command line? > >> If I use the command "/run scriptname.py" and the pythonwin is already > >> opened I get error, so someone can help me? > > > >Why do you want to run it in Pythonwin? To run a script from > >one of the command lines, the correct command is: > > > > python scriptname.py parameters.... > > I know this, but my problem is to run the script in pythonwin from dos > when pythonwin is already opened. Look in the registry and find out how Pythonwin handles the command from the shell, then do the same thing. John Roth From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Sep 22 20:47:03 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 01:47:03 +0100 Subject: Thoughts on PEP315 Message-ID: <oalumvopu9afuhno85tbp2erl52rk9hht1@4ax.com> PEP315 (Enhanced while loop) suggests a syntax as follows... do: ... while condition: ... The motives are IMO good, but I don't like this solution. It replicates a problem with the C do loop (even though this is actually different to the C do loop). Imagine that you can see the following in a piece of code... statements1 while condition : statements2 The question is this - is this a new old-style while loop starting at this point, or is it the 'while' part of a new-style while loop? Given the truncated view typical of a single screenful of code, this could be far from clear. 'statements1' could follow after an earlier 'do:', but it could equally follow after an earlier 'if ... :' or 'while ... :' or whatever. This is a situation where anyone who is unaware of the new 'do:' part (or who simply didn't think about it) could end up being confused by the 'while ... :' line. This is not an unusual situation when the C 'do' loop is used, simply because that loop is quite rarely used in practice - people don't expect it, so when people see... statements } while (condition); the tendency is to assume that either the semicolon is a mistake, or the while line is a conventional while loop with no body (not unusual in C code if the condition has side-effects). There are other issues. For example... do : ... while c1 : ... while c2 : ... Is the second 'while' line the start of a new loop, or is it a continuation of the first loop (a second exit point)? If it is a continuation, do you really potentially need to use a 'pass' to prepare for a second loop... do : ... while c1 : ... pass # to assert that the previous loop is ended while c2 : ... I basically think that this is too error-prone. When faced with a problem inventing new language syntax, IMO the first thing to do should always be to review other languages for existing solutions. Why re-invent the wheel? Here, I'll limit myself to alternate-to-while-loop structures which provide more flexibility than a basic while loop (so I'm excluding Pascals repeat-until, for instance, which is slightly different to but no more flexible than the while loop). First, ANSI Basic provides a generalised loop which is a bit more flexible - it allows both a precondition and a postcondition. do [while condition] ... loop [until condition] This can be useful in some situations, but it doesn't solve the PEP315 issue. The C for loop deserves a quick mention because it isn't just an integer for loop. The syntax is for (<initialisation>; <precondition>; <'increment'>) statement Because the <initialisation> and <increment> can be any legal C statements, the loop is quite flexible. Combined with the comma operator, for instance, it allows 'in-step' loops such as this array reverser... for (i = <first item index>, j = <list item index>; i < j; i++, j--) { temp = array [i]; array [i] = array [j]; array [j] = temp; } Once again, though, this doesn't solve the PEP315 problem. In terms of flexible loops, Ada is basically the Daddy. The mimimalist for is... loop ... end loop; But you can add a 'while' part or a 'for' part to the start... while condition loop ... end loop; for i in 1..10 loop ... end loop; for i in reverse 1..10 loop ... end loop; And in addition, you can use an 'exit when' line (in any of the cases above) to give essentially a conditional break... loop ... exit when condition; ... end loop; This last form finally handles the PEP315 problem. But Ada goes a little further. Suppose you have nested loops, and you want to exit more than just the innermost one? In Ada, you can name the loops and specify by name which one you want to exit... outerloopname: loop innerloopname: loop ... exit innerloopname when condition; ... exit outerloopname when condition; ... end loop; end loop; So what might be worth using in Python? I like the idea of an 'exit when' line, which is basically what the PEP315 'while' line gives, but I think a different syntax should be used. I would suggest that 'exit' in the Ada loop means essentially what 'break' means in Python now, except for the condition. So I would suggest the following as a possibility... while True : ... break if <condition> : ... This has no new keywords, but should be both clear and effective. The parser should expect a semicolon immediately after existing break keywords, so the distinction should be immediately clear to the Python parser. A 'continue if' might be considered as well. That is sufficient to handle PEP315 with no new keywords and without the 'is this a new loop?' confusion. Should the need for named loops ever be considered in Python, there is also an obvious place to put the name between the 'break' and 'if'. What about all those other loop ideas, though... 1. Combining a precondition with a postcondition (ANSI Basic)... No problem - just put the 'break if' at the end of the loop. It's not an 'until' postcondition, but who cares. If anything, having all loop conditions with the same 'sense' is more consistent. while True : ... break if <condition> : statements after loop 2. In-step looping (C for loop)... This is just syntactic sugar for a while loop anyway... setup1 setup2 while condition : statement increment1 increment2 My personal opinion is that there is some need for a more convenient iterate-over-integers, but this kind of stuff should normally be done as above. 3. Named loops (Ada)... Don't know. It may be a feature without a purpose. In the two and a half years when Ada was my main language, I don't remember ever using it. 4. Start-of-loop keyword which doesn't require a condition (Basic, Ada)... This is matched by the PEP315 'do', but is not actually necessary if you use 'break if' for the exit point - you can simply use 'while True :' to start the loop without ambiguity. But I admit it - the reason for going through the various languages is because I'm sick of being accused of trying to change Python into *. I don't think anyone can reasonably accuse me of trying to change Python into Basic, C and Ada at the same time (maybe I should find a way to get Prolog into the mix). Though it is slightly worrying that my preferred idea was adapted from one particular language. Still, traditionally I'm accused of trying to change Python into C, C++, Java, Pascal, Haskell or more recently C# so at least Ada will (if I remember right) make a change ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From jim-usenet at jimdabell.com Mon Sep 8 19:48:16 2003 From: jim-usenet at jimdabell.com (Jim Dabell) Date: Tue, 09 Sep 2003 00:48:16 +0100 Subject: Eureka! (Re: Comments on Python Redesign) References: <mailman.1062962051.23295.python-list@python.org> <bjibik$g3n$1@panix3.panix.com> <3F5CD10B.2020709@teksavvy.com> <200309072018.05589.dave@pythonapocrypha.com> <mailman.1063053974.13083.python-list@python.org> <3F5CF116.2F755AA6@engcorp.com> <3F5CFDA2.C947C3A2@alcyone.com> Message-ID: <Fe-dnXvQ4eBZiMCiRVn-gA@giganews.com> Erik Max Francis wrote: > Peter Hansen wrote: > >> * You can't tell ahead of time what site you are going to be >> redirected to. >> As a result, you lose complete freedom to choose whether or not you >> should >> follow the link. (Note for the imprecise: I didn't say you >> completely lose >> freedom, I said you lose complete freedom.) > > But you can't tell that any URL, even a long one that looks meaningful, > won't redirect you someplace you don't want to go. Even if it's what > you expected, there could be something on the page which potentially > does something malicious, like a Java bomb. > > It all comes down to trusting the person who's posting the URL, and that > doesn't change whether it's a tinyurl.com URL being posted or something > else. No. The crucial difference is that, if you can see the real URL, you don't have to trust the poster if you trust the website. I trust a URL pointing to the python.org domain won't redirect me to a malicious website, no matter who posts it. If said URL is obfuscated with tinyurl or similar, I only have the option of trusting the poster. -- Jim Dabell From anuradha.k.r at sify.com Fri Sep 26 06:15:39 2003 From: anuradha.k.r at sify.com (anuradha.k.r at sify.com) Date: 26 Sep 2003 03:15:39 -0700 Subject: server side socket program hangs Message-ID: <57efaf35.0309260215.5ddd5734@posting.google.com> hi, i am writing a socket program in python,both client side and server side.I've written the client side which is working perfectly fine(checked it against server program written in C).but as for my server program written in python it simply hangs.it does not show any error also.I've tried sample programs available .I don understand what the reason is as i am quite new to it. here is teh server side program: /////////////////////// from socket import * import socket import sys HOST = '' #any address PORT = htons(9999) #same port address as client try: s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) except socket.error: print 'socket not created' try: s.bind((HOST,PORT)) except socket.error: print 'error in bind' try: s.listen(5) except socket.error: print 'error in listen' conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() can someone tell me what the problem is? From jjl at pobox.com Fri Sep 12 10:14:57 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Sep 2003 15:14:57 +0100 Subject: mixing for x in file: and file.readline References: <rowen-222487.13545311092003@nntp1.u.washington.edu> <mailman.1063364898.12243.python-list@python.org> Message-ID: <8765jym6u6.fsf@pobox.com> Oren Tirosh <oren-py-l at hishome.net> writes: > On Thu, Sep 11, 2003 at 01:54:53PM -0700, Russell E. Owen wrote: > > At one time, mixing for x in file and readline was dangerous. For > > example: [...] > Yes. [...] > In Python 2.2 if you break in the middle of the loop the temporary > iterator object (xreadlines) is lost along with its readahead buffer, > leaving you at an unknown file position. The only things you can do are > to close the file or seek. In Python 2.3 the file object IS an iterator > (rather than HAS and iterator) so while the current file position is > undefined from a read/readline/tell point of view the iterator state is > still consistent so you can immediately use it in another for loop to > continue from the same position or even call its next() method directly. [...] Oh, sorry for the misinformation -- I thought the repeated-iteration and mixing-iteration-with-readline issues were the same, but clearly not. John From basile-news at starynkevitch.net Sat Sep 6 02:44:35 2003 From: basile-news at starynkevitch.net (Basile STARYNKEVITCH) Date: 06 Sep 2003 08:44:35 +0200 Subject: ANN: Guis 1.4 release (GTK2 scriptable widget server) References: <q5rsmnaok63.fsf@hector.lesours> <6e07b825.0309052123.7efebdb1@posting.google.com> Message-ID: <q5rfzjao1po.fsf@hector.lesours> >>>>> "yaipa" == yaipa h <yaipa at yahoo.com> writes: yaipa> Basile, Nice work, I don't know when I'll get a chance to yaipa> try it, but I like the model. I've been thinking as of yaipa> late, if you can have web servers why not GUI widget yaipa> servers? Guess I now know the answer. You can. yaipa> So when do we get the 'drag-n-drop' forms. ;^) You already have them: you just just have to code the appropriate initial script (Python or Ruby). The idea in Guis is that each application has (usually) an appropriate initial script (in Python or Ruby) which defines the functions (which initialize and manage the widgets) which are called by later protocol exchanges. So usually you define a start function (in Ruby or Python, inside the initial script) which realize your graphical user interface (creating windows, widgets, and putting callbacks..), and the first request from application to Guis is a call to this start function. Since Drag&Drop (DnD) is already existing in Gtk and since it is callable thru Ruby or Python you can have DnD, provided you code it in your script. See http://starynkevitch.net/Basile/guisdoc.html for more. -- Basile STARYNKEVITCH http://starynkevitch.net/Basile/ email: basile<at>starynkevitch<dot>net aliases: basile<at>tunes<dot>org = bstarynk<at>nerim<dot>net 8, rue de la Fa?encerie, 92340 Bourg La Reine, France From __peter__ at web.de Tue Sep 30 08:26:19 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Sep 2003 14:26:19 +0200 Subject: isNumber? check References: <mailman.1064916400.32187.python-list@python.org> Message-ID: <blbssu$oqs$01$1@news.t-online.com> Tony Meyer wrote: > I would think that: > """ > s = "123" > value = isNumber(s) > if value is None: > # do something that shows it's not a number. > # (obviously not raise a ValueError, because > # then there's no point using the function at > # all) > # continue program, with value in value, if needed. > """ > Would be a more logical way to do it. I would still prefer try: value = toNumber(s) except ValueError: # handle error > It's not. It was an example case showing that there isn't any need to > bother with regexs and the like if you don't want to - Python will do the > work for you. Assuming you trust the Python developers, you can trust > that it will correctly check that the value is convertible into a number, > and don't need to worry that you missed something in the regex (or > whatever). I wouldn't use regexes here, too. > A real function would have a docstring...this is only c.l.p... Everything that can be conveyed by the function name makes the code more readable. Consider def killTheBeast(beast): """ Does not actually kill the beast, but shows a grim face while hugging it """ (Sorry, couldn't resist) > The OP asked for a function called isNumber. I posted an example of one. If a suggested improvement changes the functionality, you could explain the name change to the OP. > The program snippet doesn't throw an exception at the end; your example > usage did. If the code was going to raise a ValueError if it couldn't be > converted, then it would be written differently; the OP didn't say that > that > was the case. The program flow is really: > - convert to number and return > - if an exception was raised then return None, signifying that no number > can be created > > Lots of the stuff written about Python talks about using exceptions for > code > control, as this does. This isn't C++. No, this isn't C, and one advantage, I think, is that you no longer need to check for special error values. (OK, I'm simplifying...) >> I can think of very few situations where None could actually >> be *used* instead of a numerical value. > > Why would you want to *use* None? It's simply the function signifying > that it couldn't convert the number. > >> > Note that "0" will come back as 0.0, though, because it >> > evaluates as False. It would be easy enough to special case that, if > necessary. >> >> This is a bug that demonstrates that your isInt()/isFloat() >> implementation is not even well suited to implement isNumber(). > > Rubbish. This is me not taking care of every little detail in example > code, > for the sake of brevity, but warning that that is the case. In any case, > it still correctly determines if the object can be converted to a number, > and > still correctly returns the number it is converted to. The only thing > that > is possibly incorrect is that it's a float instead of an int. As I said, > easily fixed. It is easily fixed in this trivial example. However, when you use a special value to signal an error in a sufficiently complex calling hierarchy, you end up testing for it too often for my taste. > You seem to have missed the whole point of the code snippet. The idea is > that you can use the conversion built into Python to check if a number can > be converted, without having to write code that checks yourself. Perhaps Maybe I stressed the points I did *not* like too much. Again, I agree with your no regexes policy. (Localization is a different story) > you would like this more? > > """ > def isNumber(s): > for f in [int, float,]: > try: > return f(s) > except ValueError: > pass > raise ValueError("Cannot convert to a number") > """ You're right, I like that. Now give it a decent name (e.g. strToNumber()) and we have finally reached consensus :-) > To me this doesn't seem as clear in explaining the concept, although it's > more like code I would actually use. This does return "0" as 0, and > raises > a ValueError is no conversion is possible. The point is that the concept, > which is what I was trying to convey, is the same. If you really don't > want the value returned, then you could just use: > > """ > def isNumber(s): > for f in [int, float,]: > try: > f(s) > except ValueError: > continue > return True > return False > """ I think I would build on previous work here: def isNumber(s): try: strToNumber(s) except ValueError: return False return True Peter From secun at yahoo.com Thu Sep 25 16:59:47 2003 From: secun at yahoo.com (SectorUnknown) Date: Thu, 25 Sep 2003 20:59:47 GMT Subject: Windows dialog box removal References: <MPG.19dbcef078a40b3d989688@news2.atlantic.net> <mailman.1064497835.7752.python-list@python.org> Message-ID: <MPG.19dccffd8ef62d0198968a@news2.atlantic.net> That works great. Thanks!!! In article <mailman.1064497835.7752.python-list at python.org>, dave at pythonapocrypha.com says... > On Thursday 25 September 2003 06:18 am, SectorUnknown wrote: > > I've written a Python script that runs a MS Windows program using popen. > > However, at the end of the Windows program, a dialog box appears and > > asks for the user to click on OK. > > > > Is there a way to have Python set focus on the dialog box and click OK > > so my script can continue? > > > > Does anyone have an example? > > I wouldn't be surprised if there's an easier or more correct way to do this, > but if you can reliably know the title of the window then the code below > should work (assuming you have ctypes installed): > > from ctypes import * > user32 = windll.user32 > > EnumWindowsProc = WINFUNCTYPE(c_int, c_int, c_int) > > def GetHandles(title, parent=None): > 'Returns handles to windows with matching titles' > hwnds = [] > def EnumCB(hwnd, lparam, match=title.lower(), hwnds=hwnds): > title = c_buffer(' ' * 256) > user32.GetWindowTextA(hwnd, title, 255) > if title.value.lower() == match: > hwnds.append(hwnd) > > if parent is not None: > user32.EnumChildWindows(parent, EnumWindowsProc(EnumCB), 0) > else: > user32.EnumWindows(EnumWindowsProc(EnumCB), 0) > return hwnds > > Here's an example of calling it to click the Ok button on any window that has > the title "Downloads properties" (most likely there are 0 or 1 such windows): > > for handle in GetHandles('Downloads properties'): > for childHandle in GetHandles('ok', handle): > user32.SendMessageA(childHandle, 0x00F5, 0, 0) # 0x00F5 = BM_CLICK > > -Dave > > From sketerpot at chase3000.com Fri Sep 12 12:18:28 2003 From: sketerpot at chase3000.com (Peter Scott) Date: 12 Sep 2003 09:18:28 -0700 Subject: Usenet posting wiht python References: <a26792eb.0309120243.7adb6cc6@posting.google.com> Message-ID: <659f82ff.0309120818.31ca4b65@posting.google.com> > How can I send a usenet posting from a python app? Usenet servers use NNTP, so I'd recommend nntplib, <http://www.python.org/doc/current/lib/module-nntplib.html>. It doesn't look too complicated, and there's example code in the docs. -Peter From richie at entrian.com Fri Sep 19 06:35:00 2003 From: richie at entrian.com (Richie Hindle) Date: Fri, 19 Sep 2003 11:35:00 +0100 Subject: file position *tell()* works different In-Reply-To: <LIAab.7544$9G2.6227@twister.southeast.rr.com> References: <13a533e8.0309190137.2df0cc60@posting.google.com> <LIAab.7544$9G2.6227@twister.southeast.rr.com> Message-ID: <gomlmv437217ej9vbeg5rs40no5fl9ikke@4ax.com> [Peter] > I wonder if the function *tell()* is not correctly implemented under win32. [M-a-S] > Anyway, you program works under Windows XP/Python 2.3 as expected: M-a-S, are you sure you saved test_data.txt with Unix line endings? I tested Peter's script under WinXP/Python2.3 as well, and it failed as expected (though with slightly different results): >pythonw -u peter.py Filepointer: 0 Filepointer: 8 Filepointer: 20 Filepointer: 31 Filepointer: 50 Filepointer: 0 Filepointer: 11 Filepointer: 22 Filepointer: 32 Filepointer: 50 -- Richie Hindle richie at entrian.com From eddie at holyrood.ed.ac.uk Fri Sep 5 14:38:47 2003 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 5 Sep 2003 18:38:47 +0000 (UTC) Subject: Coding Style: Defining Functions within Methods? References: <70df36e9.0309050837.1660cdf4@posting.google.com> Message-ID: <bjal7n$t2n$1@scotsman.ed.ac.uk> harry.pehkonen at hotpop.com (Harry Pehkonen) writes: >I have been defining new class methods when I'm trying to simplify >some code. But I'm thinking I should just define functions within >that method because they aren't useful from the outside anyway. >Example: >Before: >class Mess(object): > def complicated(self, count): > for i in count: > self.do_loop(i) > def do_loop(self, i): > ...whatever... >After: >class Cleaner(object): > def complicated(self, count): > def do_loop(i) > ...whatever... > for i in count: > do_loop(i) >The point is that do_loop is now not ``contaminating'' things. I >suppose do_loop could be __do_loop, but it would still show up in >places where I don't think it should (such as dir(Mess)). >Thoughts? Definitely useful, especially as the inner function can see the same variables as the outer (though I do keep getting bitten when I expect to be able update variables). Eddie From felix_mcallister at hotmail.com Mon Sep 15 09:53:25 2003 From: felix_mcallister at hotmail.com (Felix McAllister) Date: Mon, 15 Sep 2003 14:53:25 +0100 Subject: Win32 Com + ADO: How to compare the result of a recordset to 'nothing' Message-ID: <tvj9b.31786$pK2.53500@news.indigo.ie> Hi, When using win32com.client, how do you test for a 'nothing' com object as you can in VB? I have an example here when using ADO to loop over multiple recordsets returned from a query. I get the following error: Traceback (most recent call last): File "C:\dev\python\MySamples\dbtest.py", line 14, in ? rs.MoveFirst() File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 460, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: <unknown>.MoveFirst I'm assuming that after the result of rs.NextRecordSet is invalid somehow (it shouldn't be, BTW, as a similar loop runs fine in VB). In Perl, I'd just use : if (defined($rs).... Any help appreciated, Felix. The code is as follows: ###########################3 import win32com.client conn = win32com.client.Dispatch("ADODB.Connection") conn.ConnectionString = "Driver={SQL Server};Server=(local);Database=Test;Trusted_Connection=yes;" conn.Open() rs = conn.Execute("TestSPXML")[0] xmlString = "" while rs != None: rs.MoveFirst() # FAILS HERE ON THE SECOND ITERATION OF THE LOOP while not rs.EOF: xmlString = xmlString + rs.Fields[0].Value rs.MoveNext() rs = rs.NextRecordSet() print xmlString conn.Close() From achalk at XXXmagnacartasoftware.com Sat Sep 6 18:20:34 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Sat, 06 Sep 2003 22:20:34 GMT Subject: in CGI, how to include html pages? References: <20030906110544.78d7ea33.python@sarcastic-horse.com> <mailman.1062860351.26409.python-list@python.org> Message-ID: <S4t6b.220$9t2.198@newssvr23.news.prodigy.com> How about: htmlHeader = '''<html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta name="GENERATOR" content="Microsoft FrontPage 5.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>New Process ''' print htmlHeader "Nick Welch" wrote in message news:mailman.1062860351.26409.python-list at python.org... > On Sat, Sep 06, 2003 at 11:05:44AM -0400, python wrote: > > Hi- > > > > I'm writing some CGI stuff and I'm doing it in python to force myself to > > learn the language. Anyway, I want to include some html at the top of > > every page but I'm not sure how. > > > > If the header is in header.html, what is the python-ese way of printing > > that out in my html? > > > > Thanks for the help. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > f = file("header.html") > > for line in file: > print line, > > f.close() > > And of course you could easily write a function to wrap this so you > could just include("header.html"). > > HTH, > -- > Nick Welch aka mackstann | mack @ incise.org | http://incise.org > If you have a procedure with 10 parameters, you probably missed some. > From peter at engcorp.com Mon Sep 22 20:19:59 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Sep 2003 20:19:59 -0400 Subject: Slicing vs .startswith References: <3F6F12A1.3010702@bu.edu> <6e7b9822.0309221439.6dea760e@posting.google.com> <3F6F8306.1ABCC6D@engcorp.com> Message-ID: <3F6F91AF.63645AEA@engcorp.com> David Eppstein wrote: > > In article <3F6F8306.1ABCC6D at engcorp.com>, > Peter Hansen wrote: > > > Paul wrote: > > > > > > However, what if you don't want case sensitivity? For example, to > > > check if a file is a jpg, I do name[-3:].lower() == 'jpg'. This will > > > work with both foo.jpg and foo.JPG. > > > > > > Is this slower than name.lower().endswith('jpg')? Is there a better > > > solution altogether? > > > > Yes, of course. :-) > > > > import os > > if os.path.splitext(name)[1].lower() == 'jpg': > > pass > > > > That also handles the problem with files named "ThisFileIs.NotAjpg" > > being mistreated, as the other solutions do. ;-) > > I was about to post the same answer. One minor nit, though: it should be > > os.path.splitext(name)[1].lower() == '.jpg' Oops, thanks! I _always_ make that mistake. It just seems that if os.path.split() does not return any path separators in the components, then os.path.splitext() shouldn't return the extension separator... Luckily we have tests around here to catch that kind of thing. :-) -Peter From geoff at gerrietts.net Thu Sep 11 13:11:42 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 11 Sep 2003 10:11:42 -0700 Subject: 1.5 vs. 2x - build problem In-Reply-To: <3F608651.6080307@ghaering.de> <7af2fd5c1a70e3c6ce4fe1f8eee39b9b@remailer.frell.eu.org> References: <7af2fd5c1a70e3c6ce4fe1f8eee39b9b@remailer.frell.eu.org> <3F608651.6080307@ghaering.de> <7af2fd5c1a70e3c6ce4fe1f8eee39b9b@remailer.frell.eu.org> Message-ID: <20030911171142.GB2085@thoth.homegain.com> Quoting Fritz Wuehler (fritz at expires-200309.rodent.frell.eu.org): > I downloaded a tarball which doesn't compile. The error message > says I need python 2x but all I have is 1.5. Can I fix the > compatability problem and get it to work on 1.5? My experience has been that most (and not all!) of the applications that require Python 2.x, do it mostly for the sake of convenience. This means that they'll use func(*args, **kw) instead of apply(funcs, args, kw) or maybe mylist = [str(x) for x in yourlist] instead of mylist = map(str, yourlist) and x += 1 instead of x = x + 1 There are other features you'll find that don't work -- Python has gotten a lot more convenient since 1.5.2! -- but most of the time, the 2.x dependencies are convenience features. Some features are more difficult to port back than others, though. If you're dealing with something that (for instance) has unicode requirements, you're just not gonna be able to do what you need on 1.5.2. So the answer is: probably; I have only run across one app so far that I couldn't eventually port back to 1.5.2 at least well enough that it was running for me. That app was Pyana. It may or may not be easy. Quoting Gerhard H?ring (gh at ghaering.de): > On the other hand, you could invest the time and bring your > software/system up-to-date with Python 2.3. You can just install it in > /usr/local and leave your previously installed Python alone. > > FWIW I, for one, would reject any patches that'd add Python < 2.1 > compatibilty to my software. I wouldn't want to take one of my personal projects back to 1.5.2 and lose the additional expressive power that recent Pythons have given me, either. On the other hand, in my professional capacity, I have spent an assembled couple of months trying to port 200k lines of application code forward onto new versions of Python and Zope. It's going to take a couple weeks of QA and deployment work to get it all into place. On the other hand, it usually takes me an afternoon to backport someone else's extension code well enough that I can use it. Sometimes people aren't interested in the patches, sometimes they are. Sometimes I fail to produce them after making the changes. For my part, I feel bad for the next guy down the line in at least two of those cases. Many people have this cavalier "well just upgrade, wtf is wrong with you?" attitude, but it's often not as trivial as everyone would like to pretend. (Of course, sometimes it /is/ trivial, and if it is, you should do it.) --G. -- Geoff Gerrietts "Ordinarily he was insane, but he had lucid moments when he was merely stupid." --Heinrich Heine From bogus at invalid.tld Sat Sep 20 00:23:54 2003 From: bogus at invalid.tld (Jules Dubois) Date: Fri, 19 Sep 2003 22:23:54 -0600 Subject: bizarre behavior using .lstrip References: <681f9321.0309191607.4e8b858a@posting.google.com> Message-ID: <1ncwxni2hwzl5.2lpkd6rdz989$.dlg@40tude.net> On 19 Sep 2003 17:07:47 -0700, in article <681f9321.0309191607.4e8b858a at posting.google.com>, Pete Jereb wrote: >>>> s = 'chg conn_fee' >>>> print s > chg conn_fee >>>> print s.lstrip('chg ') > onn_fee > > Does this make any sense at all? where did the lead c in conn_fee go? It was removed, as you requested. lstrip('chg ') means remove every occurence of space, 'g', 'h', and 'c' from the front (left) of the string. >>>> print s.lstrip('chg') > conn lstrip('chg') stops stripping when it finds a character not in 'chg'. The space is the first character not 'chg' so that's where lstrip stops stripping. >>>> print s.lstrip('chg ') > onn lstrip('chg ') stops stripping when it finds a character not in 'chg '. The 'o' is the first character not in 'chg' so that's where lstrip stops stripping. > Not really sure what's causing this [...] As they said where I used to work, WAD: it Works As Designed. > [...] but it's making me change the > text parser I'm 600 lines into. It's not clear what you're trying to do. Do you want to remove all the leading space, 'g', 'h' and 'c' characters from the string, or do you want to remove the leading (exact) string "chg " as a whole? One way to remove the leading 'g', 'h', and 'c' characters from the front of the string first, and then remove spaces from the resulting string print s.lstrip('chg').lstrip() From peter at engcorp.com Sun Sep 21 11:42:11 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 21 Sep 2003 11:42:11 -0400 Subject: python cgi problem with method = post References: Message-ID: <3F6DC6D3.E6454738@engcorp.com> phil wrote: > > (hopefully) any answers? The mailing list and newsgroup are working well enough, so if you receive no useful answers it's likely because nobody could understand the question clearly enough to think how to answer. One thing you might consider is including some actual samples of code, so people don't have to imagine which of the five dozen possible approaches you are actually using. Also make sure you have tried other approaches to ensure that the problem is actually with your own code and not with some host-specific problem which nobody else will ever be able to reproduce locally. > > So, I don't expect anyone to be able to answer this ... but what Yet you were hopeful for answers? ;-) > > *kind* of thing should I be looking for? Is it to do with versions of > > python (2.1.3 locally, 2.2 remotely) or "cgi"? Or the webserver (I'm > > using Apache on Debian locally, I suspect my host is Apache on Red Hat > > 7.1) Python includes excellent facilities for debugging problems of various kinds, including this kind. Why not experiment a little and see what you can come up with? It's unclear from your description where your problem might be so without additional information any suggestions are random shots-in-the-dark, and that I suspect is why no one responded yet. Also, I just noticed, you waited only one day before your second post. That's far too little time to wait, as for many people it can take several days for Usenet posts to reach them and, furthermore, you posted at the end of the work week and many people read Usenet only at work. Summary: experiment, post more and more detailed information, and be more patient. -Peter From simonb at webone.com.au Sat Sep 6 19:55:25 2003 From: simonb at webone.com.au (Simon Burton) Date: Sun, 07 Sep 2003 09:55:25 +1000 Subject: Automated code generation References: <3f58ba15$0$97267$edfadb0f@dread12.news.tele.dk> Message-ID: My classes often have a __str__/__repr__ that generates a bit of python code that when eval'd will reproduce (a clone of) the instance. Simon. On Fri, 05 Sep 2003 18:30:19 +0200, Max M wrote: ... > Does anybody have any experience using Python and automated code > generation where it actually make sense? > > Or os it useless in a language as dynamic as Python? > > > regards max M From tjreedy at udel.edu Fri Sep 12 11:30:44 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 Sep 2003 11:30:44 -0400 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> <66t0mv410it5ftvjokfpkov0v029trv6lp@4ax.com> Message-ID: "Paul Foley" wrote in message news:m24qziiwvw.fsf at mycroft.actrix.gen.nz... > Terry said "FEXPR", which tells you he's about 30 years out of date > wrt Lisp :-) Actually, less than 22 years (LISP was (C)ed in 1981). I have no idea when the last (MAC)LISP definition using FEXPR was written, if indeed no one is still using it on a retro machine. I'd bet less than 15 years ago. No need to exaggerate my newly acquired (I just read the book) and freely admitted (in the followup post) out-of-dateness;-). Actually, I do not agree idea that acquiring new knowledge of old things makes one 'out of date' with respect to that subject. > Any vaguely modern Lisp has macros instead of FEXPRs. Even back then, Winston and Horn presented MACRO as a alternate keyword, with effects similar to, but more complex and powerful than FEXPR. But I believe that FEXPR is/was more like what Horne was proposing for Python, and hence more appropriate, But back to the semantics of 'function' calls. In all languages I have used, a function call meant/means one thing: evaluate the argument expressions according to the rules of the language and pass the results to the function body. I believe Horne was proposing that there be some mechanism added to function declaration syntax that would change the usual argument handling without having to explicitly change argument expressions. He happened to have gotten that idea from C#. The point of my FEXPR-containing paragraph is that C# might well have gotten the idea from Lisp, where it appeared decades ago. (And hence the joke about Lispifying rather than C#ifying Python.) Terry J. Reedy From hutsonken at ev1.net Mon Sep 22 22:56:28 2003 From: hutsonken at ev1.net (Kenneth Hutson) Date: Mon, 22 Sep 2003 21:56:28 -0500 Subject: Connect to VBA Objects? References: Message-ID: Many thanks to Bob Gailer, Dave Brueck and Peter Hansen. Kenneth Hutson San Antonio, Texas "Kenneth Hutson" wrote in message news:vmv8d1hdf55ia0 at corp.supernews.com... > Hi, > I wonder if Python can connect to the object models exposed by Excel or > Word. > Thanks in advance, > Ken Hutson > San Antonio, Texas > > From twic at urchin.earth.li Thu Sep 25 19:22:37 2003 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 26 Sep 2003 00:22:37 +0100 Subject: Another Python rookie trying to port to C/C++ question. In-Reply-To: <6%Icb.24427$dk4.777026@typhoon.sonic.net> References: <6%Icb.24427$dk4.777026@typhoon.sonic.net> Message-ID: On Thu, 25 Sep 2003, Don Bruder wrote: > [...] As such, the details *MUST* get clear if I'm to create equivalent > functionality. If only because I need to read data that was written > (presumably...) by a Python program. Hence, it becomes neccesary to get > down "in the muck" and actually know what's going on behind the nice, > tidy "dict.whosit.get()" (or whatever other operators might be involved) > interface that Python provides. is this data in 'pickle' format (as opposed to text, XML, or some specific binary format)? if it is, reading it in C/C++ is going to be very hard indeed; you might consider writing a small python program to read it and convert it to something more tractable. if it isn't, you don't need to 'get down in the muck'; you just need to write a C program to do the job that needs to be done. if pickling is entirely new to you, then your data probably isn't pickled, so you don't need to worry about it. > > Off topic (or not): A single person can start a discussion but not > > limit it, I think that's a feature of newsgroups rather than an > > annoyance. > > Perhaps, and perhaps not. Guess it depends on your perspective. Having a > stream of insult and invective dumped into your mailbox because you've > made it plain that you don't consider somebody's "pet" language the > be-all and end-all of computer programming is hardly what I'd call a > "feature"... i'm sorry that happened; i hope you won't think badly of python and pythoneers because of one moron. discreetly let the relevant people know who he is and we'll fetch the Comfy Chair ... 8) tom -- Things fall apart - it's scientific From gherron at islandtraining.com Mon Sep 29 16:14:32 2003 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 29 Sep 2003 13:14:32 -0700 Subject: append log file In-Reply-To: References: Message-ID: <200309291314.32373.gherron@islandtraining.com> > Why not ... open(filename ... ? Then 'a' should work. (or at least works > here). The new and prefered way to open a file is to use "file()". The old "open()" is a synonym kept around for backwards compatibility. Gary Herron From chrisahlers at yahoo.com Mon Sep 1 00:35:17 2003 From: chrisahlers at yahoo.com (Chris) Date: 31 Aug 2003 21:35:17 -0700 Subject: wxListbook and wxPython? Message-ID: Is wxListbook actually implemented in wxPython 2.4.07? I attempted to use the class, but an error came back and it is not defined. I found some newsgroup postings in the wxWindows group from 2002 stating that they are working on it, and there is some (sparse) documentation. There is apparently a demo c++ file that features it... Is there something specific that I must do to enable it (or a test version of it), or is it not yet implemented? Thanks, -Chris From Kevin.Smith at sas.com Mon Sep 8 10:29:27 2003 From: Kevin.Smith at sas.com (Kevin Smith) Date: 8 Sep 2003 14:29:27 GMT Subject: zlib on HP-UX 10.20 Message-ID: <20030908102932241-0400@braeburn.themorgue.org> I'm trying to compile Python 2.2.3 and/or Python 2.3 on HP-UX 10.20. However, I can't seem to get zlib working. It worked in 2.2 though. I get the following error: /bin/ld: Invalid loader fixup for symbol "deflate_stored". I read some things in other places that lead me to believe that I needed to compile zlib with +z or +Z. I tried both of them, but it didn't seem to help. Anyway, I would rather be using gcc. Has anyone else gotten this to work? -- Kevin Smith Kevin.Smith at sas.com From jjl at pobox.com Sun Sep 21 16:30:52 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Sep 2003 21:30:52 +0100 Subject: Download to client from a cgi script? References: Message-ID: <87fzip6g03.fsf@pobox.com> ?ystein Johansen writes: [...] > How can I make the browser downlaod a cgi script from > /cgi-bin/. Obviously I can't make a link to it with > , since tha script will be executed then. > > I see how Lutz in PP2E prints the script on the screen, but I want the > user to get the "save file" message box? Don't put it in the cgi-bin? There will be other ways, too, all of which are entirely dependent on your web server and its configuration. Anything regarded by your server as a cgi-script *shouldn't* be downloadable, because that would risk security problems. Some servers will always regard anything ending in ".cgi" or ".py" or whatever as CGI scripts, some will regard anything in a particular directory as CGI scripts, some will do other things. > Same thing. What about a binary file? Printing a binary file with > getfile.cgi from PP2E is just silly. The surfer must be promped to > save. So, what I want is a script like getfile.cgi, that downloads > insted of prints the file. I don't understand any of this paragraph. > (Maybe this is more a HTTP/HTML question than a Python question...) None of the above: entirely a web server question. John From zanesdad at bellsouth.net Mon Sep 8 19:59:24 2003 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 8 Sep 2003 19:59:24 -0400 Subject: os.listdir In-Reply-To: <2ce42702.0309081441.5c73a772@posting.google.com>; from pulapaka@ligo.caltech.edu on Mon, Sep 08, 2003 at 03:41:58PM -0700 References: <2ce42702.0309081441.5c73a772@posting.google.com> Message-ID: <20030908195924.A21733@cerberus.liberty> * Hari (pulapaka at ligo.caltech.edu) wrote: > > What I wanted to know was, is it guaranteed that between 2 calls > os.listdir any files added to the directory are appended and the > earlier order is maintained? Even if the module does guarantee this to you, you probably don't want to just rely on the length of the list (nor the order of it). You probably want to build yourself a dictionary and keep track of it that way. One reason is that you may not be able to guarantee that a file didn't get deleted out of the directory. Even if you think you are in total control of that filesystem, I still wouldn't trust that no files would be deleted. I dunno, maybe I'm just paranoid. Further, as the value of the dictionary (didn't mention this above, but I'd let the filename serve as the key), I'd do os.stat and use the last modified date. Again, maybe I'm just paranoid. Jeremy Jones > > thanks, > > Hari > -- > http://mail.python.org/mailman/listinfo/python-list From tassilo.parseval at rwth-aachen.de Sat Sep 6 05:27:32 2003 From: tassilo.parseval at rwth-aachen.de (Tassilo v. Parseval) Date: 6 Sep 2003 09:27:32 GMT Subject: Embedded Perl or Python (XPost) References: <74e674c13888643bf15a72e800c9d8ed@news.teranews.com> Message-ID: Also sprach Alex Martelli: [ embedding an interpreter ] > Another option you may want to consider is Ruby. I don't know > how easy it is to interface it specifically to C++, and in > particular to get the cross-language subclassing and overriding > effect you want (which Boost provides so smoothly) -- but it's > basically the same power as Perl or Python, a distinctive style > of its own that along some axes lies in-between the two P's, > and a small but enthusiastic community. Size-wise, though, I > don't think it will significantly help you. The C interface of Ruby is very simple and clear (likewise the C code in which Ruby was written). It almost made me cry when I saw it and compared it to that of Perl. :-) It's probably also smaller than both Python and Perl. I don't know about Python, but Perl's unwrapped source is currently well beyond 50meg. In compiled form it's still pretty large due to all the modules that come with Perl. Not sure whether the OP needs all of them though. The bridge to C++ should not be so hard considering that a C++ compilers wont mind to include C code as well (or can at the very least easily be convinced to do so). But anyway, embedding Perl is known to be hard. Tassilo -- $_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({ pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#; $_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval From afriere at yahoo.co.uk Fri Sep 5 00:42:20 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 4 Sep 2003 21:42:20 -0700 Subject: Writing solid code book References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> Message-ID: <38ec68a6.0309042042.58542a60@posting.google.com> Jules Dubois wrote in message news:<1dk5tt7q6acwf$.rcboqaop39ha.dlg at 40tude.net>... > On 03 Sep 2003 13:58:00 +0100, John J. Lee wrote: > > > The Python Cookbook is the first book I'd have on my list if I were > > learning Python now (O'Reilly, eds. Martelli & Ascher). > > That's the only Python book you think worth having? Or buying? > It's a great book, but IMHO it isn's a suitable introduction to the language. 'Learning Python' by Lutz & Ascher is a gentle introduction (very much the Python equivalent of Schwartz and Christiansen's 'Learning Perl'), but is sadly out of date. On the other hand Alex Martelli's 'Python in a Nutshell' (see http://www.oreilly.com/catalog/pythonian/) is certainly worth buying and having, and, if you have some experience in programming, is also a good (if terse) introduction. Check out the free sample chapter and make up your own mind. From bgailer at alum.rpi.edu Wed Sep 10 10:24:09 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 10 Sep 2003 08:24:09 -0600 Subject: I need to make Excel/Powerpoint-style charts. In-Reply-To: <004601c376f0$e36e6f80$5501a8c0@markxp> References: <56665.199.169.240.132.1063120715.squirrel@svr1.turboweb.net> <004601c376f0$e36e6f80$5501a8c0@markxp> Message-ID: <6.0.0.22.0.20030910082215.03a7bc80@66.28.54.253> At 10:39 AM 9/9/2003, mark wrote: >This isn't a terribly helpful post, but I wrote a script that would >collect data from a database using an SQL query. This data was written >to a file which was then imported into Excel using a macro to do all the >sorting and chart creation. I guess there's a learning curve either >way, but it is another way to go about it, since you mentioned that >you're using Excel already. > >I believe it's possible to call out an instance of Excel and provide >arguments to tell it which file to open and what to do with it. I'm >sure there's someone here with a better idea on exactly how to do that >(I didn't get that far before I changed jobs). My approach creates an instance of Excel, then uses Excel VBA methods and objects to transfer data and format charts. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From pkropf at legato.com Tue Sep 23 13:28:59 2003 From: pkropf at legato.com (Peter Kropf) Date: Tue, 23 Sep 2003 10:28:59 -0700 Subject: C Extension and multiple namespaces Message-ID: <96F3EC4BDF504540BB9715CBE9DACB8B019487A9@pa-mail1.legato.com> I'm looking for a way to create multiple namespaces / dictionaries from within a Python C extension. I'd like to replicate something like: a\__init__.py a\b\__init__.py a\b\c\__init__.py Where a\__init__.py import b and b\__init__.py imports c. Python 2.2.3 (#1, Jul 9 2003, 16:15:35) [GCC 3.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import a >>> dir(a) ['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'b'] >>> dir(a.b) ['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'c'] >>> dir(a.b.c) ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] I haven't been able to find any examples or other extension modules that do anything like this, so it might not even be possible. But any help or pointers would be appreciated. Thanks. - Peter Special Projects Group, Legato Systems 3210 Porter Drive, Palo Alto, CA 94304 650-812-6081 Desk 408-482-9427 Cell pkropf at legato.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From oren-py-l at hishome.net Tue Sep 16 09:51:15 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Tue, 16 Sep 2003 09:51:15 -0400 Subject: Duck Typing In-Reply-To: <221d8dbe.0309160101.4a09f2ad@posting.google.com> References: <221d8dbe.0309160101.4a09f2ad@posting.google.com> Message-ID: <20030916135115.GA15424@hishome.net> On Tue, Sep 16, 2003 at 02:01:18AM -0700, srijit at yahoo.com wrote: > Hello All, > I have been seeing this term "duck typing" for quite sometime now. It > will be nice if one of us can give an example in Python demonstrating > duck typing and/or link to some Python references. class Duck: def quack(self): print "Quack!" class MeWearingSillyDuckOutfit: def quack(self): print "ummm... Quack!" def make_it_quack(obj): obj.quack() a = Duck() b = MeWearingSillyDuckOutfit() make_it_quack(a) make_it_quack(b) From adalke at mindspring.com Tue Sep 23 00:54:01 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 23 Sep 2003 04:54:01 GMT Subject: Mutable strings References: <6e990e29.0309220251.51fa648d@posting.google.com> <87fzipavaz.fsf@mally.pyrite.org> Message-ID: Rob Tillotson: > There already is one: array. Mutable blocks of bytes (or shorts, > longs, floats, etc.), usable in many places where you might otherwise > use a string (struct.unpack, writing to a file, etc.). Even regular expressions >>> import array, re >>> t = "When in the course of human events" >>> s = array.array("c", t) >>> pat = re.compile(r"([aeiou]{2,})") >>> m = pat.search(s) >>> m.group(1) array('c', 'ou') >>> Andrew dalke at dalkescientific.com From aleax at aleax.it Thu Sep 4 04:03:22 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 04 Sep 2003 08:03:22 GMT Subject: safari (was Re: Writing solid code book) References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> Message-ID: Jules Dubois wrote: > On 03 Sep 2003 13:58:00 +0100, John J. Lee wrote: > >> The Python Cookbook is the first book I'd have on my list if I were >> learning Python now (O'Reilly, eds. Martelli & Ascher). > > That's the only Python book you think worth having? Or buying? Speaking as both the co-editor of the Cookbook and the author of the Nutshell, if I had to choose ONE Python book "worth having or buying" I think I'd go for the Nutshell. Hard decision, though. Fortunately you don't have to choose "sight unseen". You can join O'Reilly's "Safari" online-books service: it's for-pay, but you DO get a couple of weeks free access, giving you time to examine all of the 15 Python books they have available for online reading -- on the basis of how you like what you see, you may then decide to purchase any one of them -- or even, if you don't like any of them well enough, to purchase none of them and go with the other ones you can access in entirely free ways off the net. In the past, I made my choices about what books to purchase mostly by browsing books at a bookstore. Half an hour per book might mean a full day's worth of browsing to choose among 15 of them, and yet not give me a solid enough basis for choosing. Now I can spend 2 or 3 hours examining each book's contents in a more convenient setting, and in a weekend plus a couple evenings make my choice on a much more solid basis. Even ignoring safari's many other advantages, just as a book-choosing device it's superb!-) Alex From J.Knuth at ipro.de Wed Sep 17 14:29:13 2003 From: J.Knuth at ipro.de (Jochen Knuth) Date: Wed, 17 Sep 2003 20:29:13 +0200 Subject: SMTPlib Emailing Attachments In-Reply-To: <4fd6e92.0309170849.287e86b6@posting.google.com> References: <4fd6e92.0309170849.287e86b6@posting.google.com> Message-ID: Hi Bill, Bill wrote: > I am trying to have the capability to email attachments. Specifically > I want to be able to email a specific attachment that I name that may > be a PDF document, text doc, etc. I already have a working piece of > code that emails jpg attachments but does not work with any other > types of attachments. Could someone tell me how to modify this code to > send other types of attachments like the one's stated above(especially > PDF's)? look at the email package (included since Python 2.2), documented at http://www.python.org/doc/current/lib/module-email.html , specific to MIME-Attachment is http://www.python.org/doc/current/lib/node501.html . Ciao, Jochen -- -------------------------------------------------- Jochen Knuth WebMaster http://www.ipro.de IPRO GmbH Phone ++49-7152-93330 Steinbeisstr. 6 Fax ++49-7152-933340 71229 Leonberg EMail: J.Knuth at ipro.de From bokr at oz.net Sun Sep 7 11:53:40 2003 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2003 15:53:40 GMT Subject: OT: Americans love their guns References: Message-ID: On Sun, 07 Sep 2003 05:36:03 -0000, Steve Lamb wrote: [...] > > What you've all missed is that violence still happens. The Are you talking to me? ;-) (when you say "all") If you read my post, you will note that I didn't say you should not be allowed to make the choice of owning a gun. I just suggested (indirectly at that) that maybe we should regulate ownership and operation of firearms at least as well as we do cars. I suggested that this might have a good influence on the odds of bad things happening. I didn't say I expected them to stop happening. In fact, I said/wrote """ You seem to be hoping that education and attitude (which you don't mention a way of improving, enforcing, or QA-ing) will prevent all the temporary quasi-insanities that normally reasonable humans are capable of. """ I suggested that a risk management approach might be reasonable. Risks vary, as I also mentioned. I understand what happens in one's mind if one receives believable threats of bodily harm, and my sympathies if it has happened to you. I understand that there are contexts where arming oneself is rational, just as there are contexts where wearing a parachute is rational. You have to calculate your own odds. There is a non-zero probablility that you'll be pushed off a high place where a parachute would do you some good. Or jumping might be part of your job. Anyway, try not to be in the wrong place during thunderstorms etc., and never point a banana at an armed person, not even a police officer you know ;-) (well, never say never. Someone probably has bluffed their way out of a bad spot with a banana. But how many got called on it is another thing to consider ;-) Human life structured mainly according to fears is a kind of hell. It is certainly not freedom. We must be careful that our curative measures don't contribute to the disease. Enough OT ;-/ Regards, Bengt Richter From mark at hahnca.com Tue Sep 30 19:33:50 2003 From: mark at hahnca.com (Mark Hahn) Date: Tue, 30 Sep 2003 16:33:50 -0700 Subject: need help with PyXML References: Message-ID: Note: I just found a thread from over a year ago where someone else reported the same bug. Can someone give me a hint on how to work around this bug? previous thread: http://tinyurl.com/p8xj "Mark Hahn" wrote in message news:p3oeb.4606$hp5.3567 at fed1read04... > I am trying to parse HTML for the first time. I first installed > 4Suite-1.0a3.win32-py2.3.exe and then realized I didn't need it. Then I > installed PyXML-0.8.3.win32-py2.3.exe. Now when I try to execute this as > the first line of my module ... > > from xml.dom.ext.reader import Sax2 > > ... I get this Exception ... > > Sequence index out of range: list index out of range > > Traceback (innermost last): > > File "", line 1, in ? > > File "c:\codeshare\codeshare.py", line 4, in ? > from xml.dom.ext.reader import Sax2 > File "C:\Python23\Lib\site-packages\_xmlplus\dom\__init__.py", line 223, in > ? > from xml.dom.html import HTMLDOMImplementation > File "C:\Python23\Lib\site-packages\_xmlplus\dom\html\__init__.py", line > 445, in ? > g_numCharEntityPattern = re.compile('&#(\d+);') > File "C:\Python23\Lib\sre.py", line 179, in compile > return _compile(pattern, flags) > File "C:\Python23\Lib\sre.py", line 227, in _compile > p = sre_compile.compile(pattern, flags) > File "C:\Python23\Lib\sre_compile.py", line 469, in compile > code = _code(p, flags) > File "C:\Python23\Lib\sre_compile.py", line 453, in _code > _compile(code, p.data, flags) > File "C:\Python23\Lib\sre_compile.py", line 88, in _compile > _compile(code, av[1], flags) > File "C:\Python23\Lib\sre_compile.py", line 69, in _compile > _compile(code, av[2], flags) > File "C:\Python23\Lib\sre_compile.py", line 27, in _compile > for op, av in pattern: > File "C:\Python23\Lib\sre_parse.py", line 138, in __getitem__ > return self.data[index] > > From aleax at aleax.it Tue Sep 30 17:24:26 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 30 Sep 2003 21:24:26 GMT Subject: Visual Basic integration References: Message-ID: Lucas Raab wrote: > Can I use Python as an extension language to Visual Basic sort of like in > C or C++? You can implement COM (aka Active/X) servers in Python (just you could implement them in C, C++, or Visual Basic itself) and instantiate them and call their methods from Visual Basic, yes; or, vice-versa, you can put Python in the driving seat. Hammond and Robinson's book on Win32 API Programming (O'Reilly) covers the subject well, IMHO, even though it is quite dated by now (you can do a lot more things with today's Python, and today's version of Hammond's win32all extensions, than you could back when the book was written; but, you can also still do all you could do then:-). Alex From python at sarcastic-horse.com Thu Sep 11 14:35:32 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Thu, 11 Sep 2003 14:35:32 -0400 (EDT) Subject: ftplib question: how to upload files? Message-ID: <40669.199.169.240.132.1063305332.squirrel@svr1.turboweb.net> Hi: I want to write a procedure to automatically upload some files for me, but I'm getting stuck. Before I write my own gruesome put() function, I wanted to check if there is an easier way. Here's what I can do so far: >>>import ftplib >>>conn = ftplib.FTP('ftp.example.com') >>>conn.login(user='userid', passwd='passwd') >>>conn.cwd('/var/www/html/incoming') What do I do to send files? I have three files I want to upload, but I'm not sure what to do. I hoped to find a ftplib.put() method, but it looks like ftplib is a low-level interface. All help is welcome. From doc at goodweb.de Sun Sep 21 12:56:39 2003 From: doc at goodweb.de (Thomas Korb) Date: Sun, 21 Sep 2003 18:56:39 +0200 Subject: XML/XSLT with Python References: Message-ID: On Sat, 20 Sep 2003 22:32:59 +0200, K. N. wrote: > > Is there any good and fast Python module for XSLT > processing ? > I've tested the following 3 'typical' choices 1. 4Suite http://4suite.org/index.xhtml 2. Pyana (for Apache's Xalan) http://sourceforge.net/projects/pyana/ 3. libxml2/libxslt http://www.xmlsoft.org/ and decided to use libxml2/libxslt. Easy to install (on Linux and Windows), easy to use, *very* fast and no problems at all with the XSLT-processor. (I cannot say the same about the other two solutions!) The only problem is the xmlsoft.org site: it's not really obvious, which versions to install etc. WINDOWS: I use the following website for Windows, where you can download Python bindings which are bundled with a copy of libxml2/libxslt (very convenient, easy to install): http://users.skynet.be/sbi/libxml-python/ LINUX: For Linux, I use the RPMs which come with my distribution, i.e.: libxml2, libxml2-python, libxslt and libxslt-python. Hope this helps. -- Dr. Thomas Korb From sross at connectmail.carleton.ca Tue Sep 23 22:51:07 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 23 Sep 2003 22:51:07 -0400 Subject: Pre-PEP: reverse iteration methods References: Message-ID: "Raymond Hettinger" wrote in message news:HA5cb.185$kD3.168 at nwrdny03.gnilink.net... > Here is a discussion draft of a potential PEP. [snip] > Proposal > ======== > > Add a method called iter_backwards() to sequence objects that can benefit > from it. The above examples then simplify to:: > > for i in xrange(n).iter_backwards(): > print seqn[i] > > for elem in seqn.iter_backwards(): > print elem > Hi. This will mostly just be some alternate naming suggestions: How about just ".backwards", where backwards acts like a read-only property that returns a generator for reverse iteration? for i in xrange(n).backwards: print seqn[i] for elem in seqn.backwards: print elem It's not as explicit as iter_backwards(), but it's shorter, cleaner, and appears obvious (to me, anyway). Or, perhaps, 'ibackwards', or 'ireverse' ; or ibackwards() or ireverse(). (being reminiscent of imap() and izip()) '.reverse' would be good, but, of course, it's already taken... If one could be made, a fast** general purpose "reverse(iterable)" (or ireverse(iterable)) function would be my preference (at the very least, it would avoid having to add iter_backwards() to several type definitions). # e.g. for i in reverse(xrange(n)): print seqn[i] for index, item in reverse(enumerate(seqn)): print "index:%s item:%s"%(index, item) # that sort of thing... ** Yep, fast. Something where xrange(n-1, -1, -1) is not exorbitantly faster than reverse(xrange(n)). Similarly, for sequence types, you'd want reverse(list) to be atleast somewhere near as quick as: # python-faq, entry 4.6 list.reverse() try: for x in list: "do something with x" finally: list.reverse() From fredrik at pythonware.com Mon Sep 29 08:28:17 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 Sep 2003 14:28:17 +0200 Subject: unicode 3 digit decimal conversion References: <3F773EA1.4010802@v.loewis.de> Message-ID: Martin v. L?wis wrote: > Correct: UTF-8 works differently. I find it surprising that anybody > actually proposes to send non-ASCII characters using xHH, as this > byte sequence my coincidently happen in ASCII text as well. unless they expect you to send "x" as "x78", of course. From t.evans at paradise.net.nz Wed Sep 24 05:18:20 2003 From: t.evans at paradise.net.nz (Tim Evans) Date: Wed, 24 Sep 2003 09:18:20 GMT Subject: working png output from graphing modules References: <983dac9b.0309221905.1960cf02@posting.google.com> Message-ID: <87zngutuht.fsf@cassandra.evansnet> johnlichtenstein at mac.com (john) writes: > Are there any charting or graphing modules for python that can write > PNG, JPEG, or GIF graphics? I have found a couple of nice looking > packages that can make beautiful postscript, PDF, or SVGs (PyChart and > ReportLab) but they can't make PNGs, GIFs, or JPEGs. (On my Solaris > machine with Python 2.2 they don't.) Or are there any simple UNIX > filters to convert SVG, PDF, or ps files to PNG? The 'convert' utility from ImageMagick (google for it) is very good at converting PDF or PS to PNG. It uses ghostscript to do the actual conversion; it's just very good at choosing the right options to pass to ghostscript. convert -geometry 800x600 -density 200 foo.ps foo.png Will convert a postscript to a png, keeping the aspect ratio correct but making it fit inside an 800 by 600 pixel area. The -density argument tells it the dpi to use when rendering the image. Higher values are slower but give better results. -- Tim Evans From mauricio.inforcati at cenpra.gov.br Fri Sep 5 13:04:19 2003 From: mauricio.inforcati at cenpra.gov.br (=?iso-8859-1?Q?Maur=EDcio_Infor=E7ati?=) Date: Fri, 5 Sep 2003 14:04:19 -0300 Subject: Shaped window on Tkinter Message-ID: <000801c373cf$bfa741e0$237290c8@ITABIRITO> Hi. Is it possible to create windows with transparent areas, just like shaped windows on wxPython? Is there some way of creating transparent frames without associating an image to it? thanks, Mauricio Infor?ati -------------- next part -------------- An HTML attachment was scrubbed... URL: From indigomoon at bonbon.net Wed Sep 24 01:34:00 2003 From: indigomoon at bonbon.net (Indigo Moon Man) Date: Tue, 23 Sep 2003 23:34:00 -0600 Subject: float problem Message-ID: for the formula J = I / (12 * 100) where I is low (like about 8 to 15) I get 0. But when I do it with a calculator it's actually .008333 for example if I were 10. Is there a way I can get python to recognize the .008333 instead of it just giving me 0? TIA for your help! -- Audio Bible Online: http://www.audio-bible.com/ From Mike at DeleteThis.Geary.com Mon Sep 8 02:42:15 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sun, 7 Sep 2003 23:42:15 -0700 Subject: Ternary operator (Re: Ternery operator) References: <3F5B6404.BD1A9709@engcorp.com> Message-ID: > Andrew Chalk wrote: > > Is there a python equivalent of the C ternery operator? Peter Hansen wrote: > See http://www.python.org/cgi-bin/faqw.py?query=4.16&req=search As a newcomer to Python, I found it interesting to read the PEP for this: http://www.python.org/peps/pep-0308.html In retrospect, it seems obvious that the way the voting was conducted insured that no ternary operator would be added to the language. There were 16 proposed syntax options, and the requirement was that a ternary operator would be added only if an clear majority picked a single one of those options. Well, with 16 options to choose from, it hardly seems surprising that none achieved a majority-even though several of them drew quite a few votes, and the most popular proposal did get more votes than the "reject all" option. Four of the options got significantly more votes than the others. Those four options combined got more than three times the number of votes that "reject all" got. It seems to me that the majority did want some kind of ternary operator, but the large number of options prevented any one from being the clear winner. I would wager that if the BDFL had picked his favorite from any of the most popular options and said, "Now vote yes or no on *this* syntax", he would have seen that clear majority he was looking for. I suppose this is all water under the bridge now, since the PEP stated that this was the community's one and only chance. I just can't help but think that the voting system guaranteed the outcome--but it's Guido's language and it was certainly his call to make. -Mike (who just got my California voter's pamphlet with 135 candidates for governor!) From mfranklin1 at gatwick.westerngeco.slb.com Mon Sep 1 04:34:30 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 01 Sep 2003 09:34:30 +0100 Subject: homebrew 2.3 install on RedHat9 not playing nice with Tkinter In-Reply-To: <0h83b.953$8v3.90271@twister.austin.rr.com> References: <0h83b.953$8v3.90271@twister.austin.rr.com> Message-ID: <200309010934.31138.mfranklin1@gatwick.westerngeco.slb.com> On Wednesday 27 August 2003 9:12 pm, Rob Andrews wrote: > I'm on a Red Hat 9 system, which has Python 2.2.2 installed, and I > installed 2.3 separately into /home/rob/Python-2.3/ (creating the symbolic > link "py23" to point to my 2.3 installation). Now I'm trying to work out > the kinks in the process. > > Unable to run Idle using 2.3 the way I've got things set up, I created a > super simple Tkinter test program that just pops up a Label widget. I > pasted below an example of how the RH-provided 2.2 runs the script without > incident, but running the script with 2.3 produces a traceback. If someone > can help me see the error of my ways, I'll be most appreciative. > > [Wed Aug 27][03:01 PM] ~/Python-2.3/test $ python -V > Python 2.2.2 > [Wed Aug 27][03:04 PM] ~/Python-2.3/test $ py23 -V > Python 2.3 > [Wed Aug 27][03:01 PM] ~/Python-2.3/test $ py23 test2.py > Traceback (most recent call last): > File "test2.py", line 1, in ? > from Tkinter import Label > File "/home/rob/Python-2.3/Lib/lib-tk/Tkinter.py", line 38, in ? > import _tkinter # If this fails your Python may not be configured for > Tk ImportError: No module named _tkinter > [Wed Aug 27][03:01 PM] ~/Python-2.3/test $ python test2.py > > -Rob > (mediocre with Python, incompetent with linux) Rob, I had another look and I think I see your problem... basically I removed the /usr/local build of Tcl/Tk so that python 2.3 would 'find' the redhat 9 build of Tcl/Tk.... so I ran configure then make and right at the end of the make:- building '_tkinter' extension gcc -pthread -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -fno-strict-aliasing -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/usr/python/Python23/TEST111/Python-2.3/./Include -I/usr/python/Python23/TEST111/Python-2.3/Include -I/usr/python/Python23/TEST111/Python-2.3 -c /usr/python/Python23/TEST111/Python-2.3/Modules/_tkinter.c -o build/temp.linux-i686-2.3/_tkinter.o /usr/python/Python23/TEST111/Python-2.3/Modules/_tkinter.c:96:2: #error "unsupported Tcl configuration" /usr/python/Python23/TEST111/Python-2.3/Modules/_tkinter.c: In function `AsObj': /usr/python/Python23/TEST111/Python-2.3/Modules/_tkinter.c:947: warning: passing arg 1 of `Tcl_NewUnicodeObj' from incompatible pointer type /usr/python/Python23/TEST111/Python-2.3/Modules/_tkinter.c: In function `FromObj': /usr/python/Python23/TEST111/Python-2.3/Modules/_tkinter.c:1073: warning: passing arg 1 of `PyUnicodeUCS2_FromUnicode' from incompatible pointer type So it looks like the Tcl/Tk version that comes with RedHat 9 (it apears to be Tk 8.3.5 accordfing to the tk.h file in /usr/include) is not compatible with the Tkinter in Python 2.3. This means _tkinter.so is not built and Tkinter will not work! On way round this little problem would be to build your own Tcl/Tk (thats what I did) Not only will you get a working Python 2.3 but you get the new options in Tk 8.4 too all for an extra couple of downloads and about 30 mins of 'work'. Cheers Martin From db3l at fitlinxx.com Tue Sep 16 14:17:22 2003 From: db3l at fitlinxx.com (David Bolen) Date: 16 Sep 2003 14:17:22 -0400 Subject: distutils on win32 with link.exe -- use dlls? References: Message-ID: John Hunter writes: > Is there a macro or compile flag or other setting to inform distutils > to look for the DLLS of the required libraries rather than the *.lib > files? Under Windows, even if your resultant binary is going to use DLLs, you need to link against the export libraries provided for those DLLs. The export libraries only contain the external entry points into the DLLs and a reference to the DLL, but they are still separate .lib files that are necessary to build code to run against the DLLs. Thus, anyone who provides DLLs for other source to use should also be providing the matching .libs (or if you are building the DLLs from source, the build process should also create matching .lib files). -- David From ken at perfect-image.com Fri Sep 19 01:59:19 2003 From: ken at perfect-image.com (Ken Godee) Date: Thu, 18 Sep 2003 22:59:19 -0700 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) In-Reply-To: <6e07b825.0309182013.3ddeb760@posting.google.com> References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> <3y7ab.1043$Od.78860@twister.tampabay.rr.com> <3f697584$0$10966$fa0fcedb@lovejoy.zen.co.uk> <3f6a2bd3$0$10998$fa0fcedb@lovejoy.zen.co.uk> <6e07b825.0309182013.3ddeb760@posting.google.com> Message-ID: <3F6A9B37.6030207@perfect-image.com> yaipa h. wrote: > You have our permission to go out an buy that second monitor, > so that this DREADFUL problem never happens again. ;^) > Someone has to run the regressions on a dual headed system > and you get our vote. > > On a more serious note, you will find that you use the office printer > a whole lot less on a dual head machine. > > --Alan > > "John Dean" wrote in message news:<3f6a2bd3$0$10998$fa0fcedb at lovejoy.zen.co.uk>... > >>Hi >>You may or may know that BA is based on the Qt GUI Application Toolkit, so >>you problem with the duel monitor set up is something I shall take up with >>Trolltech. Unfortunately, none of use at theKompany run a duel monitor setup >>so it is something that we are not aware of. Thank you for bring up this >>problem and I will get back to you with a solution or our proposal for a >>solution boy, I didn't want to keep jumping in on this Black Adder thing but..... I also run dual monitors and Black Adder / Qt designer / pyqt apps do not have any problems splitting the screens. I'm only testing the Black Adder demo version on win32(98se) though, Nvidia (without thier goofy utilities, that screw up everything) I forget what dual head card/reference design that's in that machine but it's an under $100.00 card. From harry.g.george at boeing.com Tue Sep 9 02:34:18 2003 From: harry.g.george at boeing.com (Harry George) Date: Tue, 9 Sep 2003 06:34:18 GMT Subject: enum in Python References: <%V67b.653$NW3.617@news1.central.cox.net> <3f5d0df1$1@nntp0.pdx.net> Message-ID: Scott David Daniels writes: > David M. Cook wrote: > > > In article , Andrew Chalk wrote: > > > >>As a rank Python beginner I've used a dictionary, but presumably there is a > >>better way. > > I've seen idioms like FOO, BAR, BAZ = range(3) > > used. > > Dave Cook > > For 2.3 or after: > > class Enumerate(object): > def __init__(self, names): > for number, name in enumerate(names.split()): > setattr(self, name, number) > > To use: > codes = Enumerate('FOO BAR BAZ') > codes.BAZ will be 2 and so on. > > > if you only have 2.2, precede this with: > > from __future__ import generators > > def enumerate(iterable): > number = 0 > for name in iterable: > yield number, name > number += 1 > > > > > codes.BAZ > We have some code which uses fancy cookbooked enumerate patterns but they seem unnecessarily complex to me. Even the pattern above is a runtime build of what should be a static type definition. Instead, in any Python version, I use: class Code: unknown=0 FOO=1 BAR=2 BAZ=3 mycode=Code.unknown #typical initialization mycode=Code.FOO #specific value assigned. You get: a) type-specific namespace b) can choose the numbers (e.g., when they are predefined in a data file format) c) errors are detected d) static assignment allows compiler optimizations (don't know if any are actually done). -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From mcfletch at rogers.com Thu Sep 11 18:19:52 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 11 Sep 2003 18:19:52 -0400 Subject: getting ttf font/family name; fontTools? In-Reply-To: References: Message-ID: <3F60F508.8030300@rogers.com> TTFQuery does all this stuff (using fontTools). Particularly the "describe" module in the package does the work of pulling apart the tables to get something useful: http://sourceforge.net/projects/ttfquery/ http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/*checkout*/ttfquery/ttfquery/describe.py?rev=1.1.1.1&content-type=text/plain You'll also find scripts similar to your "findfont" in the ttfquery package, e.g. family_query.py or metadata_query.py, which are built on the ttffiles.Registry object's various methods (particularly matchName). TTFQuery will build its font-registry either by trying to guess the system paths, or by being given a directory in which to search (or both). HTH, Mike John Hunter wrote: >I would like to extract the font and family name from a TTF file. I >have been looking at fontTools ttLib, which parses the ttf file and >provides lots of helpful information, but cannot find the name. > > >>> from fontTools import ttLib > >>> tt = ttLib.TTFont("cour.ttf") > >tt['head'] seems like a good place to find it, but I can't. > >The data appear to be in the 'name' field > > >>> s = tt.getTableData('name') > >>> s.find('Courier') > 4197 > >But I still don't know how to extract this information if I don't know >the family/font name in advace. Any ideas on how to best extract this >info using fontTools or otherwise? > >What I am trying to do is find the best ttf font file for a given >fontname, fontangle, and fontweight. I plan to write my own font >finder given a font name and font family from the ttf file, but if >there is a better way to find ttf fonts let me know. Eg, what I want >to do is > > ttfile = findfont('Courier', 'Italic', 'Bold') > >and have findfont search some PATH containing TTF files and return the >closest match, or a default if no good match is found. > >Thanks, >John Hunter > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sun Sep 28 13:51:03 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sun, 28 Sep 2003 18:51:03 +0100 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> <0acdb.128801$hE5.4391247@news1.tin.it> <1Xhdb.130593$hE5.4445587@news1.tin.it> <9tabnvgbc4etnpp1hm3oh5dkffkru9pv0d@4ax.com> <2tsbnvob1k6tt6bkb29cfc69a4ji0q4giv@4ax.com> Message-ID: <136envcoppkt546p8rhjhpeqkj380a3g40@4ax.com> On Sun, 28 Sep 2003 11:22:11 -0400, David Abrahams wrote: >Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: > >>>Sorry, what specialization? >> >> Presumably template specialisation - such that the special case of >> std::pair picks up the iterating functionality that >> std::pair lacks (begin, end etc). That is what I thought you were >> saying. >> >> Or am I still getting this wrong? > >Yeah, slightly. You don't need a begin() member function in order to >make an iterator. The interface might look like: > > std::for_each(pair_iterator(my_pair), pair_iterator(), f); > >Decoupling is the way to go, man! :^) Ah - I get it! - std::pair doesn't exactly support iteration itself, but a support class can be used to add that capability. You can do this in any language. For instance, did you know that Python classes supports iterating through the subset of their attribute that have names beginning with "a", interleaved with insults? Yes, all you need is to use this generator... def A_Attrib_Gen (p_Instance) : for i in dir (p_Instance) : if i[0] = "a" : yield i yield "stupid stupid stupid" Well, OK, maybe this is a little unfair - this generator isn't exactly in the library, but with a little luck you see my point. When you say "you can in fact iterate on std::pair with the usual C++ iterator protocol" it implies to me that std::pair provides the iterator protocol itself - not that some other class provides a way to support iteration over the pair. After all, there is *always* some way to support iteration of *anything*. But maybe I'm just being overliteral. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From jerf at jerf.org Thu Sep 11 22:24:27 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 12 Sep 2003 02:24:27 GMT Subject: Parsing XML streams References: <659f82ff.0309111530.c17e4a6@posting.google.com> Message-ID: On Thu, 11 Sep 2003 16:30:18 -0700, Peter Scott wrote: > Is there some way to do this with the standard python xml parsers? > Will I need to use PyXML? Or what? xml.parsers.expat can parse things in pieces. It shouldn't be *too* much work to convert over. From jacek.generowicz at cern.ch Tue Sep 23 05:33:24 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 23 Sep 2003 11:33:24 +0200 Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> Message-ID: bokr at oz.net (Bengt Richter) writes: > You could also let the factorial benefit from its own experience, e.g., > > >>> def factorial(n, cache={}): > ... fn = cache.get(n) > ... if fn: print 'got cached %s!'%n; return fn > ... if n<2: cache[n]=1; return 1 > ... return cache.setdefault(n, n*factorial(n-1)) > ... Or, you could let _any_ (keywordless) function benefit from its own experience: # General memoizer: takes a function as returns another function which # has the same semantics as the original, but caches previously # calculated values def memoize(callable): cache = {} def proxy(*args): try: return cache[args] except KeyError: return cache.setdefault(args, callable(*args)) return proxy # A quick and dirty timer utility (timeit module in 2.3 ?), just to # help us see how we're doing. import time def timer(fn, *args): start = time.time() val = fn(*args) stop = time.time() print "Took", stop-start, "seconds ..." return val # The function we want to use def factorial_rec(n): if n <= 1: return 1 else: return n*factorial_rec(n-1) # Now, make a cache-enabled version of your function fact = memoize(factorial_rec) # ... and use that, instead of the original ... # See how long the bare function takes print timer(factorial_rec, 100) # The first call to the proxy will be slightly slower than the bare function print timer(fact,100) # But the second call with the same argument will be much faster print timer(fact,100) ================================================== Output: Took 0.000393986701965 seconds ... 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 Took 0.000407934188843 seconds ... 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 Took 4.88758087158e-06 seconds ... 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 From eppstein at ics.uci.edu Fri Sep 26 13:59:24 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Fri, 26 Sep 2003 10:59:24 -0700 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> Message-ID: In article , "Sean Ross" wrote: > Nope. Nor have I intimated I had such, nor that any would be forthcoming. > This is a naming suggestion. I am neither the originator of the proposal nor > a proponent of it, so I see no reason to formulate such a plan nor to give > an explanation of how it should be accomplished. I saw a name, and offered > another. That is all. > > P1: "If I make this thing, I propose to call it 'ShomozzleBoB'." > P2: "Really? How about just BoB?" > P3: "Do you have a plan for how to do BoB?" > P2: "Huh?" Your proposed name has an implication for the semantics. I was questioning the feasibility of the implied semantics. I don't think you're let off the hook by the excuse that "it's only a name". -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From nospamius at lundhansen.dk Sat Sep 6 05:43:34 2003 From: nospamius at lundhansen.dk (Bertel Lund Hansen) Date: Sat, 06 Sep 2003 11:43:34 +0200 Subject: Unreachable References: Message-ID: <30bjlv4lplntkhlneo6b66pciucjk8t5o0@news.stofanet.dk> raizor at rtcwonline.com skrev: >This email address is unreachable. It has been closed. I wonder why this group is hit by so many messages that ought to have been sent as personal mail? -- Bertel, Denmark From fawcett at teksavvy.com Mon Sep 15 23:43:48 2003 From: fawcett at teksavvy.com (Graham Fawcett) Date: Mon, 15 Sep 2003 23:43:48 -0400 Subject: Web server with Python In-Reply-To: <20030916014821.GB4093@frobozz> References: <6o24mvcmksid33t4s9b8cbsrnctl5n2o6m@4ax.com> <20030916014821.GB4093@frobozz> Message-ID: <3F6686F4.9020205@teksavvy.com> Andrew Bennetts wrote: >On Mon, Sep 15, 2003 at 08:18:25PM +0200, Patrick Useldinger wrote: > > >>On Sun, 14 Sep 2003 15:43:30 +1000, Andrew Bennetts >> wrote: >> >> >> >> >>>Eek! Does 1.0.7 (just released) work any better? Also, what platform are >>>you using, and are you installing from the source .tar.gz or something else? >>> >>> >>I didn't try 1.0.7, didn't even know that it was out. >>I am on a WinXP box and used the prebuild binaries. >> >> > >Ah, ok. The prebuild binaries for Windows only work on one version, and I >think the Windows maintainer has chosen to only support 2.2. You're welcome >to build your own from the source, or try to convince someone on IRC to >build 2.3 binaries for you ;) > >Also, you don't need a compiler to use Twisted. The C extensions are >entirely optional, and just provide some optimisations over some of the >equivalent pure python modules, but most users would probably never notice >the difference. > > > >>I have started digging into Medusa right now... and stay focused on >>that one until I have a blocking problem or I get bored ;-) >> >> If you'd like to use Medusa with less digging and much less boredom, I'd encourage you to check out the Quixote Web app framework, which runs beautifully on Win32/Medusa (as well as a number of other front ends, including Twisted). Personally I think it's nice to be able to write app code against a (lean, mean and delightful) framework, while maintaining the right to choose and switch between a range of Web servers. That's good separation of concerns. Quixote has a shiny new advocacy site at http://quixote.ca/ and is available for download at http://www.mems-exchange.org/software/quixote/ . >We'll be waiting ;) > > If Patrick gives Quixote a try, you might be waiting a while. Best wishes to all, -- Graham From anton at vredegoor.doge.nl Thu Sep 18 09:05:18 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 18 Sep 2003 15:05:18 +0200 Subject: Closures in python References: <9caba98e.0309180208.692e9b68@posting.google.com> Message-ID: Hallvard B Furuseth wrote: >'closure' is a much-abused word. >This is a closure over foo's x variable: How about namespaces? >def foo(): > x = 3 > def bar(): > x += 1 > return x > return bar > >f = foo() >print f() # print 4 >g = foo() >print f() # print 5 >print g() # print 4 > >...or it would be, if it worked. This works: def foo(): class ns:pass ns.x = 3 def bar(): ns.x += 1 return ns.x return bar Anton From xavim at fqingenieria.es Tue Sep 30 10:04:26 2003 From: xavim at fqingenieria.es (Xavier Martinez) Date: Tue, 30 Sep 2003 16:04:26 +0200 Subject: Tkinter not installed References: <57efaf35.0309300435.8864896@posting.google.com> Message-ID: <002801c3875b$c2eb9aa0$0102a8c0@xavim> > Have a problem in python installation.I have already installed > python 2.2 in my linux machine,but i guess tkinter packages were not > selected then.Now i want to use tkinter as an interface for my > program(actually i wanted to check if my python program written in > windows side works fine on linux side also). > is there any way i can include the tkinter packages?if so where > can i find those files? It depends of what linux distribution are you using (you should specify it). If you have a Debian box, simply type (as root): $ apt-get install python2.2-tk -- Xavier Martinez From theller at python.net Thu Sep 25 11:48:11 2003 From: theller at python.net (Thomas Heller) Date: Thu, 25 Sep 2003 17:48:11 +0200 Subject: RELEASED Python 2.3.1 References: Message-ID: Dave Brueck writes: > I've been working on a simplistic implementation of such a run-time > for my own projects. It's functional but very experimental (read: does > what I need and not much else) and not well-documented or anything, > but if anybody wants to play with what I've done so far just drop me a > line. It's nice and small: > > 19,530 ctypes.zip > 18,944 pycb.exe > 1,908 pycbcom.tlb > 19,456 pycbw.exe > 445,952 python23.dll > 749,092 python23.zip > 3,072 w9xpopen.exe > 20,480 _ctypes.pyd > > (1.2 MB total - has _socket, select, _winreg, etc built in to the main dll) Interesting. Is the python23.dll compressed,or did you leave features out? > > It registers itself as an ActiveX control so that from Internet > Explorer you can have a web page query to see if the run-time has been > installed (so that, e.g., you can have the user download the > app+runtime or just the app). > > Small download size is a primary goal, with a close second being very > little differentiation between the dev (.py) and release (.exe) > environments (which has bitten me many times in the past). Thus I > don't run python.exe any more at all for projects that will end up > being distributed this way. > > The library also registers the .pycb extension with Windows (pycb = > "Python code bundle") so that you can distribute your code in a small > app.pycb file that, from the user's perspective, is an > "executable". For example, for a personal project I just completed the > entire distribution consisted of: > > venster.pycb (82k) > main.pycb (15k) > > Under 100KB is not bad for a GUI app! :) > > The .pycb format is basically ZIP + AES encryption, and pycb uses the new > import hooks in 2.3 to handle it. The encryption is just to keep honest > people out; anybody with the right combination of smart and bored could > figure out how to circumvent it. Mark Hammond and I have also been hacking on a new py2exe version which is somewhat similar, available in a CVS sandbox subdirectory. It creates small exe-files (gui, console, service, or com), containing the main script as marshaled code objects, together with a zipfile containing the needed python modules, shared between these exe-files. The zipfile is imported using the zipimport feature of 2.3. The code is factored out so that it should even possible to add encryption for the zipfile's contents, given that a customized zipimporter is used. Thomas From vze4rx4y at verizon.net Wed Sep 24 14:18:03 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 24 Sep 2003 18:18:03 GMT Subject: Pre-PEP: reverse iteration methods References: Message-ID: [Raymond] > >Abstract > >======== > > > >This proposal is to extend the API of several sequence types > >to include methods for iterating over the sequence in reverse. [Christos TZOTZIOY Georgiou] > -0 > > I believe this should be a function in itertools. > > For indexable sequences, a little modification of itertools.islice would > do the trick, since it can't at the moment; it's designed for forward > iteration. > > Helpful error messages: > >>> itertools.islice(lst, len(lst)-1, -1, -1) > ValueError: Stop argument must be an integer or None. > >>> itertools.islice(lst, len(lst)-1, None, -1) > ValueError: Step must be one or larger for islice(). > > For non-indexable sequences (eg a file object), things get hairier, but > given enough memory, it's not hard. Here's a quick and dirty implementation of your idea (kept separate from islice for clarity). On the plus side, it is somewhat clean and easy to use. On the minus side: * It's slower than custom iterator methods * It behaves badly with infinite iterators as inputs * For non-indexables, it silently transitions into a non-lazy, memory intensive mode with a long delay on the first call. In my opinion, this defeats the purpose of using iterators in the first place. def ireverse(obj): assert not hasattr(obj, 'keys') try: for i in xrange(len(obj)-1, -1, -1): yield obj[i] except (AttributeError, TypeError): x = list(obj) # XXX fails with infinite iterators x.reverse() for elem in x: yield elem for i in ireverse(xrange(5)): print i for c in ireverse('abcde'): print c for elem in ireverse(['atom', 'beta', 'curry']): print elem for line in ireverse(file('/autoexec.bat')): print line.rstrip() for x in reverse(itertools.count()): # Never gets here and Python dies with a MemoryError # from the infinite loop pass Raymond Hettinger From rowen at cesmail.net Thu Sep 11 16:54:53 2003 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 11 Sep 2003 13:54:53 -0700 Subject: mixing for x in file: and file.readline Message-ID: At one time, mixing for x in file and readline was dangerous. For example: for line in file: # read some lines from a file, then break nextline = readline() # bad would not do what a naive user might expect because the file iterator buffered data and readline did not read from that buffer. Hence the call to readline might unexpectedly skip some lines. I stumbled across this the hard way, but am wondering if it's still present in Python 2.3. I thought I'd seen it documented recently, but looking through the description of the file object in the Python Library Reference, I didn't see it. Anyone know if it's still an issue? If so, anyone have any idea how hard it would be to fix? I'm willing to work on a patch, but would probably need some help. And if experts have already determined it's too hard, and are willing to expain, I'd love some idea of why that is. -- Russell From mcfletch at rogers.com Thu Sep 4 20:22:09 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 04 Sep 2003 20:22:09 -0400 Subject: Selecting elements from a list In-Reply-To: <87y8x4w6ym.fsf@gvdnet.dk> References: <87y8x4w6ym.fsf@gvdnet.dk> Message-ID: <3F57D731.1090907@rogers.com> Martin Christensen wrote: >B = [] >for i in A: > if A.property(): > B.append(i) > > B = [ i for i in A if i.property() ] Seems elegant, but then I'd like dictionary-comps if they came along, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From llothar at web.de Fri Sep 12 08:21:42 2003 From: llothar at web.de (Lothar Scholz) Date: 12 Sep 2003 05:21:42 -0700 Subject: Is there a web templating system like ruby's amrita ? Message-ID: <6ee58e07.0309120421.622cb55@posting.google.com> I there anything that completely avoid the use of python code inside a template. I like the Amrita system because it allows me to design the templates with WYSIWYG editors and blind text. From mwilson at the-wire.com Mon Sep 15 10:51:25 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 15 Sep 2003 10:51:25 -0400 Subject: list of lists References: Message-ID: In article , Tom wrote: >I have a list that consists of lists. >E.g. T=[[1, 2, 3], [4, 5], [6]] >Is there a way to address the a specific component in the "inner" list >directly? >E.g. right now I want to get the second value of the first list. >Unfortunately I have to save it to a variable first and then read it. >a = T[0] >print a[1] Anybody? :) print T[0][1] Python syntax is pretty regular. If T is a list, then T[0] is the zero-th element of T. If T[0] is a list, then T[0][1] is the 1-th element of T[0]. Works for tuples and dictionaries too. Hairier, if F(a) returns a function object based somehow on the value of a, then F(a)(b) will call that function with an argument of b. And so, on and on. Tuples of functions? Functions returning dictionaries caching lists of functions? ... Regards. Mel. From Scott.Daniels at Acm.Org Mon Sep 29 19:43:02 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 29 Sep 2003 16:43:02 -0700 Subject: Package question. In-Reply-To: References: Message-ID: <3f78c386$1@nntp0.pdx.net> Ian Sparks wrote: > ... On Windows, I want to set up a package structure like : > Fred\ > Bob\ > test.py > So I can say : > from Fred.Bob import * > To do this I need to put the package on the python path. > So I drop this into my python root in a file called Fred.pth : > C:\Fred\ > Now to make sure that Fred and Bob both look like packages with > empty __init__.py files like so : > C:\Fred\ > __init__.py > C:\Fred\Bob\ > __init__.py > test.py > so : > C:\python.exe -c from Fred.Bob import * > OK! But this is a lucky accident. If you do: import sys for number, name in enumerate(sys.path): print number, repr(path) You'll see (I suspect) that '' is on your path, and the Fred.pth value is irrelevant (it adds an entry for 'C:\\Fred\\', which allows you to import from Bob, not Fred. You Fred.pth file should list the directory _containing_ Fred (in this case, 'C:\\', not 'C:\\Fred\\'). Note, you'll still be surprised soon, because I suspect you think that after: from Fred.Bob import * you can freely use: test.somefunction() -Scott David Daniels Scott.Daniels at Acm.Org From spam at magnetic-ink.dk Thu Sep 25 02:22:44 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Thu, 25 Sep 2003 06:22:44 +0000 (UTC) Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> <3f71395d-46f08129-996a-495d-a5ee-05fb1caef6e9@news.szn.dk> <3f721b0c-fce176ad-f4e1-4bdc-8527-cc05ef24ad42@news.szn.dk> <3F722887.F4521F68@alcyone.com> Message-ID: <3f7289b4-d5928636-2b38-4329-ae4b-f09c5d0b3c44@news.szn.dk> Erik Max Francis wrote: >> killing blindly is bad programming practice. > > But he's killing with a signal of 0. From kill(2): > > If sig is 0, then no signal is sent, but error checking is > still performed. > > It's perfectly reasonable behavior to kill a process with a 0 signal; > it does no harm. I overlooked that detail, thanks for correcting me. // Klaus -- ><> unselfish actions pay back better From uce at ftc.gov Mon Sep 22 17:46:35 2003 From: uce at ftc.gov (Gordon Airport) Date: Mon, 22 Sep 2003 17:46:35 -0400 Subject: Mutable strings - symetry with list types In-Reply-To: <3ql141-hk4.ln1@beastie.ix.netcom.com> References: <3ql141-hk4.ln1@beastie.ix.netcom.com> Message-ID: Dennis Lee Bieber wrote: > Prior to the creation of string methods, you'd have done > > import string > > ... string.join(blah, ' ') > > Yes, it looks even worse that way. I guess that it's just rare to use a literal in the code as an object...I'm having trouble thinking of other situations where you use the ability, but I won't pretend to be an expert in the language. >>not obvious and it looks like a hack, IMO. Plus you can't do >>somestring = '%s %s %s' % [ 'nine', 'bladed', 'sword' ] > > > If you know both sides have equal numbers of terms (the %s matches the > number of entries in the list) you /can/ do a minor modification to > that line: > > somestring = "%s %s %s" % tuple(["nine", "bladed", "sword"]) I just found it strange that you couldn't do it directly without 'casting'...Probably doesn't come up much anyway. Now that I think about it it's an assignment so it's not really relevant to the discussion of mutable strings. > > Of course, you could also create a dictionary and store those as > attributes (though to my mind, you have a sword with one modifier > "nine-bladed"; as is it could be interpreted to mean nine > bladed-sword(s) -- though all swords are bladed...). > > >>>>weapon = {"type":"Sword", "attribute":"bladed", "modifier":"nine"} >>>>weapon > > {'attribute': 'bladed', 'modifier': 'nine', 'type': 'Sword'} > >>>>somestring = "%(modifier)s %(attribute)s %(type)s" % weapon >>>>somestring > > 'nine bladed Sword' > All very handy, but I don't see how it could be done better with mutable strings. I need to come up with some examples of applications. From cygwin-help at cygwin.com Wed Sep 3 07:23:47 2003 From: cygwin-help at cygwin.com (cygwin-help at cygwin.com) Date: 3 Sep 2003 11:23:47 -0000 Subject: WELCOME to cygwin@cygwin.com Message-ID: <1062588227.22325.ezmlm@cygwin.com> Hi! This is the ezmlm program. I'm managing the cygwin at cygwin.com mailing list. Acknowledgment: I have added the address python-list at python.org to the cygwin mailing list. Welcome to cygwin at cygwin.com! Please save this message so that you know the address you are subscribed under, in case you later want to unsubscribe or change your subscription address. Before posting, please check out following links: The Cygwin Web Site http://cygwin.com/ The Cygwin FAQ http://cygwin.com/faq/ Cygwin Problem Reporting http://cygwin.com/problems.html The Mailing List Archive http://cygwin.com/lists.html Generic Web Searching http://google.com/ (type in cygwin plus your search term) --- Administrative commands for the cygwin list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: To remove your address from the list, send a message to: Send mail to the following for info and FAQ for this list: Similar addresses exist for the digest list: To get messages 123 through 145 (a maximum of 100 per request), mail: To get an index with subject and author for messages 123-456 , mail: They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: To stop subscription for this address, mail: In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at cygwin-owner at cygwin.com. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: Received: (qmail 22317 invoked from network); 3 Sep 2003 11:23:46 -0000 Received: from unknown (HELO sheppard1.torfree.net) (199.71.188.20) by sources.redhat.com with SMTP; 3 Sep 2003 11:23:46 -0000 Received: from yahoo.ca (H86.C223.tor.velocet.net [216.138.223.86]) by sheppard1.torfree.net (Postfix) with ESMTP id E43096D40F for ; Wed, 3 Sep 2003 07:23:44 -0400 (EDT) Message-ID: <3F55CEC2.1060102 at yahoo.ca> Date: Wed, 03 Sep 2003 07:21:38 -0400 From: Thomas Williams User-Agent: Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax) X-Accept-Language: en-us, en MIME-Version: 1.0 To: cygwin-sc.1062360610.dhidpechaifelobfhlof-python-list=python.org at cygwin.com Subject: (no subject) Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit From NO-MAIL at hotmail.com Tue Sep 16 18:34:26 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 22:34:26 GMT Subject: Tkinter: tooltips (Windows) References: <%PK9b.13530$x21.9926@twister.southeast.rr.com> Message-ID: "Christos TZOTZIOY Georgiou" wrote in message news:js2fmv4a19aajopm5ph0he94uqj8btd5c7 at 4ax.com... > On Tue, 16 Sep 2003 20:58:35 GMT, rumours say that "M-a-S" > might have written: > > >I thought somebody might have already done it w/o Pwm, with Tkinter only. > >Bad luck. > > Idle has tooltips, and it's Tkinter only. You already have the code; > maybe ToolTip.py would be a good start :) Great! Thanks. > -- > TZOTZIOY, I speak England very best, > Microsoft Security Alert: the Matrix began as open source. From retype at terra.com.br Tue Sep 23 13:53:14 2003 From: retype at terra.com.br (Leonardo Santagada) Date: Tue, 23 Sep 2003 14:53:14 -0300 Subject: General Password questions In-Reply-To: References: <3F6F86A2.DC29472A@engcorp.com> <3F704A91.FA7D31F7@engcorp.com> Message-ID: <3f70887f$1@news.terra.com.br> Riccardo Attilio Galli wrote: > On Tue, 23 Sep 2003 09:28:49 -0400, Peter Hansen wrote: > > > > I think you have misunderstood me(mmm, I hope it sound polite enough in > english). An user should never enter the password again. I know how hashes > work, and they're useful when I can compare an entered password with an > hash value, but here I need that the user don't enter a password anymore > (after the first time). > > The natural use of the program would be: > run the e-mail client for the first time > user enter his e-mail password > the client check for new mails > user close the client. > > while 1: > user run the e-mail client > the client check for new mails WITHOUT ask for a password > user close the client > > I hope I was clearer. I think Richard got the point, whit a "sad but true" > answer. > > Ciao, > Riccardo > > I Really think he didn't understand you because hashing a password that you will need again isn't possible. You need to store the password in a crypt way, but I don't know how to generate the master password(the one that is used by the crypto program to encrypt the pop or imap passoword). I really don't understand a lot about encrypting something, but sha1 and md5 are not reversible. If they were, then I would download only the signature of a file and not the file. Now you need to know how mozilla does it. From roy at panix.com Tue Sep 23 09:55:25 2003 From: roy at panix.com (Roy Smith) Date: Tue, 23 Sep 2003 09:55:25 -0400 Subject: Need arguments for "Python vs. Perl as an OOPL" References: <3F7049D3.14C48D43@engcorp.com> Message-ID: Peter Hansen wrote: > Roy Smith wrote: > > > > I'm working on a prototype of a new application in Python. At some > > point, if this ever turns into a product, the powers that be will almost > > certainly demand that it be done in Perl. My job will be to convince > > them otherwise. > > Do you need to convince them now, to allow you to continue working on it > in Python, or are you just preparing for the time when they will come and > ask for it to be done in Perl? The latter. It's currently a bit of a skunk works project. At some point, when the time comes to actually allocate resources to this, some PHB will undoubtedly declare that it has to be done in Perl. At that point, I'll need to be able to argue coherently why that's a bad idea. From max at alcyone.com Tue Sep 30 15:04:20 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 30 Sep 2003 12:04:20 -0700 Subject: isNumber? check References: <56e1eff0.0309292105.bab5a2@posting.google.com> Message-ID: <3F79D3B4.DBE550CC@alcyone.com> Jean-S?bastien Bolduc wrote: > I used to use the latter approach suggested by Gerrit, but I recently > found on the web an alternative, elegant approach that might work > (sorry, I don't recall where I found it!): > > hasattr(x, '__int__') > > If the "__int__" method is defined for "x", it is a number. This will > work for integer, long, float and complex types, as well as for custom > classes that emulate numeric types. This is an insidiously bad idea, in my opinion. All having an __int__ method means is there is some _conversion_ from an instance to an int type. It does not at all mean the custom instance spends most of its life behaving as an integer. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ We grow in time to trust the future for our answers. \__/ Ruth Benedict From john at rygannon.com Thu Sep 11 07:26:11 2003 From: john at rygannon.com (John Dean) Date: Thu, 11 Sep 2003 11:26:11 GMT Subject: Problems with setting up mod_python and Apache References: <3f5f6b41$0$239$fa0fcedb@lovejoy.zen.co.uk> <4zK7b.11532$NW3.6643@news1.central.cox.net> Message-ID: <3f605bee$0$199$fa0fcedb@lovejoy.zen.co.uk> Hi Dave I have fixed my problem with mod_python. I have one small problem left to sort out. If I enter the URL http://localhost Apache just displays the contents of the htdocs directory, but if I enter the URL http://localhost/test.py everything works as it should. I guess this is somewhat off topic since it appears to be an Apache configuration problem so I hope you don't mind me asking you for your opinion on c.l.p. BTW What I am trying to do is to move away from PHP. Since I use Python as my primary scripting language for just about everything where you would use a scripting language, it seems to me to be a reasonable idea to use Python to provide dyanamic content for the web sites I look after. -- Best Regards John From gerrit at nl.linux.org Tue Sep 2 11:41:46 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 2 Sep 2003 17:41:46 +0200 Subject: force gtk modal window to keep focus In-Reply-To: <3a6e51c8.0309020731.1870c3c@posting.google.com> References: <3a6e51c8.0309020731.1870c3c@posting.google.com> Message-ID: <20030902154146.GA18455@nl.linux.org> brian wrote: > I am beginner using Python 1.52, GTK 1.2.10, and Glade .0.6.2 to > develop a gui which will kick off various scripts. Python 1.5.2 is very old, over 4 years. You are strongly encouraged to upgrade to a newer Python: make a large leap, and upgrade to Python 2.3! Sorry for not answering your question ;) Gerrit. -- 116. If the prisoner die in prison from blows or maltreatment, the master of the prisoner shall convict the merchant before the judge. If he was a free-born man, the son of the merchant shall be put to death; if it was a slave, he shall pay one-third of a mina of gold, and all that the master of the prisoner gave he shall forfeit. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From duncan at NOSPAMrcp.co.uk Fri Sep 12 04:14:00 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 12 Sep 2003 08:14:00 +0000 (UTC) Subject: os.listdir References: Message-ID: "Michael Peuser" wrote in news:bjq8pj$ho2$04$1 at news.t-online.com: > "Duncan Booth" > > [highly interesting details from Duncun] > > Where did you get all these details - reading Python compiler source > code? Sad to say, yes. Actually its mostly from reading the comments to the source code and there is even a file 'dictnotes.txt' in the source which describes a lot of the design decisions. See http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/*checkout*/python/python/dist/src/Objects/dictnotes.txt http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/*checkout*/python/python/dist/src/Objects/dictobject.c -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 10 15:55:31 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 10 Sep 2003 20:55:31 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> Message-ID: On Wed, 10 Sep 2003 19:05:20 +0000 (UTC), JCM wrote: >I enitirely missed the second half of your original post. Oops. It happens - you should see some of my goofs! From theller at python.net Sat Sep 27 15:16:50 2003 From: theller at python.net (Thomas Heller) Date: Sat, 27 Sep 2003 21:16:50 +0200 Subject: [Python-Dev] [development doc updates] In-Reply-To: <20030927190724.DDC8818F3E6@grendel.zope.com> (Fred L. Drake's message of "Sat, 27 Sep 2003 15:07:24 -0400 (EDT)") References: <20030927190724.DDC8818F3E6@grendel.zope.com> Message-ID: "Fred L. Drake" writes: > The development version of the documentation has been updated: > > http://www.python.org/dev/doc/devel/ > > The new glossary in the tutorial is really nice! Sure, but the hyperlinks don't work ;-) Thomas From mertz at gnosis.cx Tue Sep 9 14:14:04 2003 From: mertz at gnosis.cx (David Mertz) Date: Tue, 09 Sep 2003 14:14:04 -0400 Subject: Slight metaclass confusion References: Message-ID: ben at transversal.com (ben at transversal.com) wrote previously: |"Metaclass Programming In Python, Parts 1 and 2" |I get the fact that the instance of a metaclass is a class, but in |this case I fail to see why the following does'nt work: Read part 2 again. It takes a while to sink in. Your problem is that you aren't considering the MRO of Class: >>> class Meta(type): ... def __str__(cls): # Use 'return', not 'print' ... return "I am " + repr(cls) ... def foo(cls): ... return "I am " + repr(cls) ... >>> Class = Meta("Fish", (), {}) >>> Class.foo() "I am " Class is an instance of Meta, just like you expect. Calling the .foo() method shows this. But when you call a method, the method name is checked in the -method resolution order- (before the metaclass is checked): >>> Class.mro() [, ] Fish doesn't define a method .__str__(), so Python looks in Fish's parent, object. Well, object -does- define, .__str__(), so your call resolves to: >>> object.__str__() Traceback (most recent call last): File "", line 1, in ? TypeError: descriptor '__str__' of 'object' object needs an argument Of course, since object doesn't define a .foo(), resolution proceeds to the metaclass. If you want to get Class' metaclass method, you can let Python do the magic for you: >>> str(Class) "I am " Or if you want to be really explicit: >>> Class.__class__.__str__(Class) "I am " 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 cth at kyborg.dk Mon Sep 22 08:15:31 2003 From: cth at kyborg.dk (Claus Hemdrup) Date: Mon, 22 Sep 2003 14:15:31 +0200 Subject: ISDN / B-channel Message-ID: <3f6ee79d$0$182$edfadb0f@dread11.news.tele.dk> How do I read the B-channel? From piet at cs.uu.nl Mon Sep 8 08:04:32 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 08 Sep 2003 14:04:32 +0200 Subject: Is there a unicode EOF mark like DOS ascii ctl-z or unix crl-d ? References: Message-ID: >>>>> "Michael Geary" (MG) wrote: MG> Martin v. L?wis wrote: >> No, there is no need to have one (neither is there a need to have one >> for plain ASCII files): The end-of-file is when the file ends. Most >> operating systems support a notion of a "file size", and the file ends >> when file-size bytes have been consumed. >> >> Why Microsoft decided to use ctr-z in text files is beyond me, it does >> not fulfil any useful function... MG> It came from CP/M, which believe it or not had *no* way to specify an exact MG> file length. File lengths were measured in sectors, not bytes. So there had MG> to be some way to tell where a text file ended, and CP/M used Ctrl+Z. MG> MS-DOS picked up this convention, although if memory serves it always had MG> exact file lengths even in version 1.0. MG> Nobody uses Ctrl+Z in Windows/DOS text files any more, although I think the MG> COPY command still respects it if you use the /A switch or concatenate MG> files. I believe even stdio respects it when a file is opened in text mode. This is a common problem when people read binary files without specifying the "b" modifier: Apart from the stripped CR bytes they are often surprised that their programs stop reading early in the file. This even happens in Python. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From anuradha.k.r at sify.com Fri Sep 26 01:03:04 2003 From: anuradha.k.r at sify.com (anuradha.k.r at sify.com) Date: 25 Sep 2003 22:03:04 -0700 Subject: Python <-> C via sockets References: <8ad2cfb3.0309240113.19d9198a@posting.google.com> <8ad2cfb3.0309240628.dbbca33@posting.google.com> Message-ID: <57efaf35.0309252103.21565393@posting.google.com> hi, I 've already posted a message to this group but i think You guys can provide a solution faster.My problem is similar ,my client side (written in python) is not able to connect to the server side (written in C) in the same machine. my server side works perfectly fine and it waits for a connection to b established.However my client gives error "10061.connection refused".Will send you the code of both server side and client side.: server side: ------------ #include #include #include SOCKET recvSock,WinSocket,slisten; WSADATA WSAData; SOCKADDR_IN Acceptor; SOCKADDR_IN Connector; int TypeOfCon; int Initialise(); SOCKET ListenSocket(); int RecvBuff(BYTE * RecdBuffer,int size); void Close(); unsigned char * RecdBuffer; int main() { int flag; flag = Initialise(); slisten= ListenSocket(); flag = RecvBuff(RecdBuffer,20); Close(); return 1; } int Initialise() { WSAStartup (MAKEWORD(1,1), &WSAData); WinSocket = socket (AF_INET/*2*/, SOCK_STREAM/*1*/, 0); recvSock = socket (AF_INET/*2*/, SOCK_STREAM/*1*/, 0); return 1; } SOCKET ListenSocket() { int error; int sizeofaddr; sizeofaddr = sizeof(Acceptor); /*BOOL mcast ; mcast= TRUE;*/ Acceptor.sin_addr.S_un.S_addr = htonl(INADDR_ANY); Acceptor.sin_family = AF_INET; Acceptor.sin_port = 9999; bind(WinSocket,(const SOCKADDR *)&Acceptor,sizeof(Acceptor)); error = GetLastError(); if(error) { return 0; } listen(WinSocket,1); error = GetLastError(); if(error) { return 0; } recvSock = accept((SOCKET)WinSocket,(SOCKADDR *)&Acceptor,&sizeofaddr); error = GetLastError(); if(error) { return 0; } return recvSock; } int RecvBuff(BYTE * Buffer,int size) { int amount,error; amount = recv(recvSock,(char *)Buffer,size,0); error = GetLastError(); if(error) { return 0; } else return 1; } void Close() { closesocket(WinSocket); closesocket(recvSock); } client side: ------------- import socket #HOST = '130.10.5.38' # The remote host #PORT = 50007 # The same port as used by the server try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print 'socket not creadted' try: s.connect(("130.10.5.38", 9999)) except socket.error,msg: print 'error in connect' #s.send('Hello, world') #data = s.recv(1024) s.close() #print 'Received', `data` I'd gone thru the discussion above,so i guess probably the problem with my code is also on the port address only.Pls help. thanx, AKR. nick.keighley at marconi.com (Nick Keighley) wrote in message news:<8ad2cfb3.0309240628.dbbca33 at posting.google.com>... > Eric Brunel wrote in message news:... > > Nick Keighley wrote: > > > I'm probably missing something rather obvious, but is there a known > > > problem with getting a Python based socket program to communicate with > > > a C based socket program? A simple echo server written in Python > > > (the example from Python in a Nutshell actually) will happily talk > > > to a Python based client. If a C based client is substitued the connection > > > is refused (or so the C client reports). The C client will talk to > > > a C server. > > > > Communications between C and Python via sockets definetly work: we do that > > every day (no kidding ;-) > > > > Can you post an example of your code? > > by the time you read this the posted code may have appeared. > A call to htons() (convert unsigned short to network byte order) > was ommitted on the C side. > > this line:- > sin.sin_port = PORT; > > should read:- > sin.sin_port = htons(PORT); > > > thanks! From stephan.diehl at gmx.net Sun Sep 7 07:51:10 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Sun, 07 Sep 2003 13:51:10 +0200 Subject: Redesign of Python site References: Message-ID: > > The current site is, for me, one of the most readable sites aronnd. > The text colors work and it lets Internet Explorer adjust the text > size. > > The pollenation site is one of the worst I have seen. The mockup page > has teeny type that IE will not enlarge. (Telling me to use another > browser is besides the point. Lots of people will continue to visit > with IE even if I do switch.) The comments page has barely readable > dark-brown gray type on a lighter brown-gray background.. These pages > should only be used as examples of what not to do and how not to spoil > what we already have. It is absolutely beyond me, how IE should display the mockpage any differently than other browsers. On Mozilla, the page loads as: Stephan From thor__00 at yahoo.com Wed Sep 3 23:03:24 2003 From: thor__00 at yahoo.com (Thor) Date: Thu, 04 Sep 2003 05:03:24 +0200 Subject: Optionmenu. Message-ID: I have the following function (with some things removed): def add_stock(): stockw=Tk() stockw.title("New stock solution") sofl=Frame(stockw) sofl.pack() u=StringVar() u.set("M") cw=OptionMenu(sofl,u,"M","m","u","v","w") cw.grid(row=1,column=2) but the widget keeps not showing teh selected option. If I fo the same out of the function it works without problem (with stockw.mainloop()). What am I missing? Anybody can point me out to the solution/the right webpage? -- Thor -- Stockholm -- Sverige From tjreedy at udel.edu Sat Sep 6 16:30:49 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Sep 2003 16:30:49 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> Message-ID: <9oecnXGPy_Fn3seiXTWJiA@comcast.com> "Harri Pesonen" wrote in message news:Ucp6b.3992$ZB4.3874 at reader1.news.jippii.net... > I agree, it's not logical. Do my previous two responses today make the logic any clearer? > I'm learning Python at the moment, and like it very much. Try learning this. Class K method attribute f with params (s, *rest) can be called as K.f(Kinst, *rest), consistent with all other function calls. Abbreviation Kinst.f(*rest) makes the call look inconsistent by making K inplicit (and moving Kinst), but the same inplicitness enables runtime method lookup and superclass inheritance. I think the benefits that following are worth the minor bump in one's learning curve. Terry J. Reedy From gh at ghaering.de Sun Sep 7 15:26:41 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 07 Sep 2003 21:26:41 +0200 Subject: python module for MS SQL Server 7 or 2000? In-Reply-To: References: Message-ID: <3F5B8671.8090103@ghaering.de> Y2KYZFR1 wrote: > I have searched and only found references to using ODBC or some > ancient posts about some ancient sybase library under linux, neither > of which meets my critiera. [...] Tried Google? Doesn't look like so: http://www.google.com/search?q=python%20ms%20sql%20server -- Gerhard From mertz at gnosis.cx Sun Sep 7 21:07:37 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sun, 07 Sep 2003 21:07:37 -0400 Subject: Comments on Python Redesign References: Message-ID: "Tim Parkin" wrote previously: |Please could we move this discussion to one of the appropriate lists as |well. I suggest python-marketing to begin with. A marketing list is just not an appropriate forum for discussing redesigning the main python website. The page www.python.org just simply should not be driven primarily, or even significantly, by "marketing" issues... it's us developers who use it, in the overwhelming majority. We developers should not be treated as second class Python users because someone got the idea that the page should look like what PHBs expect. On the other hand... it seems like an entirely different site could look like that glossy pamphlet. Maybe something like: http://python-business.com/ Or even: http://enterprise.python.com/ Just as long as the main page doesn't get majorly uglified. Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From martin at v.loewis.de Tue Sep 9 14:08:05 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Sep 2003 20:08:05 +0200 Subject: Errors while compiling SWIG wrappers on Solaris In-Reply-To: References: Message-ID: Michael Schmitt wrote: > I tried some hints I found on the web: > "-shared" for compiling and linking. > "-fPIC". > "-Wl,-G". > > But none of these (also in combinations) worked. Any ideas? > > Thanks for any help. > Michael > > -------------------- > Text relocation remains referenced > against symbol offset in file > 0x2610 ../svm.o > 0x2614 ../svm.o svm.o is not position-independent. You need to compile *svm.o* with -fPIC. Passing that option to any other compiler commands, or the linker line, will be irrelevant. Once you've done that, you may find that additional object files are not position-independent, either, you then need to compile these with -fPIC as well. Regards, Martin From python at sarcastic-horse.com Sat Sep 6 11:05:44 2003 From: python at sarcastic-horse.com (python) Date: Sat, 6 Sep 2003 11:05:44 -0400 Subject: in CGI, how to include html pages? Message-ID: <20030906110544.78d7ea33.python@sarcastic-horse.com> Hi- I'm writing some CGI stuff and I'm doing it in python to force myself to learn the language. Anyway, I want to include some html at the top of every page but I'm not sure how. If the header is in header.html, what is the python-ese way of printing that out in my html? Thanks for the help. From joconnor at cybermesa.com Thu Sep 11 23:03:24 2003 From: joconnor at cybermesa.com (Fearless Freep) Date: 11 Sep 2003 20:03:24 -0700 Subject: Overlaying transparent images with PIL Message-ID: <7d3dc526.0309111903.2a4a044@posting.google.com> I know there's a PIL mailing list but I thought I would try the question here as well. I'm using PIL on Python 1.5.2 (stop laughing, it's what the ISP has for CGI and I don't have a choice) Anyway. I have a basic image and I need to overlay an image on top of it and let some of the basic image show through. Just as an aside the images are not of the same size and the top image needs to be pasted over the underlying image at an offset from the origin. I thought using GIF with transparency would do the trick but it doesn't seem to be working. Here's an example of what I am doing --------------- background = Image.open ("images/background.gif") overlay = Image.open ("images/overlay1.gif") overlaySize = overlay.size # a box for the overlay dimensions...offset by 100,200 overlayBox = (100, 200, 100 + overlaySize[0], 200 + overlaySize[1]) background.paste (overlay, overlayBox) backgroud.save ("images/tempfile.gif", "GIF") ---------------- Now, overlay2.gif is a gif file with a some transparency. However, where the transparency is becomes white instead. I suspect that I a mask image will be involved in the solution, but I'm not sure how to make a mask for my overlay image, or how to use it. Any suggestions? Take care, Jay O'Connor http://www.cybermesa.com/~joconnor/r4hsoftware - Custom Web and Application Software for Small Businesses --------------- From pythonhda at yahoo.com.replacepythonwithlinux Thu Sep 11 20:59:51 2003 From: pythonhda at yahoo.com.replacepythonwithlinux (pythonhda) Date: Thu, 11 Sep 2003 20:59:51 -0400 Subject: a quick program to download tv listings References: <1f0bdf30.0309102237.d29f0de@posting.google.com> Message-ID: <20030911205951.7ec85d81.pythonhda@yahoo.com.replacepythonwithlinux> On 10 Sep 2003 23:37:47 -0700 prochak at netzero.net (Erik Lechak) wrote: > Hello all, > > Is there anyone out there that has written anything in python to > download tv listings (no XML)? > > All the tv listing stuff that I can find is way too complex for my > taste (includes XML overkill or is not in python). I wrote the test > program below and it works. I am just curious if anyone has a more > robust python implementation before I take the time to add all the > bells and whistles. > > ... I felt the same way about the XML stuff, so what I did for a project was subclass the sgmllib.SGMLParser and use it to parse channel listings from tvlistings.zap2it.com. Their HTML was pretty bad so I had to write "clean up scripts" to strip out all the crap before I used the parser though. Take a look at ClientCookie [ http://wwwsearch.sourceforge.net/ClientCookie/ ] if you want to be able to login and personalize your listings before you download the HTML. From cnetzer at sonic.net Mon Sep 1 04:10:46 2003 From: cnetzer at sonic.net (Chad Netzer) Date: Mon, 01 Sep 2003 01:10:46 -0700 Subject: Declaration of an array of unspecified size In-Reply-To: References: Message-ID: <1062403846.1853.99.camel@adsl-209.204.179.133.sonic.net> On Sun, 2003-08-31 at 23:43, Bertel Lund Hansen wrote: > Ulrich Petri skrev: > >> self.mails=len(pop.list()[1]) > >you can skip the "mails" variable. len(mail) will give the same. > > Yes, I saw that in another posting. But I have a habit that I > aquired working with slow computers: always to substitute > function-calls with variables (faster). Is that a bad habit? Yes, because of the word "always". If you mean that literally, then I would consider it VERY bad style (sorry; no offense meant). This habit can be quite error prone, just because it is possible, even common, for your length variable to become out of sync with the true list length. These kinds of bugs can be very difficult to track down. It is best to use this habit sparingly, such as when you know your algorithm won't change the list, and you use the line length several times in quick succession, or in a small loop. That kind of thing is done all the time, on a very limited and local scale, and isn't necessarily bad. But don't always do it just for the sake of doing it. Only do it where it is a known bottleneck (or you know it will remain coorect, and it makes the code easier to express) Python's lists are not 'linked lists', btw, and the length operation is very fast (O(1)), because the length is always known exactly, and can be gotten with a fast lookup (ie. it doesn't have to count). The function call overhead in python is a bit high, but presumably your program calls LOTS of functions; a few more len() calls will have virtually no effect, outside of loops. Finally, you can google for the term "memoize python" on Google, which will demonstrate a technique for automatically caching function call results, which you may find interesting. -- Chad Netzer From pinard at iro.umontreal.ca Wed Sep 3 19:56:22 2003 From: pinard at iro.umontreal.ca (Francois Pinard) Date: 03 Sep 2003 19:56:22 -0400 Subject: Quickie mail.python.org status In-Reply-To: <727daa7e.0309031140.1af820b2@posting.google.com> References: <727daa7e.0309031140.1af820b2@posting.google.com> Message-ID: [Skip Montanaro] > They said it was going to be bad after everyone returned from the long > holiday and late-summer vacations. I guess they were right... On the other hand, I've read somewhere (on the Symantec site, I think), that at least some varieties of the virus will turn themselves off on September 9'th. I do not understand why the bad guys would have programmed such a deadline within their code, but I still wish this deadline story is true! -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From tjg at craigelachie.org Sat Sep 6 21:35:43 2003 From: tjg at craigelachie.org (Timothy Grant) Date: Sat, 6 Sep 2003 18:35:43 -0700 Subject: OT: best book in years In-Reply-To: References: <3F5891C8.A7DD1A20@hotmail.com> Message-ID: <200309061835.44498.tjg@craigelachie.org> On Saturday 06 September 2003 08:00 am, Aahz wrote: > In article <3F5891C8.A7DD1A20 at hotmail.com>, > > Alan Kennedy wrote: > >On a lighter note, a fantastic book that I really enjoyed reading (for > >leisure) was > Military SF: David Weber (start with _On Basilisk Station_) or Lois > McMaster Bujold (start with _Shards of Honor_, but don't read _Barrayar_ > yet if you pick up the _Cordelia's Honor_ omnibus). I was wondering if anyone was going to mention Weber and Harrington. My wife bought me _War_of_Honor_ for Christmas last year, solely because I wanted to support a company that would put a CD of an entire fiction series in the back of a book. I'm not a science fiction fan in anyway shape or form--or should I say wasn't. I'm a few chapters in to _Ashes_of_Victory_ now, and have not had anywhere near so much fun reading anything in years as the Honor Harrington books. I loved Forrester's Hornblower, and now I love Weber's Harington. -- Stand Fast, tjg. Timothy Grant www.craigelachie.org From http Sun Sep 14 17:12:52 2003 From: http (Paul Rubin) Date: 14 Sep 2003 14:12:52 -0700 Subject: Java Checked Exceptions References: <8ef9bea6.0309140709.14fc9712@posting.google.com> <7xy8wr45b9.fsf@ruckus.brouhaha.com> Message-ID: <7xd6e3vzu3.fsf@ruckus.brouhaha.com> "John Roth" writes: > My take on the issue is that at the time Java was designed, > the whole notion of checked exceptions was a hot topic in > the academic and language design community, and so it got > in before there was enough experience with using it in large > programs to show that it simply didn't scale well. But I thought Ada uses checked exceptions, and huge systems have been built in Ada. What's the deal? From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Tue Sep 16 15:01:37 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Tue, 16 Sep 2003 23:01:37 +0400 Subject: why pass statement? In-Reply-To: References: Message-ID: M-a-S wrote: > Why is there the pass statement? I think, the expression statement would be enough: > > class C: > None > > while True: > None > No. None is just a value (now variable), not a statment. hth, anton. From mertz at gnosis.cx Tue Sep 30 13:13:57 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Tue, 30 Sep 2003 13:13:57 -0400 Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> <3f7918e1-cebe25d5-ba02-4762-ae3e-ad3bb70874cb@news.szn.dk> <_e9eb.9852$NX3.7090@newsread3.news.pas.earthlink.net> Message-ID: |> > So I only expect around 5,428,681 primes less than 10^8 to occur. |> > Well, that's not SO much less than 7.8M. |Klaus Alexander Seistrup |> I found 5,761,455 primes < 1E8. "Andrew Dalke" wrote previously: |http://www.utm.edu/research/primes/howmany.shtml has the same number. |(found by googling for "5,761,455" - 3rd hit. :) Looking at Andrew's resource, I am reminded that N/(log(N)-1) is a better approximation for "primes up to N" than was Gauss' original. Of course, as I wrote, both are accurate at the asymptote. But infinity is a long way to go. >>> N = 10**8 >>> N/(log(N)-1) 5740303.8072846411 That looks assuringly closer to the specific total than my first pass. Obviously, enumeration of all the primes in the range is still more accurate than any such approximation formula (some further such approximations can be found at the above URL, and elsewhere). Yours, Lulu... -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From CousinStanley at hotmail.com Tue Sep 2 11:23:28 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 2 Sep 2003 08:23:28 -0700 Subject: TKinter is driving me crazy! References: <3285.208.224.10.29.1062445601.squirrel@webmail.iserv.net> Message-ID: | Frames don't have titles, but toplevels do. | Try using the 'title()' method of the toplevel widget. Daniel ... Thanks for the reply ... I'm familar with applying the title() method to a Tkinter root or Toplevel object, but couldn't figure out how to change the title on a sub-classed frame like the one Jp posted after noticing a default title of tk in the titlebar of the rendered window ... -- Cousin Stanley Human Being Phoenix, Arizona From max at alcyone.com Sun Sep 14 21:11:41 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 14 Sep 2003 18:11:41 -0700 Subject: No "side effect" assignment! References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> <75b7596ef938ab8af18b663ddd7eaf50@news.teranews.com> Message-ID: <3F6511CD.EF0909CB@alcyone.com> Andrew Koenig wrote: > How about this instead: > > def make_generator(func): > while x = func(): ^^^^^^^^^^ Not too likely in Python :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Youth is a period of missed opportunities. \__/ Cyril Connolly From martin at v.loewis.de Sun Sep 21 16:59:34 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Sep 2003 22:59:34 +0200 Subject: Trouble sorting lists (unicode/locale related?) In-Reply-To: <87y8wh50ca.fsf@pobox.com> References: <87y8wh50ca.fsf@pobox.com> Message-ID: John J. Lee wrote: >>>locale.setlocale(locale.LC_ALL, ("no", None)) > > [...] > >>If this did work, then you can use the DSU pattern like so: > > [...strxfrm...] > > The advantage of which is that you don't have to mess with the locale. No, it doesn't. strxfrm requires that the locale is adjusted to the desired LC_COLLATE facet. Otherwise, it will collate according to the C locale (in which case strxfrm is the identity). Regards, Martin From cedmunds at spamless.rochester.rr.com Sun Sep 21 15:25:58 2003 From: cedmunds at spamless.rochester.rr.com (Cy Edmunds) Date: Sun, 21 Sep 2003 19:25:58 GMT Subject: Help me choose a C++ compiler to work with Python References: <616fccba.0309210907.1e35b92d@posting.google.com> Message-ID: "rhmd" wrote in message news:616fccba.0309210907.1e35b92d at posting.google.com... > Just found Python and I love it. What an elegant language! Yeah, me too. :) > I would like to use it for various applications, but the > mathematical calculations are way too slow (a million sines 8 seconds > in Python vs. 2 seconds in Excel VBA), so was thinking of learning > enough C++ to do the number crunching in C++ and integrating the C++ > routines with Python. This one really has me squirming in my seat. C++ isn't a very good language for learning just a little bit of. Compared to Python I would say the learning curve is much steeper. It offers a lot of control over how the object code is generated but that also makes it dangerous for casual users. If you do it wrong a lot of bad things can happen, including poor performance -- although poor performance would perhaps be the best of those bad things! I suggest you look at various Python libraries to do whatever numerical processing you might need to do. They are mostly written in C anyway so their performance is excellent. For instance, I use SciPy for Fourier analysis and PIL for image processing, getting good performance on these numerically intensive tasks without ever leaving the ease and comfort of good old Python. My question: > My question: > Which compiler works best with Python? I wouldn't choose your C++ compiler for Python compatibility. How good is the debugger? How is the standards conformance? C++ compilers vary widely in these and other important criteria. > I use Windows XP and 98. Have very little experience with C++. Am > doing statistical and other simulations that require billions of > calculations (taking 1 to 2 hours in Excel VBA). Take a look at the UVS library under my sig for some C++ code which I have found useful for statistical simulations. GCC is free, MS > C++.Net is affordable at <$100 but supposedly has problems until the > next version (and I could only use it on my XP machine), older > versions of MS C++ are no longer for sale. What's the most robust > solution? The .NET compiler has a very good debugger and much better standard compliance than the old 6.0 compiler, but I haven't used lot of different recent vintage C++ compilers. I would also like to make .dll files that I can plug into > MS Excel. I generally use COM objects written in Python to connect to Excel. I am very pleased with that technique. http://starship.python.net/crew/mhammond/ > Sorry for the vagueness of this question, but I'm sure many of you > have experience with this and any information, opinions, and even > prejudices about the various compilers are welcome. > Thanks. -- Cy http://home.rochester.rr.com/cyhome/ From sfb at alysseum.com Thu Sep 18 14:34:44 2003 From: sfb at alysseum.com (Simon Bayling) Date: Thu, 18 Sep 2003 18:34:44 +0000 (UTC) Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> <3y7ab.1043$Od.78860@twister.tampabay.rr.com> <3f697584$0$10966$fa0fcedb@lovejoy.zen.co.uk> Message-ID: Since you mention this, on my windows dual-monitor setup, The BlackAdder splash screen and tips box open in the middle, spanning the gap between displays... Cheers, Simon. > Freeback, > suggestions, criticism (good or bad), etc is essential for the > developement and improvement of any software project. I will make sure From peterm at resmed.com.au Mon Sep 29 16:07:25 2003 From: peterm at resmed.com.au (Peter Milliken) Date: Tue, 30 Sep 2003 06:07:25 +1000 Subject: [ANN] pylint-0.2 References: <3F782D20.5BB43A1F@engcorp.com> Message-ID: <1i0eb.275$t44.11623@nnrp1.ozemail.com.au> Hi Peter, No, I caught all of the dependencies that are required (common libraries and optik - I think that is all that is required). I installed both of them before attempting to run pylint and still received that error. Perhaps the install is order dependent i.e. I installed pylint, then the "common libraries" then the optik package. Does Pylint work for you? Peter "Peter Hansen" wrote in message news:3F782D20.5BB43A1F at engcorp.com... > Peter Milliken wrote: > > > > I get the same error. > [snip] > > (I have a personal hangup with people who > > write good, useful packages and then don't bother documenting them - life is > > just too short to read somebody else'e code to get around this deficiency > > :-) I get frustrated however when I think there is something that I could be > > taking advantage of but something as simple as the lack of 0.5hr of > > documentation stops me :-( ). > > Maybe RTFM would help. See http://www.logilab.org/projects/pylint/documentation and > note the "dependancies" (sic) line which states "Pylint requires the > logilab-common(version >= 0.2.1) and the optik packages." > > If you download the "Common libraries" from the links provided on that page, > I suspect it will work better. > > Unfortunately, by posting the direct link to the download I suspect Alexandre > led people astray by implying that a single download might be enough to make > this work. > > -Peter From sholden at holdenweb.com Thu Sep 11 08:54:20 2003 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 11 Sep 2003 12:54:20 GMT Subject: Using Python under ASP References: Message-ID: <0g_7b.169$o71.168@news2.central.cox.net> "Max Ischenko" wrote in message news:bjmiej$ihe$1 at voodoo.volia.net... > > Hi, > > I'm using Python under ASP env. and have a question about how to > communicate Python snippets in different pages. > > For example, I'd like to create a per-session object of class FooBar and > be able to access it from any page. How could I do this? > > I can't store anything complicated in a Session. Why not? Because Microsoft says so? Becuase your employer says so? What's "complicated"? Initially, MS promoted the Session object as the place to store session state. Then they found that uninformed idiots were saving stupid things like large ADO resordsets in Session in large numbers, and getting locking and/or synchronization problems across multiple sessions. Who would have thought that crappy design could have resulted in crappy performance? Also, the larger players complained that the mechanism didn't scale across multiple servers (because it's host-specific). So the conventional advice became "don't store complex objects in Session, find some other mechanism". And software vendors and authors made stacks of money creating and writing about replacement mechanisms. > Someone here propose pickle/unpickle an object to the string but that > feels like a kludge. Should I setup some global hash, keyed by SessionID > to store data there? > If you can convince me that this will actually generate any saving then you might try it, but personally I'd try saving it in Session and seeing whether that worked OK for your application. The advantage of pickling would be that you aren't leaving a reference to an object lying around between page invocations,. One last point: if the reason you "can't save anything complicated in a Session" is because your employer's programming standards say so, then a) ask them to define "complicated", and b) start dicreetly looking for new employment :-) regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From tim.one at comcast.net Fri Sep 5 23:28:55 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 5 Sep 2003 23:28:55 -0400 Subject: Python port to Swiss Ephemeris work with 2.3? In-Reply-To: <20030906031459.GA1186@isis.gerrietts.net> Message-ID: [John Roth] >> You need to recompile using the same compiler that Python was >> compiled with (I believe that's VC 6 for the Windows version.) >> Extension modules ***always*** need to be recompiled for major >> Python releases. [Geoff Gerrietts] > Is that really true under Windows? Yes, and also for minor releases (the j in i.j.k). > It's not true on Unix releases: Also true. > Guido takes exquisite care to make sure that Python releases are > binary-compatible. Is it possible that moving the file around somehow > might make Python sufficiently aware? Nope. On Windows, the core DLL is named differently for each minor release (e.g., Python22.dll for all 2.2.k releases, but Python23.dll for all 2.3.k releases), and extension modules have the name of the DLL they require embedded in them. This makes it very easy to have multiple versions of Python installed on Windows, which is harder than it is on Linux because the core DLLs usually end up in the same magical (to Windows) "system directory". OTOH, it can be a PITA for people using lots of extension modules on Windows. > Geoff Gerrietts > -rw-rw-rw-: permissions of the beast LOL! From peter at engcorp.com Wed Sep 10 21:17:46 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 10 Sep 2003 21:17:46 -0400 Subject: Trouble Learning Zope References: Message-ID: <3F5FCD3A.ACB83234@engcorp.com> Bob Parnes wrote: > > I just installed zope, version 2.6.1-10 on a debian distribution, but I > cannot get to second base. When I try to add the tutorial to a folder, I > get an error message stating that an emergency user cannot own an > object. So I clicked onto the help page and found the tutorial there. > But I got the same error when I tried to follow it. Then I created a new > user account and restarted zope. But it would not accept a login as the > new user, only as the original, 'emergency' user. As things stand, I can > bring up zope on my browser but cannot do anything in it. > > What can I do to straighten things out. Thanks for any help. 1. When you create the new user, make sure you've set it up for "manager" privileges. 2. Subscribe to the zope mailing list, as this newsgroup does relatively little support for Zope while the mailing list is the place to be... (see the Zope web site to subscribe). -Peter From peter at engcorp.com Mon Sep 29 09:01:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 29 Sep 2003 09:01:20 -0400 Subject: [ANN] pylint-0.2 References: Message-ID: <3F782D20.5BB43A1F@engcorp.com> Peter Milliken wrote: > > I get the same error. [snip] > (I have a personal hangup with people who > write good, useful packages and then don't bother documenting them - life is > just too short to read somebody else'e code to get around this deficiency > :-) I get frustrated however when I think there is something that I could be > taking advantage of but something as simple as the lack of 0.5hr of > documentation stops me :-( ). Maybe RTFM would help. See http://www.logilab.org/projects/pylint/documentation and note the "dependancies" (sic) line which states "Pylint requires the logilab-common(version >= 0.2.1) and the optik packages." If you download the "Common libraries" from the links provided on that page, I suspect it will work better. Unfortunately, by posting the direct link to the download I suspect Alexandre led people astray by implying that a single download might be enough to make this work. -Peter From jepler at unpythonic.net Thu Sep 18 20:32:14 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 18 Sep 2003 19:32:14 -0500 Subject: Forcing getopt to process a specific option first?? In-Reply-To: <3F69F6C3.50605@asml.nl> References: <3F69F6C3.50605@asml.nl> Message-ID: <20030919003208.GB9792@unpythonic.net> Care for another solution? I'd simply do two passes over the argument list. This has an advantage over both the other alternatives proposed. First, it works if the user writes something like "-bccf" (equivalent to the arguments ["-b", "-c", "cf"]), and second it works with repeated options like [-a", "x", "-a", "y"]. This doesn't work if something in the configuration file could affect the available set of commandline switches. There may be some other shortcoming I haven't considered yet, too. Jeff ######################################################################## # Program import getopt def main(argv): args, rest = getopt.getopt(argv, "c:a:b") # First pass, parse any -c option for k, v in args: if k == "-c": print "Using config file", v # Next, parse the other options for k, v in args: if k == "-c": continue print "Processing switch", k, v print "Remaining positional arguments", rest argv = "-a x -bccf -a y ...".split() main(argv) ######################################################################## # Output Using config file cf Processing switch -a x Processing switch -b Processing switch -a y Remaining positional arguments ['...'] From danielk at aracnet.com Sat Sep 6 21:49:41 2003 From: danielk at aracnet.com (Daniel Klein) Date: Sat, 06 Sep 2003 18:49:41 -0700 Subject: [2.3] object does not appear to be a reserved word References: Message-ID: Thanks John., that's what I suspected. This particular module uses the variable 'object' as an argument to several methods and functions. I'll probably change it anyway, but I was just curious as to why it seemed to run ok. Thanks again for the confirmation. Dan On Sat, 6 Sep 2003 15:47:07 -0400, "John Roth" wrote: > >"Daniel Klein" wrote in message >news:v89klvsupdoe39e6trqbbqvmhfgecnoum8 at 4ax.com... >> Is it potentially dangerous to use the variable 'object' in code? > >"object" is, I believe, a built-in type in the builtins namespace. >As such, you can shadow it so it's inacessable. However, >the only place were that could cause problems is if you >use it as an identifier at the module level. I think. > >John Roth >> >> Thanks, >> Daniel Klein > From selwyn at home.net.nz Tue Sep 30 05:56:42 2003 From: selwyn at home.net.nz (selwyn) Date: Tue, 30 Sep 2003 21:56:42 +1200 Subject: Python mascot? How about a Pythoneer? In-Reply-To: References: <1064860580.3f787ba4b7295@mcherm.com> Message-ID: [snip] > I agree. See Disney's Robin Hood and Jungle Book for creative ways of using > snake characters. Also, a lack of arms never stopped Homestar Runner[1] from > eating, reading, etc. :) > > -Dave > > [1] http://www.homestarrunner.com > that goes for the blue racer as well!!! http://lostkartoon.tripod.com/blueracer.htm From mark at diversiform.com Tue Sep 9 12:39:05 2003 From: mark at diversiform.com (mark) Date: Tue, 9 Sep 2003 09:39:05 -0700 Subject: I need to make Excel/Powerpoint-style charts. In-Reply-To: <56665.199.169.240.132.1063120715.squirrel@svr1.turboweb.net> Message-ID: <004601c376f0$e36e6f80$5501a8c0@markxp> This isn't a terribly helpful post, but I wrote a script that would collect data from a database using an SQL query. This data was written to a file which was then imported into Excel using a macro to do all the sorting and chart creation. I guess there's a learning curve either way, but it is another way to go about it, since you mentioned that you're using Excel already. I believe it's possible to call out an instance of Excel and provide arguments to tell it which file to open and what to do with it. I'm sure there's someone here with a better idea on exactly how to do that (I didn't get that far before I changed jobs). - Mark -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of python at sarcastic-horse.com Sent: Tuesday, September 09, 2003 8:19 AM To: python-list at python.org Subject: I need to make Excel/Powerpoint-style charts. Hi- My office produces a lot of charts based on time-series data. We use MS powerpoint and excel to make these charts. The data gets updated regularly, but there doesn't seem to be an easy way to automate updating the charts using these packages. So, we spend a non-trivial amount of time manually updating lots of spreadsheets to redraw the charts we need. I hope to find some sort of python graphics library that can make charts similar to Excel and Powerpoint, and then I can start automating these tasks. Here is an example of the charts we make: http://www.sarcastic-horse.com/example.pdf #52k size file. Are there any packages that can do similar charts? I need to be able to chart time-series data with occasional missing observations. I also need to be able to shade some regions of the charts, and add text titles, captions and notes. I'm (slowly) learning the reportlab package, and it looks good, but I wanted to check if there was an even better solution out there. Thanks for the help. -- http://mail.python.org/mailman/listinfo/python-list From op73418 at mail.telepac.pt Mon Sep 1 18:01:12 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 01 Sep 2003 23:01:12 +0100 Subject: exception question References: Message-ID: On 1 Sep 2003 20:35:08 GMT, bokr at oz.net (Bengt Richter) wrote: >On Sun, 31 Aug 2003 22:22:15 +0100, Gon?alo Rodrigues wrote: > >>Hi, >> >>For error processing I found convenient maintaining a dictionary where >>the keys are exception *classes* and the values are callables. Of >>course, for this to work, exception classes have to be hashable which >>I happily found that they were. So my question is, can I count on this >>behaviour? Or is this behaviour I should not count on? (I found >>nothing on the docs about it, thus the question). >> >Would the class name strings work for you, to avoid the issue? > Yes! Thanks! It's not as pretty but it will work perfectly. I may still harass the python-dev folks as suggested though ;-) With my best regards, G. Rodrigues From janeaustine50 at hotmail.com Thu Sep 4 00:23:00 2003 From: janeaustine50 at hotmail.com (Jane Austine) Date: 3 Sep 2003 21:23:00 -0700 Subject: Active Scripting in Python Message-ID: I donwloaded win32all for Python 2.3 and installed it. I manually run pyscript.py and it returned "successfully registered" message. For a simple test(on client side), I created the following html: And opened it in IE6.0 on WinXP. Unfortunately, it doesn't show anything. After googling, I tried "pyscript.py --debug" and the trace collector shows: Object with win32trace dispatcher created (object=None) in _InvokeEx_ with GetInterfaceSafetyOptions 0 1 (IID('{BB1A2AE2-A4F9-11CF-8F20-00805F2CD064}'),) None None in _InvokeEx_ with GetInterfaceSafetyOptions 0 1 (IID('{BB1A2AE1-A4F9-11CF-8F20-00805F2CD064}'),) None None Am I doing something stupid? Jane From mcfletch at rogers.com Mon Sep 22 01:01:14 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 22 Sep 2003 01:01:14 -0400 Subject: Toronto Pythonistas, don't forget the PyGTA meeting this Tuesday... Message-ID: <3F6E821A.2050504@rogers.com> 8PM, usual place, (519 Community Centre). You can find all the details here: http://web.engcorp.com/pygta/wiki/NextMeeting Enjoy, and hope to see you all out, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From nav+posts at bandersnatch.org Fri Sep 5 23:01:49 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 05 Sep 2003 23:01:49 -0400 Subject: OT: best book in years References: <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <3F5868BA.85F506B4@engcorp.com> Message-ID: "Michael Peuser" writes: > So I should contribute another clasical book: > Hofstadter: Goedel Escher Bach Good god, man! The guy's already going to be in the hospital. GEB is something that should be tackled at full health. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From cavok at freemail.it Thu Sep 4 19:13:30 2003 From: cavok at freemail.it (Domenico Andreoli) Date: Thu, 04 Sep 2003 23:13:30 GMT Subject: this is my own python-setuid.c In-Reply-To: References: Message-ID: Domenico Andreoli wrote: > Hi, > > I did a little research about execution of Python setuid scripts. I > found only a couple of C wrappers I don't like. So I wrote my own, it is > available at [0]. Feel free to send comments. > yes, it is heavily based on the one found in the Python source tree. -----[ Domenico Andreoli, aka cavok --[ http://filibusta.crema.unimi.it/~cavok/gpgkey.asc ---[ 3A0F 2F80 F79C 678A 8936 4FEE 0677 9033 A20E BC50 From xnews at fredp.lautre.net Wed Sep 17 12:30:08 2003 From: xnews at fredp.lautre.net (Fred Pacquier) Date: 17 Sep 2003 16:30:08 GMT Subject: replace %(word) in a string References: Message-ID: Mirko Zeibig said : > Especially useful together with the locals() function, which returns a > dictionary of locally defined variables: > > def foo(): > a = "Hello" > b = "World" > print "%(a)s %(b)s" % locals() Yes, that's a wonderful feature. Recently though, I've wondered a couple of times : is there an easy way to substitute with both local AND global variables ?... -- YAFAP : http://www.multimania.com/fredp/ From fgeiger at datec.at Tue Sep 9 14:25:00 2003 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 9 Sep 2003 20:25:00 +0200 Subject: My future Python IDE article References: Message-ID: <3f5e1aaf@news.swissonline.ch> Hi David, 1) WingIDE 2) Komodo 3) IDLE And now for something completely different: 4) The really world's best outliner (man, I tried quite a few) and Literate Programming Tool: Leo Best regards Franz GEIGER P.S.: I've listed Leo as (4) because I do not use it for programming, but others do, with great success by the way. I use it to organize my projects, contacts, as calender, as - well, for each and everything. And thru its Clone-feature everything is always just a click away from where I am in my outlines. And it's scriptable and and and. In short: I organize myself with Leo. I do this since April 2003, still with great pleasure. Using Leo is like programming Python: Each day's a pleasure like the first day. So, would you have asked for PIMs to be suggested I would have written 1) Leo 2) Leo 3) Leo 4) Leo Sory, I'm getting OT now... "David Mertz" schrieb im Newsbeitrag news:mailman.1061920192.21278.python-list at python.org... > Pythonistas, > > My loyal fans :-) will remember that I did a Python IDE roundup for > _Charming Python_ a couple years back. Now I have another such roundup > lined up... not the very next article, but it's there on the list. > > In the intervening years, I've hardly touched anything one might call an > IDE. I've looked at screenshots from time to time, and read various > announcements. But really I just use text editors and command lines. > > Here's the thing: I probably have room to look at about four different > tools in one article. In fact, it wouldn't be absurd to only do three. > Past that, I cannot do more than list contact information and platform > in the available words. I'm sure there are more than four IDEs that > -someone- loves to work with out there... but I need to have a cutoff. > > So c.l.py readers... make the case for your favorite one getting on the > list. I have a while to ponder the opinions advanced, should this > prompt some discussion (it may take a little while to order review > copies of commercial tools and/or get things installed). > > 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 jjl at pobox.com Mon Sep 22 07:05:49 2003 From: jjl at pobox.com (John J. Lee) Date: 22 Sep 2003 12:05:49 +0100 Subject: Where to publish my code References: <1f0bdf30.0309212039.16c9bef0@posting.google.com> Message-ID: <87r829t75e.fsf@pobox.com> prochak at netzero.net (Erik Lechak) writes: [...] > 1) Vaults of Parnassus - have not tried it yet. The registration > process makes it looks like they don't provide the space for the > application. I could be wrong? I've never heard that they provide web space. > 2) Sourceforge - A little too bloated for my needs. But they do > provide the space to put my code. I used them before and it was kind > of a pain to do updates. [...] Just ignore their file release system (which is apparently going away soon anyway). That's what I do -- treat it as free web space. All you need is scp and ssh. You can shut down their bug tracking system too, so people don't start posting stuff there. SF doesn't provide download stats, since it's expensive for them to provide (apparently). 4) GNU has an SF clone called Savannah. John From colarte at telesat.com.co Fri Sep 26 08:53:35 2003 From: colarte at telesat.com.co (Camilo Olarte) Date: Fri, 26 Sep 2003 07:53:35 -0500 Subject: Q: How to Change Pmw.ComboBox width ?? In-Reply-To: <1064568803.24328.1.camel@m-franklin> References: <20030926041434.4943182a.colarte@telesat.com.co> <1064568803.24328.1.camel@m-franklin> Message-ID: <20030926075335.3d2d3c15.colarte@telesat.com.co> On Fri, 26 Sep 2003 10:33:24 +0100 Martin Franklin wrote: > entry_width = 3 Thats Exactly what I needed , thank you very much. Camilo Olarte From mark at hahnca.com Tue Sep 30 00:38:39 2003 From: mark at hahnca.com (Mark Hahn) Date: Mon, 29 Sep 2003 21:38:39 -0700 Subject: [ANN] pylint-0.2 References: Message-ID: They not only feel no need to document, they also feel no need to follow ANN threads they start. "Peter Milliken" wrote in message news:ToKdb.9$t44.805 at nnrp1.ozemail.com.au... > I get the same error. > > I tried to find documentation to see whether I was using Pylint correctly or > not but there isn't any. There seems to have been an attempt at providing > the possible command line options (python pylint.py --help) but I don't find > them particularly self-explanatory - so without documentation and the > apparent ability to "run out of the box", I guess I'll just have to give > this one a miss. > > One nice thing that has happened is it has led me to the Optik package > (Option parsing). There is some nice documentation for this package - the > author(s) of Pylint could take some direction from this package if they > really want people to use Pylint (I have a personal hangup with people who > write good, useful packages and then don't bother documenting them - life is > just too short to read somebody else'e code to get around this deficiency > :-) I get frustrated however when I think there is something that I could be > taking advantage of but something as simple as the lack of 0.5hr of > documentation stops me :-( ). > > In the meantime, I'll just have to watch this space :-) > > Peter > > > "Mark Hahn" wrote in message > news:EBkdb.3354$hp5.1305 at fed1read04... > > > > > Pylint is a lint-like tool for Python code > > > > Does pylint only work for modules? When I tried to run it on my code file > > (ezpicmailer.py) , it raised an exception: > > > > No config file found, using default configuration > > > > Exception: Unable to find module for C:\photoedit\ezpicmailer in > > > > > > and then it gave a long list of modules in my sys.path. It seems to > insist > > that the argument I give it be a module in sys.path, not just an arbitrary > > python code file. > > > > ------------------------------------------ > > > > "Alexandre Fayolle" wrote in message > > news:mailman.1064594507.31702.python-list at python.org... > > Logilab has released pylint-0.2 > > > > What's new? > > ----------- > > > > In addition to a large number of bug fixes, this release adds two new > > checkers, for missing encoding declaration, and for FIXME comments. Zope > > support was improved. > > > > About Pylint > > ------------ > > > > Pylint is a lint-like tool for Python code. It performs almost all the > > verifications that pychecker does, and additionally can perform some > > stylistic verification and coding standard enforcements. The checked > > code is assigned a mark based on the number and the severity of the > > encountered problems. The previous mark of a given piece of code is > > cached so that you can see if the code quality has improved since the > > last check. > > > > URLs > > ---- > > > > Homepage: http://www.logilab.org/projects/pylint > > Download: ftp://ftp.logilab.org/pub/pylint/pylint-0.2.tar.gz > > > > > > -- > > Alexandre Fayolle > > LOGILAB, Paris (France). > > http://www.logilab.com http://www.logilab.fr http://www.logilab.org > > D?veloppement logiciel avanc? - Intelligence Artificielle - Formations > > > > > > From wtrenker at shaw.ca Fri Sep 19 10:09:52 2003 From: wtrenker at shaw.ca (William Trenker) Date: Fri, 19 Sep 2003 14:09:52 +0000 Subject: [OT] New Play: SPAMELOT In-Reply-To: References: Message-ID: <20030919140952.4a6583b5.wtrenker@shaw.ca> On Fri, 19 Sep 2003 15:37:44 -0400 Terry Reedy wrote regarding Re: [OT] New Play: SPAMELOT: > I nominate whoever sent me over a thousand fake MS Update + attachment > spams in the last 24 hours. I nominate for hero: Spambayes! I have never received so many virus-related spam messages as this latest 'Swen' virus. Even the recent 'Klez' virus didn't come close on volume of spam messages received. This latest one has been such a pain that yesterday I decided to try out Spambayes. I have Python 2.3 on Linux here, using Sylpheed for email. I was pleasantly surprised how easy it was to setup Spambayes and its pop3proxy.py application. I waited (not long) for a few of the virus messages to come my way, trained Spambayes on just those few messages, and haven't been bothered since. I would also nominate Spambayes as Python App of the Year! Spambayes certainly is a showcase of the sophistication, and practicality, that can be achieved using Python 'out of the box'. Bill From bdesth.nospam at removeme.free.fr Sat Sep 20 06:56:12 2003 From: bdesth.nospam at removeme.free.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2003 12:56:12 +0200 Subject: urls on securing python on a shared hosting ? Message-ID: <3f6c2f8a$0$20641$626a54ce@news.free.fr> Hi everyone ! Could someone point me to infos about securing python for use as CGI or mod_python for a shared hosting environnement ? I searched google, but did not find anything specific :( I'm not an admin myself, but I try to convince my hosting admins to install Python. For now, their answser is that they don't know how to secure this, and have not time to learn how to do it. (NB : this is a 'cooperative' hosting service, not a commercial one...) TIA Bruno -- http://bdesth.free.fr http://www.laotseu.net -- From Harri.Pesonen at wicom.com Thu Sep 4 04:28:31 2003 From: Harri.Pesonen at wicom.com (Harri Pesonen) Date: 4 Sep 2003 01:28:31 -0700 Subject: Embedding Python in multi-threaded app Message-ID: <17fbc98a.0309040028.6776d426@posting.google.com> Hello. Thanks to the message below (http://groups.google.fi/groups?selm=dkuhlmanF1KAr0.5J9%40netcom.com), I was able to do the same, almost. I have currently only one problem. When I call Py_Finalize() when the dll terminates, it crashes. I have Python 2.3. Everything else works, I have run many different scripts in threads. I wonder if someone has noticed anything similar, and perhaps found a solution. Also I don't understand PyThreadState_Swap(interp) call below, but it does not work properly without it, the thread termination hangs without it. The documentation says that Py_NewInterpreter() already makes the new state current. Thanks for any help! Harri --- Original message below ---- Thanks for comments from Guido. I have a very preliminary version working with Python embedded in a multi-threaded C++ application. I'd like to summarize what I'm doing so that others will have an example to follow or so that someone can correct me if I'm still doing something wrong. My application creates multiple threads, one for each end-user session. I create a separate Python sub-interpreter for each thread (session), then evaluate scripts in that session with the sub-interpreter for that session. I do this so that within a session, scripts are evaluated under a context/environment local to that session and so that the scripts in a session do not share (borrow or steal) global values, imported functions, etc from other sessions. Thus, my users (who are developing Python scripts) can write scripts from the viewpoint that the scripts for each session will run in their own little world under their own separate environment. I view this as a very important benefit that embedded Python gives me. Here is a summary of my latest code: // At the very beginning of the application. Py_Initialize(); PyEval_InitThreads(); PyEval_ReleaseLock(); o o o // Here we are in the constructor for a session. PyEval_AcquireLock(); interp = Py_NewInterpreter(); // Note that this application has multiple threads. // It maintains a separate interp (sub-interpreter) for each thread. PyThreadState_Swap(interp); // Call some Python C/API functions here PyEval_ReleaseThread(interp); o o o // Get sub-interpreter for current thread. interp = ... PyEval_AcquireThread(interp); // Call more Python C/API functions here, e.g. PyRun_SimpleString PyEval_ReleaseThread(interp); o o o // Get sub-interpreter for current thread. interp = ... PyEval_AcquireThread(interp); // Call more Python C/API functions here PyEval_ReleaseThread(interp); o o o // Here we are in the destructor for a session. // Get sub-interpreter for current thread. interp = ... PyEval_AcquireThread(interp); Py_EndInterpreter(interp); PyEval_ReleaseLock(); o o o // At the very end of the application. PyEval_AcquireLock(); Py_Finalize(); Thanks again for help. And I hope that this can serve as a simple model for others trying to embed Python in a multi-threaded application. -- Dave Guido van Rossum wrote: > Yes, but this is still dangerous. You should really use the APIs that > manage the lock *and* the thread state: use > PyEval_AcquireThread() and PyEval_ReleaseThread(). (The argument to > the latter should be the current thread state, gotten from > PyThreadState_Get().) > In case you're inclined to continue this while I'm unavailable, read > the source -- e.g. the routines I mentioned here are in > Python/ceval.c. > --Guido van Rossum (home page: http://www.python.org/~guido/) From tim.parkin at pollenationinternet.com Sun Sep 7 17:31:56 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 22:31:56 +0100 Subject: Comments on Python Redesign In-Reply-To: Message-ID: <003401c37587$7cd9a920$0a00a8c0@JASPER> Dave Kuhman said >Actually, from its appearance, the new design looks like it is >trying to sell me something. "Advert filters up!" It makes me >suspicious, skeptical, and cynical, as all advertising does. But theres the dichotomy >When I send or refer someone to a site like that, >I'd feel I'd have to warn them: "It looks like promotional >material, but don't be put off; there is really good content there >if you look for it. They would't have to look for it. There is the same content on the page I designed as on the current page. A slimmed down navigation yes but that was one of the remits, it is better to have a smaller number of links that the user can quickly find what they want than a large number where they get lost. Tim Ps please can we move this off the comp.lang.python list. From msajec at ieee.org Mon Sep 22 20:12:27 2003 From: msajec at ieee.org (Mike S.) Date: 22 Sep 2003 17:12:27 -0700 Subject: Compiling informxidb-1.3 on python2.2? Message-ID: Hello, Has anyone had success compiling the informixdb-1.3 module under python 2.2? It seems the absense of makefile.pre.in in python 2.2 causes the break under py2.2. Is there an easy way around this. I've heard rumors of a manual method, but have been unable to track down details. Any help is very much appreciated. Thanks in advance, Mike From mpeuser at web.de Fri Sep 5 16:13:06 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 22:13:06 +0200 Subject: OT: best book in years References: Message-ID: "Juha Autero" > > G?del, Escher, Bach: an Eternal Golden Braid. It may not be the best > book I read and not very useful, but I'd recomend reading it anyway. > I made the same recommendation some minutes ago, but without your reservation. In fact I might even come to the conclusion it *is* the best book I have read ;-) Why do you think it is not very useful? What do you think of Shakespeare by the way? Kindly Michael P From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Sep 29 14:08:23 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Mon, 29 Sep 2003 19:08:23 +0100 Subject: Try/except vs. if/else References: <3F70598E.8020500@bu.edu> <8ef9bea6.0309270025.3c4d79ed@posting.google.com> Message-ID: On Mon, 29 Sep 2003 10:33:27 +0100, Tim Rowe wrote: >Internal constructs don't bother me -- ultimately it all comes down to >machine code which will be a mass of goto's. That doesn't mean that >my code should be (could be!) a mass of goto's. > >And the last time I needed a goto for anything I was programming in >BASIC; I don't need to use exceptions to emulate it in a language with >decent flow control constructs (Python qualifies, of course!). Ah - a good old goto debate ;-) I have long claimed that goto is useful in rare circumstances, that it can be clearer and more maintainable than structured code in those rare cases, and that while anything can be abused it is still perfectly possible for a good programmer to use it responsibly and to refactor when the code becomes too messy. Structured, OO, and indeed any style of programming can become unreadable and unmaintainable (hence the fuss about refactoring). That said, it was quite a shock when I actually found a case where I needed a goto about six months ago. Quite literally I made several attempts at writing a function in a structured way and got it wrong each time. Each time I came back to it the previous version seemed a horrible mess so I rewrote it. Eventually I figured this was stupid, especially as it didn't seem so hard in my head. I put that mental picture onto paper - and as I did so I realised it simply wasn't a structured job. It was very much a state transition model. But because it completes all its work in one go, and doesn't need to maintain the state between calls, it simply hadn't occurred to me to think of it that way. I remember telling a college lecturer that if state transition models are appropriate for some things then so must gotos be appropriate, and that in a 'short running' state machine a goto would be the logical way to implement the transitions. At the time, I didn't think it would be so long before I found an example ;-) Anyway, this example was in some fairly low level library code I was writing in C++. I don't see any need for goto in Python, trust that it will never be added, and don't like to see exceptions abused that way. Just sharing a rather pointless anecdote. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From alan.gauld at btinternet.com Wed Sep 3 18:14:23 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Sep 2003 22:14:23 GMT Subject: Writing solid code book References: Message-ID: <3f566751.342339448@news.blueyonder.co.uk> On 3 Sep 2003 04:39:02 -0700, post400 at prontomail.com (post400) wrote: > there is another famous book 'Writing solid code' but does it apply to > Python ? Or it's usable only by Microsoft C programmers ? The author > seems to be an ex-Microsoft guy ! Forget this one, it wasn't as good as Code Complete when it came out and it has aged less well. Its not even of great value to C programmers nowadays, it spends a lot of time dealing with the inadequacies of the compilers and other tools around at the time! Better tools mean much of it has lost its urgency. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From bokr at oz.net Sat Sep 6 12:28:58 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Sep 2003 16:28:58 GMT Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <3f59014d$0$152$a1866201@newsreader.visi.com> <3f591d28$0$175$a1866201@newsreader.visi.com> Message-ID: On Fri, 5 Sep 2003 20:15:00 -0400, "John Roth" wrote: > >"Grant Edwards" wrote in message >news:3f591d28$0$175$a1866201 at newsreader.visi.com... >> In article , John Roth wrote: >> >> >> So that there's no difference between a function and a method. >> >> >> >> Simplicity and orthogonality are good things -- despite what >> >> C++ proponents thing. >> >> >> >> > Hence my comment that requiring it is more complex than not >> >> > requiring it. >> >> >> >> No, it's more complex the Java/Ruby way, since you have to have >> >> two sets of rules for what a name means depending on whether >> >> you're inside a "normal" function or a method. In Python >> >> there's just one set of rules -- mostly. >> > >> > As I said earlier, it's quite possible to define it so that there >> > is always an instance of some kind; whether that's an instance >> > a class or the module itself. >> >> I don't follow. You're talking about defining a keyword that >> always refers to the first parameter passed to a function? And >> the declared parameters would refer to the 2nd through Nth >> parameters? What if the keyword isn't used in the function >> definition, then do the delcared parameters refer to the 1st >> through Nth? > >When Python invokes a function, it binds the operands in the >function call to the identifiers named in the function / method >header. If this is a method, it binds the instance (which is not >in the invocation parameter list, btw.) to the first >parameter in the method header. > >If you make "self" a reserved word, then all it has to do >is bind the instance to "self," rather than the first identifier >in the parameter list. > >In current python, there are two classes of functions (module >level and embedded) and three classes of methods (instance, >class and static.) Instance methods get the current instance, >class methods get the class object as the instance, and the other >three categories get nothing. > >As a separate suggestion, I'd have Python bind the module >object to "self" for module functions and static methods. I >haven't figured out what I want done with embedded methods >and unbound methods yet. Notice that this eliminates the >need for the global statement for module functions - all >identifiers are accessible for rebinding through "self." > >> > I think my comments have shown that you can reduce the amount >> > of scoping / name space rules noticably. >> >> Compared to what? It sure sounds like you're introducing more >> rules than there are now. How would you propose reducing the >> number of rules? > >If you don't have to write "self" as the first parameter of a method, >that reduces the complexity. Everything else remains the same. Will this still be possible? >>> def foo(*args): print args ... >>> class A(object): pass ... >>> class B(A): pass ... >>> a = A() >>> b = B() >>> A.bar = foo >>> b.bar('howdy') (<__main__.B object at 0x00906E70>, 'howdy') >>> a.bar('howdy') (<__main__.A object at 0x00907170>, 'howdy') >>> foo('howdy') ('howdy',) >>> A.bar('hello') Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method foo() must be called with A instance as first argument (got str instan ce instead) >>> A.__dict__['bar']('hello') ('hello',) I.e., the method-vs-function distinction is a matter of how you access the function dynamically, not how you define it. There is no static distinction in functionality, AFAIK (though I guess there could possibly be some speculative optimizations). (The above doesn't even get into the multiple name issues I alluded to). Regards, Bengt Richter From adalke at mindspring.com Wed Sep 24 00:49:04 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 24 Sep 2003 04:49:04 GMT Subject: CGI Redirect to another page References: Message-ID: <4n9cb.1447$RW4.791@newsread4.news.pas.earthlink.net> Andrew Chalk: > Assume that I have a static HTML page that I want > displayed (e.g. index.htm). Other than 'print ...' is there any way to > redirect to this URL (for example, like Response.Redirect() in ASP)? The Response.Redirect likely works by putting something in the header. The HTML page you have doesn't have access to the header. However, you can use the meta tag to tell the browser to look elsewhere. But that won't work for tools which don't parse the HTML. It's an easy web search (once you know the right keywords :) - "header redirect meta" and I found http://vancouver-webpages.com/META/FAQ.html#redirect "How can I redirect the user to another page ?" with three different answers Andrew dalke at dalkescientific.com From lorenb2 at bezeqint.net Tue Sep 9 03:09:26 2003 From: lorenb2 at bezeqint.net (Bill Loren) Date: Tue, 9 Sep 2003 09:09:26 +0200 Subject: script won't run Message-ID: <040a01c376a1$4dd17250$6400a8c0@EVOD31> Hi all, I'm encountering problems when trying to execute my python script outside PythonWin's IDE. Running it from PythonWins goes smooth, while clicking the .py icon or hitting the script's name directly from the command line abruptly ends with error messages. specifically the error is socket.error: (10061, 'Connection refused'). running Ethereal in the background shows no activity. any suggestions for the cause of the difference between the two methods of executing ? thx, ~B From gh at ghaering.de Tue Sep 9 08:48:35 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 09 Sep 2003 14:48:35 +0200 Subject: set built-in func_code? In-Reply-To: References: <3F5D9A9E.1000305@ghaering.de> Message-ID: <3F5DCC23.4050004@ghaering.de> Birgit Rahm wrote: > Hallo, > I have a program (not written by me :-( ) that loads socalled helpfunctions > and executes that dynamically. > One error message was : ... cant get the func_code of the helpfunctionX. That sounds strange. But the reason is most probably that helpfunctionX is in fact not a function. > Which reason this message has, I dont now. > My main problem is, that I dont know what func_code is : a built-in function > or attribute or what ? And why is it used. I don't know why it's used either, because I don't know the program you use :) I think you're relatively new to Python (only saw you posting here recently) :-) So what we're touching here is advanced stuff, but I'll try to explain it as good as I can: *Everything* in Python is an object, including functions. Here's an excerpt from an interactive session: >>> def times2(x): return 2*x ... >>> times2 >>> type(times2) >>> So, times2 is a function object. Being an object, it also has attributes: >>> dir(times2) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] Now it's relatively clear what func_name might be: >>> times2.func_name 'times2' But there's also more advanced stuff like the func_code attribute. func_code is a code object (yes, *again* an object), that contains the Python bytecode for the function in question. If you really wanted to, you could replace the code object of the function with a new code object, that does something totally different. This is probably one of the deepest hacks you can do in Python :-D So if, for example, I wanted times2 to return "x*3" instead of "x*2", I could use something like: def changeMeaningOfTimes2(): def __tmpfunc(x): return x*3 times2.func_code = __tmpfunc.func_code As I already said, this is a very ugly hack, that is seldom, if ever justified. If you're just trying to make a call to times2() invoke something different, you could just do: def __tmpfunc(x): return 3*x times2 = __tmpfunc() because all this does is bind the name 'times2' to a different function object. I hope this gives you an insight in the possibilites of what you *can* do with Python. And that not everything you *can* do is necessarily a good idea ;-) That being said, what you described sounds to me like the real problem is that a name helpfunctionX is assigned to something other than a function and that your program tries to get the func_code attribute from this object, which fails, because it's not a function but something else. ciao, -- Gerhard From mpeuser at web.de Fri Sep 5 03:37:13 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 09:37:13 +0200 Subject: just a beep References: Message-ID: "Leo" schrieb im Newsbeitrag news:bj3ug3$23m5$1 at otis.netspace.net.au... > thanks a lot! that's what i want: an platform independend beep! > > and indeed i want to read more about functions vs methods! but my quick > browse through the docu did not show me that there is sth in beetween > Tkinter and bell... Of course it did not! Have you ever used mainloop() or after(..) ? Kindly Michael P From dakidd at sonic.net Mon Sep 15 13:58:42 2003 From: dakidd at sonic.net (Don Bruder) Date: Mon, 15 Sep 2003 17:58:42 GMT Subject: Advice from Jeff (Was Re: Is there "let binding" in Python?) References: <20030914214340.13608.qmail@web40904.mail.yahoo.com> Message-ID: In article , "Terry Reedy" wrote: > "Don Bruder" wrote in message > news:o0d9b.21665$dk4.674856 at typhoon.sonic.net... > > In article , > > Jeff Epler wrote: > > > Not an answer, but advice: when writing programs in Python, > >> write Python programs. > > > > Gawd, but that's profound! And on several levels... No... I'm > serious. > > But I'm also smiling. > > Jeff's advice is perhaps too terse for someone not already familiar > with it. Does the following seem more helpful? > > If you are writing a Python program to either learn Python or > accomplish a computing task, you will probably be happier and more > successful (in the middle to long run) if you write idiomatic Python > rather than 'literal translations' in the style of some other langauge > and *its* idioms. > > The OP is not the first to more or less ask 'how do I literally > translate this foreign idiom' (which the poster may not even see as a > language-specific idiom) rather than 'how do I accomplish the same > function'. This questions usually garner the advice given above. Like I said, that's *VERY* profound advice. It wasn't a question of me "not understanding", it was an observation of fact. Even if it does make me grin when I read it. > > > If it's your task to translate some Scheme (or any other > > > language) into Python as literally as possible, my heart goes out > to you. > > > How miserable do you expect me to be translating from > > Python to C/C++ as literally as possible? > > In respect to the basic data/object model, Python is more similar to > Lisp than C++. In respect to syntax, the opposite is true. I have (mercifully) forgotten almost all of the tiny bit of lisp I ever knew. Never before or since have I seen such a butt-ugly, unfreindly, difficult to deal with language. On second thought, I take that back... Brainf*ck may be the only contender. > By default, Python code is generic -- it runs with any object with the > needed interface. So, unless a block is explicitly specialized to one > type with a preceeding assert or conditional, the literally 'as > literal as possible' translation to C++ is to template code. Are you > doing this, or specializing the C++ code by declaring variables and > function parameters to a particular type? Definitely declaring variables. I'm nowhere near far enough along to mess with templates yet. They just confuse me. -- Don Bruder - dakidd at sonic.net <--- Preferred Email - SpamAssassinated. Hate SPAM? See for some seriously great info. I will choose a path that's clear: I will choose Free Will! - N. Peart Fly trap info pages: From mpeuser at web.de Fri Sep 5 15:50:16 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 21:50:16 +0200 Subject: Tkinter Text widget getting too slow References: Message-ID: "Christos TZOTZIOY Georgiou" schrieb im Newsbeitrag news:eoselvguf3hvie3s95kjndhtuno0jiu09s at 4ax.com... > On Thu, 4 Sep 2003 03:15:16 +0900, rumours say that "Changjune Kim" > might have written: > > >(I'm interested to see his "extremely fast" text widget, too) > > Notice that Michael Peuser described an "extremely fast" "binary > editor"; I assume a dual view (hex / chars) one. This is not a text > widget --you don't have to account for line feeds and variable width > characters :) Well I have somthing a little bit over 100 lines; I removed the editor part but that is straight forward. No scaling to size up to 1 GB. ----------------------------------- # wckhwex by Michael Peuser May-2003 # Using some ideas from F. Lundh (WCK) # This is Open Source. I will be happy if it could help somebody. versionString="wckhex 0.3 by mpeuser.de" from __future__ import division from Tkinter import * from WCK import Widget, EventMixin from tkFileDialog import askopenfile import mmap class HexView(EventMixin, Widget): """Displays HUGE binary file using memory mapped files """ aCols=10 # address field bCols=2.5*16+1 # binary field cCols=16+1 # ascii field ui_takefocus=1 ui_doublebuffer=0 def __init__(self,root, buffer=None): self.buffer=buffer self.defLines=(len(buffer)+15)//16 self.firstLine=0 # numer of first line in window self.oldFirst=-1 # .. compared to last time self.visLines=1 # visible lines in window self.pix=None # pixmap will be created on resize self.ui_init(root) self.vscroll=Scrolls(self,orient=VERTICAL) self.vscroll.pack(side=RIGHT,fill=Y) self.pack(side=TOP,fill=BOTH,expand=1) self.font=self.ui_font(0,"Courier 10") (self.cWidth, self.lHeight) = self.font.measure("X") def ui_handle_resize(self, width, height): self.height=height self.width= max(width, (self.aCols+1+self.bCols+1+self.cCols)*self.cWidth) # pixel self.visLines=self.height//self.lHeight self.pix=self.ui_pixmap(self.width, self.height) self.vscroll.doScroll() # compute new thumb self.drawPix() def ui_handle_clear(*whatever): pass # no need for clear as is pixmap long enough def ui_handle_repair(self, draw, x0, y0, x1, y1): #if self.pix: draw.paste(self.pix) def onclick(self, ev): self.focus_set() if ev.num==1: pass #XXX implement editor here if ev.num==3: pop=Menu(self,tearoff=0); pop.add_command(label=versionString,state=DISABLED) pop.post(ev.x+self.winfo_rootx(),ev.y+self.winfo_rooty()) def onkey(self, event): todo ={'Down': ("scroll",1,"lines"), 'Up': ('scroll',-1,'lines'), 'Next': ("scroll",1,"pages"), 'Prior':('scroll',-1,'pages')} x=todo.get(event.keysym) print x if x: self.vscroll.doScroll(*x) def bgText(self,x,y,w,h,text,theBrush): "Displays centered text with background color" self.pix.rectangle((x+1,y+1,x+w-2,y+h-2),theBrush) (tw,th)=self.pix.textsize(text,self.font) self.pix.text((x+(w-tw)/2,y+(h-th)/2),text,self.font) def drawPix(self,unchangedSize=0): "Central dawing routine" c=self.pix repair=None whiteBrush=self.ui_brush(0xffffff) yellowBrush=self.ui_brush(0xffff99) grayPen=self.ui_pen(0x999999,2) ww,wh = self.ui_size() h=self.lHeight posX = 0 # speed up scrolling by image blitting, but unclean parametrisation of paste if unchangedSize: ## check if blitting useful linesTBS = self.oldFirst-self.firstLine ## TBS = to be scrolled if 0 < linesTBS < self.visLines/2: ## down, repair top c.paste(c,(0, h*linesTBS)) theRange=range(1,linesTBS+1) c.rectangle((0,h,ww,(linesTBS+1)*h),whiteBrush) c.rectangle((0,h,self.aCols*self.cWidth,(linesTBS+1)*h), yellowBrush) elif 0 < -linesTBS < self.visLines/2: ## up, repair bottom c.paste(c,(0, h*linesTBS)) delta=self.visLines+linesTBS theRange=range(delta-1,self.visLines) c.rectangle((0, delta*h, ww, wh),whiteBrush) c.rectangle((0,delta*h, self.aCols*self.cWidth, wh), yellowBrush) else: unchangedSize=0 # blitting would not make much improvement... self.oldFirst=self.firstLine # remember first line for next time # end of blitting optimization if not unchangedSize: # all new c.rectangle((0,0,ww,wh),whiteBrush) theRange=range(1, self.visLines) c.rectangle((0,h,self.aCols*self.cWidth,wh), yellowBrush) for w, text in \ ((self.aCols,"address"),(self.bCols,"hex"),(self.cCols,"ascii")): w *= self.cWidth if repair!='T': self.bgText(posX, 0, w, h, text, yellowBrush) c.line((posX - 1, 0, posX - 1, wh -1), grayPen) posX+=w # addresses and data posY = self.lHeight for y in theRange: posX = 0 heightY = self.lHeight address=(y-1+self.firstLine)*16 vals = self.buffer[address:address+16] c.text((posX,y*self.lHeight), "%3x.%05x " % divmod(address, 1024*1024), self.font) posX += self.aCols*self.cWidth for vala in range(address,address+16): if vala %8==0: posX+=self.cWidth//2 # some in between space if valam.defLines: # the end m.firstLine=m.defLines-m.visLines+1 if m.firstLine<0: m.firstLine=0 size = m.visLines/m.defLines # 0...1 start= m.firstLine/m.defLines # 0...1 if self.visible: self.set(start,start+size) if oldfirst != m.firstLine: m.drawPix(unchangedSize=1) if __name__ == "__main__": root=Tk() root.iconify() fbb=askopenfile("r+"); assert fbb, "No file" buffer=mmap.mmap(fbb.fileno(),0) s=HexView(root, buffer=buffer) root.title("%s (%6.3f MB)" %(fbb.name, len(buffer)/1024/1024)) root.geometry("720x550+10+10") root.deiconify() root.mainloop() fbb.close() # the End From mertz at gnosis.cx Fri Sep 12 14:08:26 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Fri, 12 Sep 2003 14:08:26 -0400 Subject: safari References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <51809ae4.0309040634.7999e400@posting.google.com> <51809ae4.0309110734.1e5d28be@posting.google.com> <87y8wvfd6d.fsf@pobox.com> Message-ID: bokr at oz.net (Bengt Richter) wrote previously: |[OT] So instead of a distributed implementation of business, with no |individual way of making billion dollar mistakes, the consolidation |centralizes control and makes billion dollar mistakes both possible |and survivable, and therefore more probable. I don't have an airtight explanation for why it "has to be so", but empirically[*], media consolidation almost always leads to a narrowing of ideological diversity. Fewer and fewer different opinions get expressed, and everything gets mushed together into an "offend no one" middle. The trend is perhaps more obvious with political news, movies, music, etc., but I fear for the same thing in computer books. Rather than publish occassional books on oddball technologies by authors with their own take on programming matters, the danger is that every book becomes "VB.NET for Dummies", or something like that. It may seem like a silly fear. But back when I was shopping my book (a couple years back now), one of the publishers I approached was New Riders. They had published Beazley's excellent _Python Essential Reference_, as well as quite a number of good programmer-oriented titles. But the stated "new" focus of New Riders was "graphics design applications" (I think one of the first steps in mergers was PeachPit+New Riders). While there is certainly nothing wrong with that type of book, it really seems to throw away the hard-earned reputation of New Riders for a certain kind of high-quality programming text--in favor of something which seems a lot more "middle of the road." AW still seems to do a lot of good books (not just mine), and maintains that nice computer-science-ish focus. But I wonder whether a cookie-cutter pressure will force their titles into narrower molds, over time. [*] Maybe Alex will pipe in with a "rational actor" explation of why what I claim either must be, or cannot be, true. :-) |[really OT] |Factoids: Iraq 2002 per capita GDP: ~$2,400. Iraq population: ~24.7 million. |$87bn if distributed to all Iraquis: ~$3,500. per capita. Brilliant observations, Bengt! Yours, Lulu... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From BoteDesSchattens at web.de Thu Sep 11 01:23:37 2003 From: BoteDesSchattens at web.de (Tobias Pfeiffer) Date: 11 Sep 2003 05:23:37 GMT Subject: FIFO problems Message-ID: Hi! I want to write a "client-server-application" (only running on the same machine) or actually I've already begun with and have problems with the interprocess communication. The server, when started, opens a FIFO and opens it with open(infifo, 'r'). Then I check the content of the file with while 1: line = serverIn.readline()[:-1] if line == "bla": do this else: print line So at the beginning everything works fine. I can start the client prog and they will talk and understand to each other. The same if I connect with three or more clients simultaneously (?). If one of these clients exists, no problem. But when the last process exists and closes the FIFO-file which was opened by os.open(infifo, os.O_WRONLY), the server begins to print an empty string everytime it goes through the loop, means it won't wait for a complete line to appear before continuing. Why? Then I modified the thing above to: while 1: line = serverIn.readline()[:-1] if line == "bla": do this elif line == "": open(infifo, 'r') print "help!!!" else: print line So in contrast to what I thought, there was not a bunch of "help!!!" lines printed, but nothing. When I tried then to connect again, there was a single "help!!!" and then the correct message for the client having connected. So, anyone any idea how I can fix this. I just want the server to continue line-by-line-reading... Bye Tobias From g2h5dqi002 at sneakemail.com Tue Sep 23 00:52:41 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 23 Sep 2003 16:52:41 +1200 Subject: Pass-by-reference : Could a C#-like approach work in Python? In-Reply-To: References: Message-ID: Michael Chermside wrote: > But my counter argument would be that this breaks one of the elegent > simplicities of Python -- that callables of all kinds are equivalent > and have a very simple interface. ... There's no place in this simple > protocol for type declarations (of course), and there would be no > place for tracking whether an argument was "ref" or not. Apologies for reviving this thread, but I'd just like to point out how this proposal ("ref" parameters, for anyone who's forgotten) could be implemented without adding any complication to the argument passing model. In fact, it could be decoupled from argument passing almost completely. Suppose there were an expression ref x which would return what I will call a Namespace Reference Object (NRO) which refers to the binding of the name 'x' in the current scope. It would have some suitable protocol, such as get() and set() methods, for accessing this binding. Note that this would be a general expression, usable anywhere, not just in a function call. Thats' really all that is strictly needed, because we can now write def Inc(xref): xref.set(xref.get() + 1) and call it with Inc(ref a) However, as a convenience, we might want to allow the 'ref' keyword to be usable on the left hand side of an expression as well, in a kind of "unpacking" sense, so that ref x = xref x = y would be equivalent to xref.set(y) (The semantics of this are perhaps a bit murky, but would be something line "assign xref to x, and have the compiler note that any other mention of x in this scope is to use the NRO protocol implicitly".) Now we can write def Inc(xref): ref x = xref x += 1 Further, analogous to the way tuples can be implicitly unpacked in an argument list, we should similarly allow arguments to be implicitly "unrefed" in an argument list: def Inc(ref x): x += 1 This is identical to the original proposal, but is implemented using mechanisms which are completely orthogonal to argument passing, and could be used in other contexts if desired. Not that I'm necessarily advocating the proposal -- I tend to agree that there's no pressing need for passing arguments by reference in Python. I'm just setting down these ideas for posterity. Okay, you can let this thread die properly now. :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jepler at unpythonic.net Fri Sep 12 08:21:17 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 12 Sep 2003 07:21:17 -0500 Subject: Tkinter Canvas/Grid question In-Reply-To: References: Message-ID: <20030912122112.GA3268@unpythonic.net> > "Gary Richardson" > > Michael, Jeff, > > > > Thanks for your replies. I made the changes indicated above and the > resizing > > works just fine now. I'm still puzzled as to why pack() would be used with > > the frame and grid() used with the canvas, and other widgets. You can manage any widget with any geometry manager. (You can even grid a button inside of a label, but god knows why you'd want to) Sometimes you must use "grid" to get proper layout. For instance, if you want to create a scrolled item (canvas or text) with horizontal and vertical scrollbars, this is the only sane way to do it. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 02:10:50 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 07:10:50 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <63gvmvcf6iakbs8pgll7u8ogblkbqld6fp@4ax.com> <6EQbb.1770$PT3.279727@news20.bellglobal.com> Message-ID: <8vovmvgmb5c677ii8a43l8l0o1sjbosre2@4ax.com> On Tue, 23 Sep 2003 01:14:57 -0400, "Sean Ross" wrote: >"Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in >message >> Personally, I think the conventional '..' has more chance than your >> '...'. > >Hi. >Actually, I think '...' is more conventional notation for expressing a range >of numbers. Like when you want to show a sequence: > ># odd numbers greater than 3, but less than 257 >5, 7, 9, 11, ..., 255, 257 > >That sort of thing. Good point, but I think the commas are essential to making that clear. Without the commas, it simply doesn't look like the same thing. >I've seen it in Ruby and Smalltalk (where integers have such methods), and >it's not '...' , nor is it range(), so that might be an alternative. Whether >it is a good alternative ... . It doesn't add new syntax, only new >methods to existing objects. That is also an advantage to my slicing idea - it only requires a new method (__getitem__ IIRC) be implemented for one object (the builtin type object called 'int'). -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From zanesdad at bellsouth.net Thu Sep 11 09:10:29 2003 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 11 Sep 2003 09:10:29 -0400 Subject: Debug python programs In-Reply-To: ; from yorklee70@yahoo.com on Thu, Sep 11, 2003 at 12:41:48PM +0100 References: Message-ID: <20030911091029.A32566@cerberus.liberty> * York (yorklee70 at yahoo.com) wrote: > Hi, anybody, > > Would you please recommend some good softwares/methods for > tracking/debugging python codes. > > Thanks, > York You've got lots of options. 1) Your standard insertion of "print" statements throughout the code. A lot of times, this is good enough to get the job done. I typically set an instance variable named DEBUG for each class that I create (in __init__, set self.DEBUG = 0 or 1). Then I have lots of if self.DEBUG: print "whatever" #insert debug statements here It's not the most elegant thing, but man, has it come in handy when you don't need a full-blown debugger. (Segue into number 2) 2) Python comes with a pretty good debugger built in. Here are the docs: http://www.python.org/doc/current/lib/module-pdb.html 3) pychecker. I know, I know, I know - it's not a debugger. But if you point it at your code, it'll inspect it and can help you uncover some mistakes that can bite you in the rear. 4) trace.py. Never used it, but it's in the standard distribution now under Tools/scripts. (I'm including this line item since you mentioned "tracking". I guess this is what you mean?) HTH Jeremy Jones From newsgroups at jhrothjr.com Tue Sep 23 21:55:25 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 23 Sep 2003 21:55:25 -0400 Subject: why the inconsistency? References: Message-ID: "mensanator" wrote in message news:fbf22ff1.0309231704.3f324abf at posting.google.com... > I just installed Python 2.3 (upgrading from 2.1). > > Version 2.3 is noticably faster and the automatic > conversion to long integers is very handy: > > >>> print 2**64 > 18446744073709551616 > > > But if I want to know how many digits 2**64 has, I can't > just do > > >>> print len(2**64) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: len() of unsized object > > So instead, I did this > > >>> print len(`2**64`) > 21 > > But the correct answer is 20, not 21. The reason the > answer is wrong > > >>> print `2**64` > 18446744073709551616L > > Why is the "L" there? I thought "L" isn't used anymore? I believe it's scheduled to vanish in 2.4, but I could be wrong about that. John Roth From maxm at mxm.dk Mon Sep 1 02:47:40 2003 From: maxm at mxm.dk (Max M) Date: Mon, 01 Sep 2003 08:47:40 +0200 Subject: Declaration of an array of unspecified size In-Reply-To: References: Message-ID: <3f52ebb2$0$97173$edfadb0f@dread12.news.tele.dk> Bertel Lund Hansen wrote: > Ulrich Petri skrev: >>>class PopMailServer: >>> host = "" >>> user = "" >>> password = "*" >>> mails = 0 >>> mail[] # This is wrong but what do I do? >> >>mail = [] #would work > >>But you are creating class-variables here. Are you sure thats what you want? > > Yes. I have the habit from Java and C++. Is there a better way to > declare them in Python? Class variables holds the same value for all instances of your object. If you want different instances to be able to have different values you should declare them as instance variables in the __init__ method. class PopMailServer: def __init__(self): self.host = "" self.user = "" self.password = "*" self.mails = 0 self.mail = [] regards Max M From tim.one at comcast.net Thu Sep 18 10:10:16 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 18 Sep 2003 10:10:16 -0400 Subject: "tuple index out of range" side effect of C extension?? In-Reply-To: <20030918221732.H25840@bullseye.apana.org.au> Message-ID: [Andrew MacIntyre] > I'm seeing a bizarre situation where IndexErrors are being thrown with > "tuple index out of range" error strings. > > The scenario is something like: > > l = [(v1a, v1b), (v2a, v2b), ..., (vna, vnb)] > > for a, b in l: > ... > > > > with the IndexError being thrown on the "for..." line after the last > element of l has been through the for loop. > > I've also seen the same exception thrown on first access to an > attribute of a simple class. > > The exception being thrown is not consistent, It's probably the case then that C code is setting an exception in a function F but neglecting to make F return its "there's an error" return value. The most common way this happens is for an extension module to call a Python C API function and neglect to check *it* for an error return value. In general, every Python C API function call must be checked for an error return, and, when one occurs, the calling function must either return an error code itself, or explicitly clear the error. If an error return isn't made, ceval.c (the interpreter's main loop) doesn't know an exception is pending, and not all bytecodes check for a pending exception. The exception doesn't get triggered then until the interpreter happens to execute a bytecode that does check for a pending exception. The original C code that set the exception is long gone at that point, and the reported exception doesn't appear to make sense. > and reducing the number of tuples and lists in the code seems to > reduce the likelihood of the exception being thrown. You wish . > The only thing unusual is the presence of a C extension Bingo. > which I am testing > - an Ingres DB interface module, most of whose functionality seems to > work when the IndexErrors don't get thrown. It's probably doing something like PyList_GetItem with an out-of-bounds index itself, then neglecting to check whether PyList_GetItem complained. > Perusal of the source, while not exhaustive, hasn't turned up anything > obvious; other than the embedded SQL stuff it seems to be in tune > with the module layout in the Python docs. > > The complications are:- > - I don't have MSVC, so can't build a standard Windows Python debug > setup to really look at the internals; If you can do any sort of debug build of the interpreter, ceval in a debug build inserts extra checks to try to catch "some routine set an exception but didn't return an error value" mistakes sooner when they happen. Look for #ifdef CHECKEXC in ceval.c to find the extra checks made then. You could #define CHECKEXC alone to get that much. > - I built the module with MinGW32 1.1 (gcc 2.95.3, it compiles with > only 1 warning which surprised me a bit) and Python can't yet be > built by MinGW (so that I could use gdb) AFAIK. Beats me what happens then. It *sounds* like a common mistake in extension modules, though, so pursue that first. > ... > Replies cc'ed to the reply-to address in addition to the list > appreciated. Done. Good luck! From domma at procoders.net Sun Sep 21 05:07:00 2003 From: domma at procoders.net (Achim Domma) Date: Sun, 21 Sep 2003 11:07:00 +0200 Subject: How to catch socket timeout? Message-ID: Hi, I'm using Python 2.3s timeout sockets and have code like this to read a page from web: request = ... self.page = urllib2.urlopen(request) and later: try: self.data = self.page.read() except socket.error,e: ... except socket.timeout: ... except timeout: ... but none of these excepts catches the the timeout while reading the data. I still get the following exception, which I cannot handle: ... File "F:\CrawlingFramework\Rules\Tools\__init__.py", line 91, in __init__ self.data = self.page.read() File "C:\Python23\lib\socket.py", line 283, in read data = self._sock.recv(recv_size) timeout: timed out Any hint on how to handle this exception or what's going wrong? regards, Achim From jallan at smrtytrek.com Tue Sep 23 21:17:00 2003 From: jallan at smrtytrek.com (jallan) Date: 23 Sep 2003 18:17:00 -0700 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> <299f1138.0309230818.22bc9bf6@posting.google.com> Message-ID: <299f1138.0309231717.5d35ecaa@posting.google.com> Peter Otten <__peter__ at web.de> wrote in message news:... > jallan wrote: > > > I don't see any particular reason why Python "cannot handle case > > mappings that increase string lengths". > > Now that's a long post. I think it essentially boils down to the above > statement. > > Looking into stringobject.c (judging from a first impression, > unicodeobject.c has essentially the same algorithm, but with a few > indirections): > > static PyObject * > string_upper(PyStringObject *self) > { > char *s = PyString_AS_STRING(self), *s_new; > int i, n = PyString_GET_SIZE(self); > PyObject *new; > > new = PyString_FromStringAndSize(NULL, n); > if (new == NULL) > return NULL; > s_new = PyString_AsString(new); > for (i = 0; i < n; i++) { > int c = Py_CHARMASK(*s++); > if (islower(c)) { > *s_new = toupper(c); > } else > *s_new = c; > s_new++; > } > return new; > } > > The whole routine builds on the assumption that len(s) == len(s.upper()) and > nothing short of a complete rewrite will fix that. But if you volunteer... I would love to if I had the time. Sigh! Maybe in some months. > Personally, I think it's a long way to go for a little s, sharp as it may be > :-) If it were just ? one could thrown in a quick conversion of any ? to ss at the beginning. But there are over a hundred other characters that expand when uppercased in http://www.unicode.org/Public/UNIDATA/SpecialCasing.txt, most of them Greek. Greek is a horror. See http://www.tlg.uci.edu/~opoudjis/unicode/unicode_adscript.html for the sad tale. Unfortunately language and orthography are messy and inconsistant and illogical and sometimes just silly. But handling orthography properly involves dealing with these complex rules and subrules and exceptions to rules rather than ignoring them. Unicode gives us great power, but with great power comes great responsibility and lots of niggling code. :-( Fortunately only the Latin, Greek, Coptic, Cyrillic and Armenian scripts have such a thing as casing and the Unicode people have provided data files and algorithms that supposedly handle casing for these languages acceptably. >From the Conformance requirements for Unicode at http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G29484 (C20): << An implementation that purports to support the default casing operations of case conversion, case detection, and caseless mapping shall do so in accordance with the definitions and specifications in Section 3.13, Default Case Operations. >> This involves even more messy fussing about with context specification for casing and with what values should be returned from a case querying function, e.g. "A2" is true as either uppercase and titlecase but not as lowercase. "3" is true as lowercase, uppercase and title case. Python or any applicaton or language either does or doesn't conform. I doubt that there is currently any application that can yet honestly purport to support Unicode default casing operations of case conversion, case detection and caseless mapping. Jim Allan From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Tue Sep 23 11:56:53 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Tue, 23 Sep 2003 19:56:53 +0400 Subject: Bottleneck? More efficient regular expression? In-Reply-To: <3f7069db_4@corp.newsgroups.com> References: <3f7069db_4@corp.newsgroups.com> Message-ID: Tina Li wrote: > Hello, > >[skipped] > Personally I'd rather split it in several separate re's. Something like match_tag(tag_name) that matches tag group at the start of the string. hth, anton. From twic at urchin.earth.li Wed Sep 24 13:09:51 2003 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 24 Sep 2003 18:09:51 +0100 Subject: Python embedded in C & memory releasing In-Reply-To: <63701d2f.0309231819.31fdec85@posting.google.com> References: <63701d2f.0309231819.31fdec85@posting.google.com> Message-ID: On 23 Sep 2003, lebo wrote: > I'm trying to understand how Python handles memory usage and dynamic > object loading and unloading. Problem to solve? Build a very low > memory footprint (non-GUI) Python application for Unix/Windows. Why > use Python? End user flexibility. > > So far it seems that (on Windows): > (1) memory increases when you import . Expected behaviour. > (2) memory does not release when you del . Why not? Is Python > not releasing the memory or is it the OS not releasing memory? > > So then I tried embedded Python in C: > (1) c application base 1.6MBytes (a good number) > (2) Call Python function from c application - memory up to 2.6MByte > (OK number) > (3) Python function exits but memory usage stays at 2.6MByte > > Why is memory not releasing? How can I tell if this Python behaviour > or OS behaviour? this is how most runtime systems handle memory. they have a certain amount of space allocated, and if they run out, they ask the OS for more, but they never give it back. i think this is what most implementations of malloc/free do; it's certainly what java does. what you want is some way to tell python to give back some or all of its spare memory. i'm not aware of such a thing myself. tom -- unconstrained by any considerations of humanity or decency From aleax at aleax.it Mon Sep 8 08:51:17 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Sep 2003 12:51:17 GMT Subject: exec code with timeout? References: <87n0dfcx7v.fsf@pobox.com> Message-ID: <9X_6b.44056$R32.1398393@news2.tin.it> John J. Lee wrote: > Alex Martelli writes: >> Graham Fawcett wrote: > [...] >> > Hmm... well, again I'd suggest the PyThreadState_SetAsyncExc function. >> > It shouldn't be that hard to wrap... I'd try it myself, but haven't >> > made it >> > to 2.3 yet. :( >> >> Nope -- the attacking script can easily use try/except to defeat attempts >> to kill it via PyThreadState_SetAsyncExc . The latter isn't meant for >> any "adversarial" situation, but just for potentially _buggy_ threads. > [...] > > Which is what the OP asked for, actually -- the users are trusted. I think you're right -- I had not understood the OP's specs correctly. In this case, the OP's application seems to be exactly THE typical use case for the new functionality (which has been kept in C only to avoid attracting _inappropriate_ use...). See my lightning talk at OSCON, slides at http://www.strakt.com/docs/os03_threads_interrupt.pdf , for a brief explanations of the how's & why and C source code to wrap the new call if you KNOW it's exactly what you need. Alex From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 12:49:46 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 17:49:46 +0100 Subject: Thoughts on PEP315 References: Message-ID: On Tue, 23 Sep 2003 15:19:12 +0100, Tim Rowe wrote: >On Tue, 23 Sep 2003 04:39:14 +0100, Stephen Horne ><$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: > >>On Mon, 22 Sep 2003 21:47:05 -0400, "John Roth" >> wrote: > >>>do: >>> bibbity >>> bobbity >>> boo >>> while condition # note the lack of a colon! >> >>Yuck!!! >> >>This is really no different to the following, which is quoted in the >>PEP as something to move away from... >> >> while True : >> ... >> if condition : break >> ... >> >>The fundamental problem is that the exit point is not obvious because >>it is 'hidden' in the detail of the loop - it is a statement within >>the loop body instead of being lexically a part of the loop. > >It is very different indeed. In the second case stuff can go after >the "if condition: break", so the terminating condition is potentially >buried in the surrounding code. On my reading of John's proposal >nothing can go after the "while condition", so the end is clearly >marked in the Python way by the indentation dropping back a level. Maybe - but in my reading of Johns suggestion the 'while' was just a statement like the existing 'break' or 'continue' (hence the lack of a colon). So you could legally write... >>>do: >>> blah; blah; blah; blah; blah; blah >>> blah; blah; blah; blah; blah; blah >>> blah; while condition; blah; blah >>> blah; blah; blah; blah; blah; blah >>> blah; blah; blah; blah; blah; blah Which hides the 'while' quite well He said there was no colon - he said nothing about semicolons. This was not true for the original PEP315 suggestion, nor for my own, which is... while True : blah; blah; blah; blah blah; blah; blah; blah break if condition : blah; blah; blah; blah blah; blah; blah; blah Even with a severe case of not-enough-whitespace, it is still clear where the loop exit point is. >What I /don't/ like about it is the overloading of the "while" >keyword. I would much sooner reverse the condition and use "until", >though I realise the back-compatibility issues of introducing new >keywords. I agree. That's why I suggested 'break if' - it reuses existing keywords, yet is unambiguous and explicit about what it is doing. The sense of the condition seems unimportant to me (a boolean not is simple enough) so the fact that 'break if' reads more like 'until' than 'while' seems irrelevant to me. Actually, I kind of like the fact that it will normally be an easy drop-in replacement for 'if condition : break'. In itself, I don't think my suggestion is compelling - but as an alternative to the existing PEP315, on the assumption that some change is going to happen, I think my idea has significant merit. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From malcolm.wood3 at ntlworld.com Mon Sep 29 17:45:44 2003 From: malcolm.wood3 at ntlworld.com (Mac Wood) Date: 29 Sep 2003 14:45:44 -0700 Subject: error explanation Message-ID: <13df83a2.0309291345.32db8a2b@posting.google.com> Could someone please explain this error message: Traceback (most recent call last): File "C:\Python23\time.py", line 1, in -toplevel- time.py NameError: name 'time' is not defined I tried entering the following example: time.py #This programs calculates rate and distance problems print "Input a rate and a distance" rate = input("Rate:") distance = input("Distance:") print "Time:",distance/rate which according to the tutor should have run as this: > python times.py Input a rate and a distance Rate:5 Distance:10 Time: 2 Thanks for your help From skip at pobox.com Fri Sep 26 10:24:19 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Sep 2003 09:24:19 -0500 Subject: [Python-Dev] Re: RELEASED Python 2.3.1 In-Reply-To: References: <200309240802.h8O82mqF026019@localhost.localdomain> Message-ID: <16244.19475.777510.550060@montanaro.dyndns.org> Martin> "Jason R. Mastaler" writes: >> Python 2.3.1 (#1, Sep 24 2003, 15:55:24) >> [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> from os import fsync >> Traceback (most recent call last): >> File "", line 1, in ? >> ImportError: cannot import name fsync >> >>> Martin> Why is that a bug? Your system just does not have a declared Martin> fsync function. No, it was a typo in the configure scripts. I checked in a fix for both the head and release23-maint branches yesterday. Red Hat 8.0 does have fsync: FSYNC(2) Linux Programmer's Manual FSYNC(2) NAME fsync, fdatasync - synchronize a file's complete in-core state with that on disk ... That is from an 8.0 system. Skip From donn at u.washington.edu Tue Sep 23 20:15:19 2003 From: donn at u.washington.edu (Donn Cave) Date: Tue, 23 Sep 2003 17:15:19 -0700 Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> Message-ID: In article <879b6a51.0309231547.428214f7 at posting.google.com>, joseph at ugcs.caltech.edu (John Lin) wrote: > I want to know how to tell if a forked process is done. > > Actually, my real question is that I want to run a shell script inside > of a python script, and after the shell script has finished running, I > want to do more stuff *condition* on the fact that the shell script > has finished running, inside the same python script. > > The only way I can think of is to fork a process and then call the > shell script, as in: > pid = os.fork() > if pid == 0: > os.execl(shellscript_name.sh, "") > but how can I know if the shell script is finished? > > In sum, my two questions are: > 1. How can I know if a forked shell script is finished? > 2. How can I run a shell script inside a python script without > forking a new process, so that I can know the shell script is done > from within the same python script? The simplest way to do what you appear to want is os.system("shellscript_path") If any of the command line is actually going to come from input data, or you have some other reason to prefer an argument list like exec, see os.spawnv and similar, with os.P_WAIT as first parameter. Or if your next question is going to be how to read from a pipe between the two processes, see os.popen() for starters. All of these functions will fork a process, but they use waitpid or some similar function to suspend the calling process until the fork exits. See man 2 waitpid, which is available from python as posix.waitpid() or os.waitpid(). Donn Cave, donn at u.washington.edu From fortepianissimo at yahoo.com.tw Thu Sep 18 08:26:35 2003 From: fortepianissimo at yahoo.com.tw (Fortepianissimo) Date: 18 Sep 2003 05:26:35 -0700 Subject: semantic operation in simpleparse? Message-ID: A while ago I decided to use simpleparse to write a parser for a kind of formula representation that I created. This representation is typed, so there're invalid parses to reject based on sematnics ground (type mismatch, etc.) I checked simpleparse documentation, and the only thing which seems to be close is this CallTag thing, but it doesn't seem to be able to block a parse. I'd appreciate if someone can show me some example code doing this - just a skeleton of things. Thank you! From adalke at mindspring.com Tue Sep 23 22:13:48 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 24 Sep 2003 02:13:48 GMT Subject: Pre-PEP: reverse iteration methods References: Message-ID: John Roth: > There are objects that support iteration that > don't support len(), such as file objects. Sure. Then it'll given an exception. The implementation should turn around and raise the proper exception there instead of a "len doesn't exist" one. There's also a problem that len works on a dict but __getitem__(int) will only work if the dict stores 0->n-1 as keys. > This has got the advantage, of course, that it would > automatically work on all objects that support > an sequence-like protocol, though. Yup. > Frankly, I prefer the notion of a method. While I don't. There are many, many ways to iterate through a list. (What about all evens followed by all odds?) Right now they are all done by using a function which creates an iterator across a container. If it's a method then you've said that reverse_iter is special enough that it must be a method, which seems strange for something which is so infrequently used. Andrew dalke at dalkescientific.com From newsgroups at jhrothjr.com Tue Sep 2 11:27:31 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 2 Sep 2003 11:27:31 -0400 Subject: **kwds behavior? References: <924a9f9c.0309020652.212c54eb@posting.google.com> Message-ID: The description of the locals() function is: Update and return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. Note that this implies that the dictionary is essentially read only. What you're trying to do shouldn't work. John Roth "Paradox" wrote in message news:924a9f9c.0309020652.212c54eb at posting.google.com... > Why does the following attempts to pass in keywords arguments not > work. It would be alot cooler if there was a way to not have to have > the function defined with the variable name. It really seems to me > that the 3rd function should work. Does anyone know how to accomplish > something like this. > def testKeywords1 (**kwds): > print x > > def testKeywords2 (**kwds): > locals().update(kwds) > print x > > def testKeywords3 (**kwds): > locals().update(kwds) > def testNested(): > print x > testNested() > > dict = {} > dict['x'] = 5 > # doesn't work > testKeywords1(**dict) > # doesn't work > testKeywords2(**dict) > # doesn't work > testKeywords3(**dict) From ark at acm.org Fri Sep 26 13:43:11 2003 From: ark at acm.org (Andrew Koenig) Date: Fri, 26 Sep 2003 17:43:11 GMT Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: Stephen> I doubt the need for exclusive ranges in integer for loops. I Stephen> also doubt the need for switching between different range Stephen> systems (inclusive, exclusive, half-open). IMO there is more Stephen> confusion than anything down those routes. Really? I would expect a common usage to be: for 0 <= index < len(list): do something with list[index] -- Andrew Koenig, ark at acm.org From BjornPettersen at fairisaac.com Thu Sep 11 15:32:36 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Thu, 11 Sep 2003 14:32:36 -0500 Subject: FIFO problems Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624506@stpmsg00.corp.fairisaac.com> > From: Steve Holden [mailto:sholden at holdenweb.com] > > "Duncan Booth" wrote ... > > "Steve Holden" wrote in > > news:tJZ7b.67$o71.53 at news2.central.cox.net: > > [...] > > > > > > while 1: > > > line = serverIn.readline() > > > if not line: > > > break > > > del line[:-1] > > > if line == "bla": > > > do something incredibly interesting > > > else: > > > print line > > > > Untested is right. Your 'del' statement is a little bit too > > destructive, or at least it would be if strings were mutable. > > > :-) Well, I can only remind myself that "the person who never > made a mistake never made anything". > > > Here's my (equally untested) alternative: > > > > for line in serverIn: > > line = line[:-1] > > if line == "bla": > > do something incredibly interesting > > else: > > print line > > > > Unfortunately this doesn't include the end-of-file test [...] .. the iterator doesn't? -- bjorn From grisha at modpython.org Mon Sep 22 15:59:34 2003 From: grisha at modpython.org (Gregory (Grisha) Trubetskoy) Date: Mon, 22 Sep 2003 15:59:34 -0400 Subject: Python ISPs In-Reply-To: <6ee58e07.0309190541.691b842d@posting.google.com> References: <924a9f9c.0309181224.374a5bef@posting.google.com> <6ee58e07.0309190541.691b842d@posting.google.com> Message-ID: <20030922154936.S25097@onyx.ispol.com> On Fri, 19 Sep 2003, Lothar Scholz wrote: > > > "Ulrich Petri" wrote in message news:... > > "Paradox" schrieb im Newsbeitrag > > news:924a9f9c.0309181224.374a5bef at posting.google.com... > > > Does anyone know of some ISPs that have Mod_Python installed. Most > > > seem to allow Python CGI but not things like Mod_Python or Spyce. Is > > > this a viable solution or should I just learn PHP. I would prefer to > > > leverage my Python knowledge but I also would like a fast robust > > > solution. > > > > You could go for one of those virtual servers all for yourself... > > > > Most (all !?) of this virtual servers are the worst i've ever seen. > > Putting 100 customers on a 1 GB 2x2 GHz maschine is not a good thing > if everyone must install there own MySQL,Apache etc. All web hosting companies suck this way. Only a dedicated physical server would not have this issue. But second to a colocation or a dedicated physical server, virtual servers (especially FreeBSD jail(8) based) are the best (low cost) solution for mod_python. I understand there are companies that have mod_python loaded on a shared instance of Apache and provide access to databases using db access controls, but I would never use such a service because there is no way it can be anywhere nearly as secure (and in most cases it's just plain insecure). Grisha From Mike at DeleteThis.Geary.com Thu Sep 25 23:02:05 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 25 Sep 2003 20:02:05 -0700 Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: Grant Edwards wrote: > I don't remember if the actual DOS system calls accepted '/' or if > the C library translated. I do know that DOS C programs could > use '/' for path separator at least 20 years ago. It was the DOS system calls. -Mike From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Sep 25 19:12:41 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 00:12:41 +0100 Subject: Another Python rookie trying to port to C/C++ question. References: Message-ID: <79t6nvceo80m6cumskpqdmipa921da054o@4ax.com> On Thu, 25 Sep 2003 15:19:00 -0700, Brian Quinlan wrote: >> Well, since I'm not worried about "flexible", have my doubts about the >> "much slower" part, > >Your implementation is O(n) with the number of entries while the Python >implementation is O(log(n)). If n is small then your implementation >might be acceptably fast. Can't you just use the STL hash_map template >class? Are you sure Python dictionaries are O(log n)? - Remember, they are based on hashing. Simple hashing is O(1). Handling of collisions and stuff will affect that (and I'm no expert on hashing techniques) but I can't help wondering if you're confusing Pythons hashing with tree-based techniques. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From pinard at iro.umontreal.ca Tue Sep 16 17:18:30 2003 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Tue, 16 Sep 2003 17:18:30 -0400 Subject: Unicode Newbie In-Reply-To: References: <20030909162009.0247ce9d.sylphaleya@hta.fhz.ch> <20030916124656.254a24ca.sylphaleya@hta.fhz.ch> Message-ID: <20030916211830.GA19800@alcyon.progiciels-bpi.ca> [Martin von L?wis] > Manuel Huesser writes: > > > Yep Unicode supports less characters than there are possible with > > utf-8 (ucs range = 2 ** 31). > > > > so there is no possibility to support the full range of the ucs > > character set with python? > > The ucs range (for UCS-4) is *not* 2**31; it is 17*2**16. It was 2**32 > in ISO/IEC 10646:1993 (I believe), but it got constrained in 10646:2000. I think UCS-4 is (or at least was) defined for 2**31 code points only. I do not know why the sign bit was excluded (maybe to avoid problems with negative values for code points?), but if you consider the logic of UTF-8, you will see than one full byte would be needed to support the 32th bit. This does not mean it was the reason, I do not know. UTF-16 has 17*2**16 code points. I did not recently study the legal verses, but my overall impression is that UTF-16 has been more or less integrated in UCS-2 in more recent Unicode versions, and made official. I do not know exactly what means UCS-2 nowadays, as it does not really exist anymore as defined originally (with the intent of being fixed width). Unless UCS-2 is 2**16 - 2**11 codepoints? The surrogate areas cannot sensibly be part of it, at least nowadays. Hmph! I should really read recent legal texts when I get to dive in such areas... :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From theller at python.net Thu Sep 18 04:56:32 2003 From: theller at python.net (Thomas Heller) Date: Thu, 18 Sep 2003 10:56:32 +0200 Subject: Checking if the computer is online References: Message-ID: Mickel Gr?nroos writes: > On Thu, 18 Sep 2003, Thomas Heller wrote: > >> Mickel Gr?nroos writes: >> >> > Hi all, >> > >> > I have a silly question. Is there are simple way to check if the computer >> > is connected to the Internet? It seems this should be a pretty >> > straight-forward thing to do, but as I am totally unfamiliar with sockets >> > and such, I ask for your help before getting my hands dirty. >> >> For windows? >> >> > > I want to get this done on both Windows (2000/XP) and (Redhat) Linux (7.x > or higher). > > Isn't there a way to wrap a call to urllib.urlopen in some kind of timer, > so that the call fails if there is no answer in N seconds? (I.e. if > urllib.urlopen cannot open a specific web page in N seconds, then I > assume that the reason is that the computer is not online.) That would be > good enough for me. Any suggestions? Of course you can do it this way. Or even simpler with the socket module. But it depends on what you exactly want: It's been quite a time that I had a dial-up connection, but IIRC, trying network activity when the computer was not connected would result in Windows trying to establish the connection. To conclude: the above mentioned URL contains code which exactly answers your original question. Thomas From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 24 02:06:41 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 24 Sep 2003 07:06:41 +0100 Subject: Pre-PEP: reverse iteration methods References: Message-ID: <4bc2nv07g7hcfd9nm291n3s3aarkifu1a7@4ax.com> On Wed, 24 Sep 2003 04:44:21 GMT, "Andrew Dalke" wrote: >-1 from me. 'backwards' looks to me like something which changes >the list ordering in place, like what 'reverse' does. Or something >which returns a new list but in reverse order. It's an adjective, >when it should be a verb. I disagree with this. IMO something that modifies a value in place should be named using a verb (such as reverse, or sort, or update...). Something that returns a value without modifying its parameters/object should be named to describe what it returns - normally a noun or adjective (such as globals, len, isinstance). So if we had a sorting function that returns a sorted version of the parameter without modifying its parameter, I'd want it to be called 'sorted' as opposed to the current in-place 'sort'. Of course there are non-modifying functions that are named as verbs (map, filter and reduce being particularly obvious), but that does seems slightly wrong to me - though for the ones I've listed there is basically an overriding convention (they are well known names). -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From anthony at interlink.com.au Mon Sep 1 04:44:53 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Mon, 01 Sep 2003 18:44:53 +1000 Subject: homebrew 2.3 install on RedHat9 not playing nice with Tkinter In-Reply-To: <200309010934.31138.mfranklin1@gatwick.westerngeco.slb.com> Message-ID: <200309010844.h818irXD025002@localhost.localdomain> >>> Martin Franklin wrote > On way round this little problem would be to build your own Tcl/Tk > (thats what I did) Not only will you get a working Python 2.3 but you get the > new options in Tk 8.4 too all for an extra couple of downloads and about 30 > mins of 'work'. Alternatively, use the RPMs I built from http://www.interlink.com.au/anthony/tech/rh9-tcltk/ These replace the RH9 Tcl/Tk RPMs with ones that are built from the vanilla Tcl/Tk sources; the Redhat breakage is removed. They can just be installed with rpm -U tcl*.rpm tk*.rpm >From a brief look at the beta of Redhat 10 that's available, they appear to have fixed tcl/tk to work properly again (well, at least tcl/tk applications no longer consume tens of megabytes per day). Anthony -- Anthony Baxter It's never too late to have a happy childhood. From jepler at unpythonic.net Tue Sep 23 07:54:32 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 23 Sep 2003 06:54:32 -0500 Subject: Factory function to generate a named class In-Reply-To: <3f702b3a$0$23594$5a62ac22@freenews.iinet.net.au> References: <3f702b3a$0$23594$5a62ac22@freenews.iinet.net.au> Message-ID: <20030923115427.GA30467@unpythonic.net> Populate a dict with a mapping from class names to class objects: d = {} def register(cls): d[cls.__name__] = cls def factory(clsname, model): try: factory = d[clsname] except KeyError: raise TypeError, "Class %s not registered" % clsname return factory(model) class ViewController: pass register(ViewController) If you absolutely want this to be automatic, a metaclass trick can probably be played to do it. Something like: class FactoryMeta(type): def __init__(cls, name, bases, dict): super(FactoryMeta, cls).__init__(name, bases, dict) register(cls) class Factory(object): __metaclass__ = "FactoryMeta" del d["Factory"] # Unregister this "abstract" class All code is untested. Jeff From eric.brunel at pragmadev.N0SP4M.com Fri Sep 19 06:49:47 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Fri, 19 Sep 2003 12:49:47 +0200 Subject: file position *tell()* works different References: <13a533e8.0309190137.2df0cc60@posting.google.com> Message-ID: M-a-S wrote: > I'm not sure if that't the reason, but the binary mode for reading is 'rb'. > Actually, the order of 'r' and 'b' shouldn't matter. But the '+' has a different > meaning: the file should allow "opposite" access as well, e.g. 'r+', 'rb+' > means that you can write to the file too, while 'w+' means: open it for > writing but permit reading too. You can try to say 'rt' for the read/text mode. Sorry, but no you can't: the default is to open the file in text mode, and you can change it with a 'b', but 't' has no meaning at all. BTW, 'b' also has no meaning at all on all Unices: the so-called "binary" or "text" mode are the same, i.e. what is read is what is in the file. Windows needs it only because of its superfluous \r's at the end of each line. > Anyway, you program works under Windows XP/Python 2.3 as expected: > > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > C:\Home\Programming\Python\2>py > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>^Z >>> > > C:\Home\Programming\Python\2>test.py > Filepointer: 0 > Filepointer: 12 > Filepointer: 24 > Filepointer: 35 > Filepointer: 54 > > Filepointer: 0 > Filepointer: 12 > Filepointer: 24 > Filepointer: 35 > Filepointer: 54 > > I'm sorry if it doesn't help. The bug must be somewhere else then. > > M-a-S > > > "Peter Abel" wrote in message news:13a533e8.0309190137.2df0cc60 at posting.google.com... > >>Hi all, >>I'm working under W2k with === >>Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 I do confirm the methods tell and/or seek are broken on Win2K when you open the file in text mode: doing myFile.seek(myFile.tell()) is not a no-op. The "ghost" \r's at the end of lines seem to be taken into account by one of the methods and not by the other one. The problem also happens on Win98. I don't know if it's a Python bug or a bug in the underlying C API. Knowing Windows, and considering the Python wrapper must be quite trivial, I'd bet on the C API... The only workaround I found was to always open the files in binary mode, and explicitely ignore the \r's. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From john.abel at pa.press.net Sat Sep 20 06:56:21 2003 From: john.abel at pa.press.net (John Abel) Date: Sat, 20 Sep 2003 11:56:21 +0100 Subject: Help Compiling 64bit Python Message-ID: <3F6C3255.6010606@pa.press.net> I'm having a bit of hassle, trying to compile Python in 64bit mode on Solaris8, using GCC 3.1/3.3 (tried both). I've set the relevant settings ( export CC="gcc -mcpu=v9 -m64 -D_LARGEFILE64_SOURCE=1" - hopefully) before ./configure, which seems to work OK. The problem happens halfway through the make. It produces the following output: c++ -o python \ Modules/python.o \ libpython2.3.a -lresolv -lsocket -lnsl -lrt -ldl -lpthread -lm ld: fatal: file Modules/python.o: wrong ELF class: ELFCLASS64 ld: fatal: File processing errors. No output written to python collect2: ld returned 1 exit status make: *** [python] Error 1 I'd be very grateful for any pointers. Regards John From fperez528 at yahoo.com Sun Sep 7 20:08:14 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 07 Sep 2003 18:08:14 -0600 Subject: Comments on Python Redesign References: Message-ID: Tim Parkin wrote: > Fernando: >> That's why you really need to post a readable >> html site, not a png: it's almost impossible for anyone but you to >> properly judge the site with graphical screenshots. It takes a long > time to create a professional html design that is cross browser to > the extent needed for this site and also as accessibile as possible. > I am unwilling to spend this amount of time just to get some feedback > on a design that might possibly be used. To give you an idea of how > much this HTML design would cost from a consultancy (which is what > pollenation is), calculate professional rates at approx thirty two > hours work (my guess, about ?1,600 or maybe $2,500). Could someone > please explain why it's impossible to judge the design of the site > without it being rendered as HTML. Perhaps the accessibility / speed > needs HTML, but not the design. Do people feel that the design would > be impossible to create as a optimal HTML entity? Well, with an image, nobody can tell if the layout remains sensible when users set drastically different font defaults. I, for one, use a laptop with a 14 in, 1600x1200 LCD. I have fairly large font defaults set in mozilla, and my fonts look gorgeous (many individual pixels per letter, they read almost like printed paper). Properly coded sites are no problem, the layout flows around the text and it all looks just fine. But I've also seen sites where the text splatters all over the graphical elements, because those elements assumed a fixed pixel size that text would never exceed. Sites like that are a disaster to read. By looking only at a static png, I (or others in a similar situation), have no way of knowing whether your proposed design would work ok or not with our font choices. I had assumed you had taken a screenshot from an existing test site in your browser. From your other posts, I'm starting to guess that you actually 'drew' the design in a graphics program. So I don't know if it's even possible for you to provide in short order a functional mockup. But you said you wanted this discussion in a marketing list I just don't have the time to subscribe to, so I won't continue to post here further. Good luck, Fernando. From Mike at DeleteThis.Geary.com Fri Sep 5 04:15:05 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Fri, 5 Sep 2003 01:15:05 -0700 Subject: newbie question about dictionnary ? References: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Message-ID: Sophie All?on wrote: >... > have a triangle class (made of 3 edges) > have an edge class (made of 2 points and embeding a triangle > list (those connected to the edge) > > for each triangle construct its edges but I have to check if the > edge already exists > > for doing this I thought the dictionary was excellent but the key > is a string while I want it to be the 2 points forming the edge ? > How to do it ? Sophie, dictionary keys can be just about any immutable value. They can be tuples, if the tuples contain only strings, numbers, or other tuples: >>> d = { (1,2): 'one two', (3,4): 'three four' } >>> d {(1, 2): 'one two', (3, 4): 'three four'} >>> d[(1,2)] 'one two' >>> d[(3,4)] 'three four' >>> For more information, see the Dictionaries section in the Python tutorial: http://www.python.org/doc/current/tut/ -Mike From gh at ghaering.de Fri Sep 19 05:40:29 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 19 Sep 2003 11:40:29 +0200 Subject: Access to Win API In-Reply-To: References: Message-ID: <3F6ACF0D.5000403@ghaering.de> Ladv?nszky K?roly wrote: > What is the best way to access Win API functions that are not present in the > various extension packages. Is writing a C extension the only solution? You don't have to write a C extension, you can use ctypes instead. -- Gerhard From FBatista at uniFON.com.ar Fri Sep 19 15:12:35 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 19 Sep 2003 16:12:35 -0300 Subject: How do I learn operator overriding? Message-ID: #- The only problem is that I have no idea how to override operators in #- python. Can anyone give me a few trivial examples of how it is done? Check the "language reference". There you'll find a lot of methods that get called when you do what you?re trying to do. For example, methods __add__ and __radd__ when you do qDate + 5... #- And, on a completely unrelated note, I am getting a truly #- amazing amount #- of spam today. Anyone else? Yes, me. And my employeers makes me to use Outlook (bloody exchange server), and it sucks as spam filter... . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lk at digicart.hu Fri Sep 19 06:45:37 2003 From: lk at digicart.hu (Ladvánszky Károly) Date: Fri, 19 Sep 2003 10:45:37 GMT Subject: Access to Win API References: Message-ID: <0c58d500ac94b27d7f8ff87a2a59f6e1@news.meganetnews.com> Thanks for your help. I remember once I tried a Python cookbook sample code that included ctypes but now 'import ctypes' does not work. Should ctypes come together with the 2.3 installation? K?roly "Gerhard H?ring" az al?bbiakat ?rta a k?vetkezo h?r?zenetben: mailman.1063964485.26108.python-list at python.org... Ladv?nszky K?roly wrote: > What is the best way to access Win API functions that are not present in the > various extension packages. Is writing a C extension the only solution? You don't have to write a C extension, you can use ctypes instead. -- Gerhard From peter at engcorp.com Fri Sep 26 10:59:17 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 26 Sep 2003 10:59:17 -0400 Subject: Reduce need of backslash References: Message-ID: <3F745445.D9628351@engcorp.com> Nicolas Fleury wrote: > > I was wondering if the need for \ could be reduce in the language. For > example, could a line ending with = or + could be automaticly considered > incomplete? What should Python do in the following case? a = 5 + someFunc(a) Okay, you want it to quietly add 5 and the result of someFunc() together and assign to "a". What if I told you that I actually had intended to add 5 plus "b" and assign to a, then call someFunc() and discard the return value. You've just turned a nice clean error message from the compiler into a silent and possibly deadly bug. "Explicit is better than implicit, and errors should never pass silently" as has been noted again recently in another thread. -Peter From CanardFurieux at hotmail.com Mon Sep 15 16:54:51 2003 From: CanardFurieux at hotmail.com (CanardWC) Date: Mon, 15 Sep 2003 22:54:51 +0200 Subject: Calling Python from PHP References: Message-ID: "Daniel Klein" a ?crit dans le message de > We need to use PHP with MQSeries, however PHP does not have a MQ interface > afaik. So my question is: Can Python be used as a proxy for PHP to call into > Python libraries, specifically PyMQI? Have you try this ? http://pear.php.net/package-info.php?package=mqseries From newsgroups at jhrothjr.com Sun Sep 7 08:57:19 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 7 Sep 2003 08:57:19 -0400 Subject: Redesign of Python site References: Message-ID: "Stephan Diehl" wrote in message news:bjf60f$iqc$07$1 at news.t-online.com... > > > > > The current site is, for me, one of the most readable sites aronnd. > > The text colors work and it lets Internet Explorer adjust the text > > size. > > > > The pollenation site is one of the worst I have seen. The mockup page > > has teeny type that IE will not enlarge. (Telling me to use another > > browser is besides the point. Lots of people will continue to visit > > with IE even if I do switch.) The comments page has barely readable > > dark-brown gray type on a lighter brown-gray background.. These pages > > should only be used as examples of what not to do and how not to spoil > > what we already have. > > It is absolutely beyond me, how IE should display the mockpage any > differently than other browsers. > On Mozilla, the page loads as: > > > > It loads the same on IE. The problem that Terry is complaining about results from it being a mockup: you're displaying a PNG, so it's understandable that attempts to resize the type or change the foreground or background colors won't work. John Roth > > Stephan > From erwin at andreasen.com Sun Sep 28 14:46:23 2003 From: erwin at andreasen.com (Erwin S. Andreasen) Date: 28 Sep 2003 20:46:23 +0200 Subject: Getting C++ object from PyObject * References: Message-ID: <87lls83g5c.fsf@andreasen.org> Nikolai Kirsebom writes: > I'm using BOOST to integrate Python into our application. Could > someone tell me how I get hold of the C++ object (pointer to the > object instance) from a PyObject *. > How would I code the SetInput method: > > void MyObjectB::SetInput(PyObject *o) > { > //Check that type of 'o' is an (instance) object of class 'MyObjectA' > //Fetch the pointer (reference) to the actual instance of MyObjectA > MyObjectA * ca = ..... If you want setInput to be able to take any python object, use the "object" type instead that boost::python provides. That will take care of refcounting etc. and provide easier access to calling methdos on the Python objects. Once you have an object, you can try a conversion using "extract": MyObjectA *m = extract(o); This throws on failure. There's another way to do it, which doesn't throw. See: http://www.boost.org/libs/python/doc/tutorial/doc/extracting_c___objects.html However, I'm not sure you need this manual work at all -- just making SetInput take a MyObjectA* directly should make boost::python generate the correct code in the wrapper, and raise an exception if the types do not match. -- =============================================================== Herlev, Denmark <*> =============================================================== From mpeuser at web.de Sun Sep 7 02:23:19 2003 From: mpeuser at web.de (Michael Peuser) Date: Sun, 7 Sep 2003 08:23:19 +0200 Subject: Why python??? References: <87fzjalogu.fsf@pobox.com> <87vfs6unsx.fsf@pobox.com> <87r82tpmnq.fsf@pobox.com> Message-ID: "John J. Lee" > OK. (actually, um, do ASICs have any code in them at all? can't > actually remember what they are...) > Fascinating stuff! Goggle also for VHDL and FPGA. And yes, ASICs and FPGAs are programmed and that might turn out to become one of the greater problems in the next years. (Alex, please don't comment, if possible) > > Indeed, IIRC David Beazley wrote SWIG for just that purpose > (controlling molecular dynamics simulations of some kind from Python). > I think there's a paper about it, probably on the SWIG site. > > Plenty of other examples, of course. Tcl is still quite popular for > this purpose, since that's what Ousterhout designed it for! And I > know Python has been ported to various Cray machines. With respect to "glue languages" this has to be expected. They probably will also use their job control language ;-) Notice that there is no longer any Cray among the Top 10 of supercomputing. My former argument refered to the fact that most supercomputers are build to utmost performance. It makes no sense to degrade that by some in-between virtual machine. The argument of programmers (=programming scientists) cost and productivity does not hold so strictly in academic circles. Kindly Michael P > > > John From herrn at gmx.net Tue Sep 9 15:35:30 2003 From: herrn at gmx.net (Marco Herrn) Date: Tue, 9 Sep 2003 21:35:30 +0200 Subject: How to instatiate a class of which the name is only known at runtime? Message-ID: <20030909193530.GA2218@darkstar.localdomain.fake> Hi, I am writing a program that has to instantiate a class from which I don't know the name until runtime. That leads to two problems for me. 1. How to do the import? I didn't find a way to give a string to the import statement. 2. How to write such code to instantiate? The first is a problem, when I don't know where the classes reside. Currently it is planned that all these classes reside in a specific subdirectory. Is it possible to say 'import * from subdirectory' ? What other problems could occur here and how could I avoid them? And to the second question, I have no idea about how to do this. Any hints? Bye Marco -- You can't judge a book by the way it wears its hair. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From br_y at yahoo.de Thu Sep 4 02:12:57 2003 From: br_y at yahoo.de (Birgit Rahm) Date: Thu, 4 Sep 2003 08:12:57 +0200 Subject: Arguments of function as out References: Message-ID: Thank you, I've already read this, but I hoped, there is a way to get these out parameters beside this. Because I cant redesign the function on the server side. So I have only the possibility to change the client side code, which calls this function. It seems there is no way in python to use it and get the new out paramter value after finishing the function. Birgit "Piet van Oostrum" schrieb im Newsbeitrag news:wzoey20yy4.fsf at nono.cs.uu.nl... > >>>>> "Birgit Rahm" (BR) wrote: > > BR> Hallo Newsgroup, > > BR> I have the following problem: > BR> I work with Python 2.2 and invoke functions via CORBA ( I use > BR> onmiORB/omniORBpy) on a server. > BR> The server provides me a function, where the 3 arguments are out-arguments > BR> and the return is void / None. > BR> How can I get these out arguments? > BR> I have read that every argument is seen as local to the function and > BR> can not be used as return value. > BR> (I can't redesign the server function.) > BR> Can I make the 3 arguments global before they were used in the function? > BR> Does this help me? > BR> Or what can I do? > > This is described in the Python language binding: > > Operations of an interface map to methods available on the object references. > Parameters with a parameter attribute of in or inout are passed from left to > right to the method, skipping out parameters. The return value of a method > depends on the number of out parameters and the return type. If the > operation returns a value, this value forms the first result value. All > inout or out parameters form consecutive result values. The method result > depends then on the number of result values: > > * If there is no result value, the method returns None. > * If there is exactly one result value, it is returned as a single value. > * If there is more than one result value, all of them are packed into a > tuple, and this tuple is returned. > -- > Piet van Oostrum > URL: http://www.cs.uu.nl/~piet [PGP] > Private email: P.van.Oostrum at hccnet.nl From __peter__ at web.de Thu Sep 4 03:25:03 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Sep 2003 09:25:03 +0200 Subject: strings References: Message-ID: Scribe wrote: > Hi > Somewhat new to Python and would appreciated some help in selecting the > best builtins to achieve what I want. > I pass a string to a function, it is either > empty > spaces > alpha and digits > or > a decimal ie. 5,789.88 > if it is a decimal I want to return the number without the commer any > others return 0. > Should be simple or maybe I am. > Any help apreciated. import locale locale.setlocale(locale.LC_ALL, ("en", None)) def strtofloat(s): try: return locale.atof(s) #return float(s.replace(",", "")) except ValueError: return 0.0 for s in "a 0 12 123.4 12,345.67 12,24a".split(): print s, "->", strtofloat(s) Output: a -> 0.0 0 -> 0.0 12 -> 12.0 123.4 -> 123.4 12,345.67 -> 12345.67 12,24a -> 0.0 Peter From FBatista at uniFON.com.ar Wed Sep 17 14:28:34 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 17 Sep 2003 15:28:34 -0300 Subject: Money data type Message-ID: Can't find it. I mean something like: >> m1 = Money(decimal=2) >> m2 = Money(decimal=2) >> m1.value = 3.20 >> m2.value = 2.15 >> print m1 + m2 5.35 5.35! Not 5.3500000000000001 neither 5.34999999999999999999. I think this is not a rare thing, but I can't find it in the standar library neither the package index. Thanks! . Facundo From stain at ozelot.stud.ntnu.no Thu Sep 11 22:07:57 2003 From: stain at ozelot.stud.ntnu.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Fri, 12 Sep 2003 02:07:57 +0000 (UTC) Subject: Recursive import within packages Message-ID: all examples performed with: Python 2.3+ (#2, Aug 10 2003, 11:09:33) [GCC 3.3.1 20030728 (Debian prerelease)] on linux2 (2, 3, 0, 'final', 1) This is a recursive import: -- blapp.py -- print "Blapp start" import blupp print "Blapp end" -- blupp.py -- print "Blupp start" import blapp print "Blupp end" This works like a charm: >>> import blapp Blapp start Blupp start Blupp end Blapp end The same files with a directory thing with __init__: >>> from thing import blapp Blapp start Blupp start Blupp end Blapp end Changing the imports to import thing.blupp and import thing.blapp: >>> from thing import blapp Blapp start Blupp start Blupp end Blapp end Adding a print of the module with: print "Blapp end", blupp results in: >>> import blapp Blapp start Blupp start Blupp end Blapp end Changing to: import thing.blapp as blapp and vice versa >>> from thing import blapp Blapp start Blupp start Traceback (most recent call last): File "", line 1, in ? File "thing/blapp.py", line 2, in ? import thing.blupp as blupp File "thing/blupp.py", line 2, in ? import thing.blapp as blapp AttributeError: 'module' object has no attribute 'blapp' Changing to: from thing import blapp and vice versa >>> from thing import blapp Blapp start Blupp start Traceback (most recent call last): File "", line 1, in ? File "thing/blapp.py", line 2, in ? from thing.blupp import blupp File "thing/blupp.py", line 2, in ? from thing import blapp ImportError: cannot import name blapp And finally: print "Blapp start" import thing.blupp print "Blapp end", thing.blupp (and vice versa) >>> from thing import blapp Blapp start Blupp start Blupp end Traceback (most recent call last): File "", line 1, in ? File "thing/blapp.py", line 2, in ? import thing.blupp File "thing/blupp.py", line 3, in ? print "Blupp end", thing.blapp AttributeError: 'module' object has no attribute 'blapp' Adding a print of dir(thing) verifies this: -- blapp.py -- (and vice versa) print "Blapp start" import thing.blupp print dir(thing) print "Blapp end" >>> import thing.blupp Blupp start Blapp start ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] Blapp end ['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'blapp'] Blupp end -- blapp.py -- print "Blapp start" import thing.blupp import thing.notexisting print "Blapp end", thing.blupp >>> from thing import blupp Blupp start Blapp start Traceback (most recent call last): File "", line 1, in ? File "thing/blupp.py", line 2, in ? import thing.blapp File "thing/blapp.py", line 3, in ? import thing.notexisting ImportError: No module named notexisting Now, could anyone please explain to me the logic involved here? Why is circular import only valid when accessing them without package name? It clearly works by not using full references, even to print the module while the other module is being loaded. The user-fix to the problem is of course: a) Don't use circular references b) delay circular import until module usage (ie. within class/function) c) Use relative modulenames (works only within the same package) d) import thing.blapp - but don't expect thing.blapp to be there until module usage (ie. within class/function) But my question is why this works outside packages, but not inside packages. This must be a bug, but I can't find it anywhere in the bugs section on SourceForge. (A google search for 'circular import' on Google seems impossible =) Way too many circle-square-shape-examples!) The FAQ says: Circular imports are fine where both modules use the "import " form of import. They fail when the 2nd module wants to grab a name out of the first ("from module import name") and the import is at the top level. That's because names in the 1st are not yet available, (the first module is busy importing the 2nd). However that is not correct in this case, the "thing" module is loaded and works fine, it is the name thing.blapp that is not registered until after blapp is loaded. In my opinion thing.blapp should be bound before the actuall import of thing.blapp. Actually, thing.blapp gets registered into sys.modules right away. -- Stian S?iland Being able to break security doesn't make Trondheim, Norway you a hacker more than being able to hotwire http://stain.portveien.to/ cars makes you an automotive engineer. [ESR] From tim.one at comcast.net Fri Sep 26 11:11:56 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 26 Sep 2003 11:11:56 -0400 Subject: PEPs link gone from the Python homepage? In-Reply-To: Message-ID: [David Abrahams] > Since a significant part of Python is only documented in PEPs, I am > disappointed to see that they can't be easily found. Where are they? Well, the only sane way to try to find anything on the web anymore has become google. google on Python PEP and the top hit is the right hit: http://www.python.org/peps/ python.org's own sometimes-working search page will also take you to it. The most straightforward path from the python.org home page is probably via the Developers link. Then has links to the PEP index, SF bug and patch managers, SF CVS browser, and so on. From timh at zute.net Wed Sep 10 10:39:23 2003 From: timh at zute.net (Tim Hoffman) Date: Wed, 10 Sep 2003 22:39:23 +0800 Subject: Pass-by-reference : Could a C#-like approach work in Python? In-Reply-To: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> Message-ID: <3f5f3667$1@news.highway1.com.au> Hi Stephen The bit I can't fathom is why you would want to do this ? At least in the case of the simple example you give. In your example aren't you really asking for a reference to a reference to be passed, because in Python you always just pass a reference to an object, in the sense that x = 1 is variable x pointing to the integer object 1. When you call inc function you are taking an immutable object 1 and creating a new object which is the result of adding 1 to 1. And what you are then asking it to rebind the variable x to point to the new int object 2 inside the function. Why you would want to do this is unclear. Secondly if it where a more abstract object it would have an increment method which you could call on the object which was passed to the function. So again I just can't see why you want to do it. Maybe I am missing something here Tim Stephen Horne wrote: > I have in the past suggested that Python functions could use some kind > of modifier token for parameters to indicate pass-by-reference, so > that immutable items in particular could be modified (or more > accurately replaced) by the function, with that modification affecting > what the caller sees. In case I'm explaining this badly, here is how > Python currently works... > > >>>>def Inc(p) : > > ... p += 1 > ... > >>>>x = 1 >>>>Inc(x) >>>>x > > 1 > > ... and here is (roughly) what I'd like to be able to do... > > >>>>def Inc(ref p) : > > ... p += 1 > ... > >>>>x = 1 >>>>Inc(x) >>>>x stuff removed. > I would then be able to write... > > >>>>def Inc(ref p) : > > ... p += 1 > ... > >>>>x = 1 >>>>Inc(ref x) >>>>x > > 2 > > Obviously the implementation would not be trivial, but i think this > would be a very useful feature. > > Any thoughts? > From Scott.Daniels at Acm.Org Mon Sep 29 19:28:06 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 29 Sep 2003 16:28:06 -0700 Subject: Python question In-Reply-To: References: Message-ID: <3f78c007$1@nntp0.pdx.net> John D. wrote: > #This program gives: "SyntaxError: unqualified exec is not allowed > # in function _ it contains a nested function with free variables" Here is a (slightly) smaller version that may give you an idea: def myfunc(codetext): def setvar(): d[0]=1 exec codetext ### Causes the error def myfunc(codetext): def setvar(): d[0]=1 exec codetext in globals() ### Does not cause the error The complaint is about the ambiguity of z's execution environment (globals and locals), when there is code (setvar) which will reference the local environment. Notice that: def myfunc(codetext): def setvar(d): d[0]=1 exec codetext has no problem: setvar now only looks at its own code. The question is not what setvar looks at outside of itself (enclosing function or globals), but whether it can (potentially) look at any of myfunc's locals. If setvar looks at nothing, it doesn't matter whether code in z potentially creates a local in myfunc or not. Hope this is enough for you to figure it out. If not, ask a few more questions. -Scott David Daniels Scott.Daniels at Acm.Org From jepler at unpythonic.net Mon Sep 15 21:01:41 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 15 Sep 2003 20:01:41 -0500 Subject: object.attribute vs. object.getAttribute() In-Reply-To: References: Message-ID: <20030916010135.GS32270@unpythonic.net> On Mon, Sep 15, 2003 at 08:29:10PM -0400, Roy Smith wrote: > For the past 6-8 months, I've spent most of my time writing C++ and a > little bit of Java. Both of these languages support and encourage the > use of private data and explicit accessor functions, i.e. instead of > writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to > writing Python, I find myself in a quandry. > > Historically, I've always avoided accessor functions and just reached > directly into objects to get the value of their attributes. Since > Python doesn't have private data, there really isn't much advantage to > writing accessors, but somehow I'm now finding that it just feels wrong > not to. I'm not sure if this feeling is just a C++/Java-ism that will > cure itself with time, or if perhaps it really does make sense and I > should change the way I code. Write your python code naturally, using 'x = foo.bar'. Derive all your classes from 'object' (use new-style classes). If you ever need to do something "behind the scenes", you can switch to using "property", and have a function automatically called on attribute read, write, and delete---and it even documents itself: class C(object): def __init__(self): self._y = 0 def get_x(self): return self._y * self._y def set_x(self, val): self._y = val def del_x(self): raise TypeError, "Cannot delete attribute" x = property(get_x, set_x, del_x, "A stupid attribute that squares itself" "... and won't go away") >>> from roy import C >>> c = C() >>> c.x = 3 >>> print c.x 9 >>> del c.x >>> del c.x Traceback (most recent call last): File "", line 1, in ? File "/tmp/roy.py", line 12, in del_x raise TypeError, "Cannot delete attribute" TypeError: Cannot delete attribute >>> help(C) [...] | ---------------------------------------------------------------------- | Properties defined here: | | x | A stupid attribute that squares itself... and won't go away [...] Jeff From peter at engcorp.com Wed Sep 17 09:19:03 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 17 Sep 2003 09:19:03 -0400 Subject: Meaning of MOP (was Re: was: Re: looking for MOP documentation) References: <3F62123C.F671D058@engcorp.com> <3F6319E9.4C7BAA0F@engcorp.com> <3F66F516.3D06D946@engcorp.com> Message-ID: <3F685F47.E9F9F71E@engcorp.com> Peter Hansen wrote: > > Ng Pheng Siong wrote: > > > > According to Peter Hansen : > > > kasper graversen wrote: > > > > On Fri, 12 Sep 2003 14:36:44 -0400, Peter Hansen wrote: > > > > >> Erm, what's "MOP" mean? > > > > what has all this talk to do with documentation of the MOP??? > > > Er, if you'll look back, you'll see that Anthony asked what MOP > > > meant > > > > Meta Object Protocol. > > Thanks, but one might say that this is what it spells, not what it _means_. > > At this point, I'm sure google would help, if I felt a driving > need to go and learn what it really means. Annoyed that nobody seemed to be willing to actually define this (which leads me to suspect that none of those involved in the thread actually *know* what it means, other than to expand the acronym), I did a little searching and found http://cliki.tunes.org/Meta-Object%20Protocol , which at least attempts to define it. It still doesn't describe it well enough for someone to really understand the purpose, the value, the reason for bothering to do such a thing, but it's better than the definitions offered so far in this thread... -Peter From zanesdad at bellsouth.net Wed Sep 10 13:44:21 2003 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 10 Sep 2003 13:44:21 -0400 Subject: Threading troubles In-Reply-To: <1063211947.3f5f53abceb92@www.stud.u-szeged.hu>; from Monda.Laszlo@stud.u-szeged.hu on Wed, Sep 10, 2003 at 06:39:07PM +0200 References: <1063211947.3f5f53abceb92@www.stud.u-szeged.hu> Message-ID: <20030910134421.A28550@cerberus.liberty> * Monda.Laszlo at stud.u-szeged.hu (Monda.Laszlo at stud.u-szeged.hu) wrote: > > I want to control the execution of all threads from the main thread. I mean > stopping, continuing and terminating other threads. However as I've read in the > libc manual, there is no way to specify signal handlers for individual threads. > Actally I don't even know how could I signal any threads from Python at all. Any > workaround would be greatly appreciated. > Not sure if it's possible. Someone else on the list can correct me if I'm wrong. I did find the following post to c.l.p dated 2-19-2003: http://groups.google.com/groups?q=python+kill+thread&hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=mailman.1045698656.1301.python-list%40python.org&rnum=6 This post includes a patch to the Python interpreter that will allow the killing of a thread in Python. Not sure if that gets you any closer to your goal. I would strongly recommend that you think about the problem you are trying to solve and see if there is a better solution than starting/stopping/resuming threads (if that's even possible). A better approach would be to break down the tasks that you want your threads to accomplish into smaller pieces, possibly maintain state somewhere (either a thread-safe container if it's going to be accessed by the threads or in a plain-old container if the main thread is going to manage state) and have your main thread delegate the activity. A couple of excellent resources for dealing with threads is the Python standard library Queue and there is a recipe out on activestate that shows how to implement a thread pool (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871). I don't know exactly what you are trying to do, so maybe starting/stopping/resuming threads is the correct approach. I've just found that, typically, breaking things down a little more is a more manageable approach that is easier to wrap your head around. Jeremy Jones From guillaume.alleon at club-internet.fr Mon Sep 1 15:01:34 2003 From: guillaume.alleon at club-internet.fr (Guillaume ALLEON) Date: Mon, 1 Sep 2003 21:01:34 +0200 Subject: monitoring resources Message-ID: <3f53979a$0$20944$7a628cd7@news.club-internet.fr> Is there a way to monitor system resources (CPU, memory, ...) used by a running python script ? Thanks Guillaume From theller at python.net Fri Sep 26 11:54:32 2003 From: theller at python.net (Thomas Heller) Date: Fri, 26 Sep 2003 17:54:32 +0200 Subject: PEPs link gone from the Python homepage? References: Message-ID: "Daniel Dittmar" writes: > David Abrahams wrote: >> Since a significant part of Python is only documented in PEPs, I am >> disappointed to see that they can't be easily found. Where are they? > > Don't bother with site navigation, google "pep site:python.org". Or use mozilla together with Mark Hammond'd Python sidebar. This convinced me (among other things) to switch from IE to mozilla. Thomas From stacom at stacom-software.de Tue Sep 16 04:54:15 2003 From: stacom at stacom-software.de (Alexander Eisenhuth) Date: Tue, 16 Sep 2003 10:54:15 +0200 Subject: distributing a standalone python app. under Linux In-Reply-To: References: Message-ID: Nicola Mingotti schrieb: > Alexander Eisenhuth writes: > > >>Hallo alltogether, >> >>under windows, the py2exe is first choice, but has anybody done it >>under Linux ? My first try with Installer >> > > > most linux these days already have a python interpreter > installed so i think the simplest (simplistic) method > would be send the *.py or *.pyc file/s . > ( i follow this way when i give little apps to my friends ) Maybe youre right, but the applicatiobn runs under embedded linux, so the size of your applikation is another argument :-( Alexander From tdelaney at avaya.com Mon Sep 8 19:13:23 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 9 Sep 2003 09:13:23 +1000 Subject: Eureka! (Re: Comments on Python Redesign) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEAD4D04@au3010avexu1.global.avaya.com> > From: Delaney, Timothy C (Timothy) > > > From: Delaney, Timothy C (Timothy) > > > From: Delaney, Timothy C (Timothy) > > > > From: Delaney, Timothy C (Timothy) > > > > > From: Delaney, Timothy C (Timothy) > > > > > > From: Paul McNett [mailto:p at ulmcnett.com] > > > > > > > > > > > > > http://www.amazon.com/exec/obidos/tg/detail/-/0321112547/qid=1 > > > > > > > > 063059237/sr=1-4/ref=sr_1_4/002-8213749-9028058?v=glance&s=books > > Hmm - that URL doesn't look too good now ... Sorry - I sent too early ... The purpose of this email is to show that you don't always have control over the format of something. I regularly receive emails quoted 4-5 levels deep when receiving field issue reports. I spend too much time reconstructing URLs ... Tim Delaney From skip at pobox.com Sat Sep 6 18:08:57 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 6 Sep 2003 17:08:57 -0500 Subject: Any tools to print source code call hierarchy In-Reply-To: <200309061133.53521.scott_list@mischko.com> References: <200309061133.53521.scott_list@mischko.com> Message-ID: <16218.23289.361563.407292@montanaro.dyndns.org> Scott> I need a tool that will go through a python module (ClientForm in Scott> this case) and allow me to specify a starting module to parse and Scott> tell me what all it uses. This is not a trivial exercise to perform with Python because it is dynamically typed. In many cases you don't know the type of an object until runtime. Skip From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Sep 26 16:32:07 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 21:32:07 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: <9v59nv00v6jnfq5m507coditrok0e3h60q@4ax.com> On Fri, 26 Sep 2003 17:43:11 GMT, Andrew Koenig wrote: >Stephen> I doubt the need for exclusive ranges in integer for loops. I >Stephen> also doubt the need for switching between different range >Stephen> systems (inclusive, exclusive, half-open). IMO there is more >Stephen> confusion than anything down those routes. > >Really? I would expect a common usage to be: > > for 0 <= index < len(list): > do something with list[index] We have half-open already. I was commenting on the need for supporting several *different* schemes. Basically... I don't see the need to support this case... for 0 < index < len(list) : # ie exclusive And think that supporting one or the other of these two would be sufficient... for 0 <= index < len(list) : # ie half-open for 0 <= index <= len(list) : # ie inclusive And can I think of any languages that support a variety of cases? C, C++, Java etc support both half-open and inclusive with a simple change of the continuation condition operator. The Pascal, Modula 2, Ada etc seem to stick with inclusive IIRC. These 'limitations' don't really seem to cause a problem, though. That said, with all this reverse iteration stuff we've been discussing recently, there is a point to make. If half-open ranges are common, then the 'reverse' half-open case may be useful too... for len(list) > index >= 0 : It's basically a case of symmetry. It avoids the need for all those '-1' corrections we've been stressing about just recently. Well, who says I can't have second thoughts. Still not keen on the syntax, though. And as exclusive ranges have no apparent frequent use, and rewriting inclusive ranges as half-open ranges is not really a problem, so really we only need to support the two half-open cases. And that is really what all the backward iteration stuff is about. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From ads at chead.org Mon Sep 15 23:31:10 2003 From: ads at chead.org (ads) Date: Tue, 16 Sep 2003 10:31:10 +0700 Subject: from clipper move to python In-Reply-To: <3F668176.2020502@teksavvy.com> References: <3812075547.20030915130057@chead.org> <6.0.0.22.0.20030915085400.041dd200@66.28.54.253> <801542245.20030916095806@chead.org> <3F668176.2020502@teksavvy.com> Message-ID: <173526863.20030916103110@chead.org> Thank you again, and sorry for my "flamewar" word, I just hate because the system get crashes all the time, and I must rebooted which take long time. Regards, :) --------------- Replied message -------------- The Bat! mailer ver 1.53d ---------------------------------------------- Date : Tuesday, September 16, 2003 >From : Graham Fawcett To : ads Subject : from clipper move to python ---------------------------------------------- ads wrote: >Thank you for the respon, > >But right now I'm still not ready using linux, a lot of my client were >using windows. Is someone know what should I use to create text >console application like clipper using python in (stupid) windows? > >Thanks >:) > > Stupid Windows? Now, now, let's not start a flamewar. ;-) I've never used it, but I do see that there is a "Curses for Windows for Python" project at http://flangy.com/dev/python/curses/ though it's an "alpha" stage project. There's also "public domain curses" or pdcurses, available for Win32, http://gnuwin32.sourceforge.net/packages/pdcurses.htm Presumably it would work with the Python curses module. But again, I've not used it. In my opinion, you would probably have more success writing a GUI application using one of the "easy" app builders like PythonCard. It may be a new experience for you, but there will be more people who would be able to support you and answer your questions. -- Graham ---------------------------------------------- From a.neudecker at uni-bonn.de Tue Sep 2 11:17:41 2003 From: a.neudecker at uni-bonn.de (Andreas Neudecker) Date: Tue, 02 Sep 2003 17:17:41 +0200 Subject: Docs on speeding up Python code? Message-ID: Hi. I have seen some discussions going on about making Python code faster and several measures looked fairly 'esoteric' to me (i.e.: you need to know a lot of background things to even KNOW about these possibilities). Is there anywhere a concise Howto, article, PEP, whatever that describes possible measures to make Python code faster (and probably 'cleaner', too)? And possibly in a way, that a beginner or intermediate Python user can understand? ;-) If you know of any such docs, I would be happy if you could post some links. Regards Andreas From andrew-pythonlist at puzzling.org Tue Sep 16 23:11:44 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Wed, 17 Sep 2003 13:11:44 +1000 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <3F67CDEF.3030202@sci.fi> References: <16231.25317.741455.556170@montanaro.dyndns.org> <3F67677E.9030408@sci.fi> <16231.28433.221154.160576@montanaro.dyndns.org> <3F67CDEF.3030202@sci.fi> Message-ID: <20030917031144.GC7689@frobozz> On Wed, Sep 17, 2003 at 05:58:55AM +0300, Harri Pesonen wrote: > But if the reference count is negative for allocated objects, then you > already have a bug. I mean that the count is never negative when the > application works correctly. The object is already deallocated when the > count reaches zero, so checking for negative counts is (usually) > superfluous. Python gets slightly faster if you just remove this check > (from release version). Have you benchmarked whether removing this check makes any significant, or even measurable, difference to the speed of a Python program? I'm not convinced that the benefits of this outweigh the costs. -Andrew. From dave at boost-consulting.com Sun Sep 28 11:31:37 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 28 Sep 2003 11:31:37 -0400 Subject: Meta programming question References: Message-ID: Bruce Dickey writes: > Ben Finney wrote: >> On Sat, 27 Sep 2003 19:18:15 -0600, Bruce Dickey wrote: >> >>>I've read a number of the meta progamming articles. I have not found >>>what I am looking for. I want to override assignments to variables >>>which are in the module namespace (not object members -- no classes >>>involved). Can this be done? >> AFAIK, no. If it were possible, it would be very confusing. >> What is it you're trying to achieve? Perhaps a better alternative >> can >> be suggested that doesn't break expected behaviour. >> > I'm investigating the use of Python as a grammar language. I'm trying > to achive minimal required syntax/verbage. Cool! You might take a look at http://spirit.sf.net for some ideas. Python's a great language for metaprogramming because of its rich syntax. If you were willing to discourage left-recursion you might go with something like: expression = term._('+').expression | term._('-').expression On the other hand, when I had to do something like this I built my own "python-like" syntax for the grammar rules and left the semantic actions in pure Python, then ran the files through a simple preprocessor. It's just too ugly to write grammar rules in pure python without overloaded whitespace. -- Dave Abrahams Boost Consulting www.boost-consulting.com From wweston2003 at yahoo.com Sat Sep 20 10:09:30 2003 From: wweston2003 at yahoo.com (wes weston) Date: Sat, 20 Sep 2003 14:09:30 GMT Subject: Help with parsing and matching a character References: Message-ID: <3F6C5D5B.1050606@yahoo.com> Fernando, A look at some strings in p would help; but. for line in p: if line.find("/home/build90") > -1: doyourthing() or I think this works: if "/home/build90" in line: doyourthing() wes Fernando Armenta wrote: > Hello, > > > > I need some help matching a file to a path. This is my code: > > > > # I open an expect script to log into a linux system and get the > version (6.5) > > > > MGMTP_IP = x.x.x.x > > > > p = os.popen('./remcmd.exp ' + MGMT_IP + ' ver ' + ' | grep Management > > ' + ' build ') > > > > # I create a file call build with the version information > > > > I want to match the build information to an specific path /home/build90 > or /home/build91 > > > > How can I do that in Python? Thanks for your help. > > > > -F > > > From ialbert at mailblocks.com Sun Sep 7 20:02:40 2003 From: ialbert at mailblocks.com (Istvan Albert) Date: Sun, 07 Sep 2003 20:02:40 -0400 Subject: Redesign of Python site In-Reply-To: References: Message-ID: rt lange wrote: > http://www.pollenation.net/journal/index.php?p=37&c=1 > > main page mockup: > http://www.pollenation.net/assets/public/python-main.html The last time we redesigned our website, we've got a significant amount of of hate mail. "You suck", "Idiots", "Previously it was so great you had to destroy it", "I've been a user for five years but I will never come back to this site" etc... The odd thing is that we thought that the site was significantly more usable than before, after all the redesign was based on an extensive usability testing. (It was a pretty cool experiment, observing users trough a one way mirror as they attempted predefined tasks, multiple cameras and microphones tracking what users do, it is a great thing to do if you have the chance) It was pretty hard to digest this hate mail, it was as if these people had zero respect for all the hard work we've put in, in fact most email was actually very rude and rushed, yet the only common ingredient in all of these emails was the perceived infallibility of the authors themselves. But guess what, usage became indeed a whole lot higher, users were doing more searches and were submitting significantly more ratings than before. We have accomplished everything we wanted. This and other anecdotal evidence led me to the conclusion that redesingin a site in a way that will please old-timers is impossible. Even more, one should be very careful in gathering input from them since they might live in a different world than most of the people one wants to reach. Negative comments will always far outnumber positive ones, for the simple reason that it seems a lot harder to praise a work than putting it down. I would agree with most here that a more text based site would be more suited, but let's try to remember that there are people that worked hard on this, and may even be right in what they are trying to accomplish. cheers, Istvan. From joerg.maier at rz.uni-mannheim.de Mon Sep 8 18:39:56 2003 From: joerg.maier at rz.uni-mannheim.de (=?ISO-8859-15?Q?J=F6rg?= Maier) Date: Tue, 09 Sep 2003 00:39:56 +0200 Subject: pexpect and escaping " Message-ID: he guys, i have a problem using python and pexpect module in windows with cygwin: down a bash command like: [1] $ rsync --partial -cvaLe "/usr/bin/ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" "user at server:path_to_file" "/cygdrive/c/" it works perfect, but used in pexpect.spawn like : [2] child = pexpect.spawn(RSYNC_PATH, ['--partial', '--progress', '-cvaLe "/usr/bin/ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no"', '"' + myssl.user + '@' + myssl.server + ':' + source + '" "' + target + '"'], timeout=300) i got child.before from pexpect that is like: No such file or directory Failed to exec "/usr/bin/ssh : but without " around ssh and options rsync is about to think that -o UserKnownHostsFile=/dev/null is an rsync option and gives an error. every masking with \ or \\ or \\\ fails. Any ideas howto tell pexpect just to pass the first string? Thank you, J?rg -- Hi I am a signature virus. Please copy me to your .signature file to help me spread. From kiko at async.com.br Sat Sep 20 14:38:14 2003 From: kiko at async.com.br (Christian Reis) Date: 20 Sep 2003 11:38:14 -0700 Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <17d520f6.0309130701.222d09fe@posting.google.com> Message-ID: ubaidullahnubar at hotmail.com (Ubaidullah Nubar) wrote in message news:<17d520f6.0309130701.222d09fe at posting.google.com>... > I will appreciate some more clarification regarding the GUI framework. > From the wxPython web site, it looks very good but the two tools > mentioned here > for easing the development of GUI apps (mojoview and kiwi) are both > based on GTK. Well, I can speak of Kiwi at least, which I designed to help us write large GUI applications in Python, here at Async Open Source. Kiwi is different from most of the other frameworks you'll find in the sense that it encourages you to move beyond the string manipulation that's so common in GUI programming (read a string from an entry, write a string to a label, etc etc). In Kiwi, you're expected to work with objects holding data and low-level domain semantics (want to display objects as a list? define the columns, and load the objects in the list with one call; no more worrying about string/numeric/date conversions). Kiwi *really* cuts code length down; you could probably write a phonebook application like you've asked initially in less than 40 lines, if using libglade. The intention when writing Kiwi was to allow you to be truly object oriented while coding; it's not a simple wrapper around a C/C++ API as most of the other GUI libraries are (of course, Kiwi hijacks James' PyGtK library to its own evil purpose) > Are they fundamentally different or just a matter of style. > > How easy to switch from one framework to another? Kiwi is fundamentally different, though you can use as much as you like (just the base view classes, the proxy, the widgets, etc). I think you'll find that the more you use a framework, the harder it is to switch (as with any library). > Which framework supports internationalization better? Do they support > Right-to-left layouts? GTK+2 has this pretty much solved; pango is a very nice implementation. > Also, a comparison between Boa Constructor and Glade-2. I haven't seen > either so am not sure if they are even comparable. Glade, when associated with libglade, is a *great* way to write the GUI. All Glade does is generate XML, which libglade reads at runtime -- the rest is real code, version-controllable code that you can work with in your preferred editor. There's nothing that offers comparable reuse and long-term productivity, IMHO, but others will differ. From aleax at aleax.it Mon Sep 22 09:31:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 13:31:11 GMT Subject: was: Re: looking for MOP documentation References: <3F62123C.F671D058@engcorp.com> <3F6319E9.4C7BAA0F@engcorp.com> <3F66F516.3D06D946@engcorp.com> <3F69AD0F.53D51719@engcorp.com> <3F69D215.5649AF66@hotmail.com> <3F69DFEB.5B05CED8@engcorp.com> <7h37k45j895.fsf@pc150.maths.bris.ac.uk> <3F6B2AB1.2D839EF5@engcorp.com> <7h3he359eda.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson wrote: ... > Fair enough. I can see your point of view, I just don't (completely) > agree with it :-) You could have something with similar syntax, > keywords, etc to Python but semantics like C, and it would still be > horrible (IMHO). Tried pyrex? It comes reasonably close to the "something" you describe, and it ain't all that horrible (IMHO). Alex From maney at pobox.com Sun Sep 7 00:39:03 2003 From: maney at pobox.com (Martin Maney) Date: Sun, 7 Sep 2003 04:39:03 +0000 (UTC) Subject: Redesign of Python site References: Message-ID: rt lange wrote: > came across this page searching feedster. > dont know whether this is the official resdesign or just a proposal; > but the mockups look very nice. They look very nice if you're just taking in the view: they look like crap if you want to actually read the content. I've posted a more detailed complaint there, but in brief "I say it's spinach..." -- There's one way to find out if a man is honest: ask him; if he says yes, you know he's crooked. -- Twain From jjl at pobox.com Fri Sep 5 21:01:21 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Sep 2003 02:01:21 +0100 Subject: Why python??? References: Message-ID: <87fzjalogu.fsf@pobox.com> "Michael Peuser" writes: [...] > "Alex Martelli" schrieb im Newsbeitrag > news:NO66b.30883$R32.926812 at news2.tin.it... > > Michael Peuser wrote: [...] > > Moore's Law is working in favour of higher level languages even harder > > than it's working in favour of free but highly efficient OS's. > > There are two aspects: > (1) More power for same price - this works in favour of 'complex software' > (2) Same power for less money - this works in favor of 'cheap software' And? What is your point? In both cases, the more bangs per buck, the greater the economic advantage that accrues to Python when compared with, say, C++. [...] > > > So it comes to the question: What does the common programmer know? This > is > > > > Not necessarily. If common programmers only knew machine language, > > it would still be cheaper to use any available high-level language, > > say COBOL, even if you needed to supply training for it (it's not > > hard to teach COBOL to somebody who knows assembly, anyway -- the > > reverse is harder). > I am on your way; maybe they more probably would be trained for some "macro > language". This is no 'paradigm change'. Most C++ programmers (I know what I > say!) write C programs. That's certainly true of switching to C++ from C, because C++ is a hideous hairy beast of a language. OO in Python is easy to learn by comparison, because you don't have to think about all that other stuff -- the C++ language details that are pressing because they're the things stopping you from getting your work done in the short run. Python is an order of magnitude easier to learn than C++, but it brings really significant programmer-efficiency benefits. As a result, the argument about training simply doesn't stand up: the costs are lower than the benefits even on a short timescale. > > Similarly, using Python can lower costs even > > if you factor in training costs (again, teaching Python to good > > Cobol programmers is quite easy -- other higher-level languages may > > not be _quite_ as cheap in these terms, admittedly, but still the > > economics aren't _hugely_ different). > > This argument is valid for: > - OOP ("Reuse will reduce costs") > - RAD > - XP > - Design-for-testing > - Rigid configuration control > - state any new thing you like > > The fact that a better world is possible does not mean you get it. True (with the definite exception of 'state any new thing you like'!), but I get the impression most places don't even try. Obviously, OOP *has* swept the industry, and presumably most commercial development makes use of version control. > Python is by no means a "perfect" alternative to - lets say: DOT-NET and > # - the advantages are difficult to see for persons in power or - I > mentiones the tool costs - are of minor relevance. Well, there's our point of disagreement, I think. Certainly, they're difficult to see for persons in power -- that's mostly their fault, though ;-) Total costs are exactly the issue -- the contention is that use of languages like Python really does have a significant impact on that. > I should as well like to discuss your aspect of programmer's productivity. > This is an important factor. However all investigations show that > programmer's productivity is an unmeasurable quantity. How would an empirical investigation show such a thing? Financial constraints certainly make such studies rare, and the large number of variables make them difficult, but it's far from impossible. Small-scale studies have been done -- I remember at least one (reference, anybody?), and it certainly supported the position that C++ and C are, by a fat margin, less programmer-efficient than higher-level languages: Perl, Python, etc. Larger-scale studies would simply cost more. On top of this, I think it should be noted that science is far from limited to such empirical studies. In fact, that kind of study is really the dregs of science, at the same sort of level as epidemiology. Epidemiology, in the long term, isn't a fraction as useful as real understanding of the processes of life, which has as much to do with theory as experiment. In the absence of that, our common-sense counterpart of that kind of theoretical understanding, backed up by what little empirical research that exists so far, and (just as importantly) by the anecdotal experience of people who've suffered both Python and other languages, is actually the best knowledge we have. These common-sensy bits of knowledge aren't merely matters of opinion, they're backed up by experience and sound argument from people like Alex. Far from perfect, but the best knowledge we have is the knowledge we should be using! > It certainly has to > do with what the programmer likes to do. If he or she would like to program > in Python everething would be fine. However most or today's programmers like > to do what is called "mainstream" (circular reasoning, I know) [...] Yes, and that reasoning is only valid when you remember that it's merely shorthand for "mainstream languages give us access to well-supported library code, well-stocked labour market, etc. etc.". When you take those things into account, Python still frequently comes out on top. John From skip at pobox.com Thu Sep 11 17:21:46 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 11 Sep 2003 16:21:46 -0500 Subject: why is this failing? In-Reply-To: <9x58b.139$u07.2@newsread1.news.atl.earthlink.net> References: <9x58b.139$u07.2@newsread1.news.atl.earthlink.net> Message-ID: <16224.59242.726053.25593@montanaro.dyndns.org> Chris> def write(self, value, row=None, col=None, len=None): You overrode the len() builtin in your function signature ^^^. Skip From max at alcyone.com Sun Sep 7 16:01:11 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 07 Sep 2003 13:01:11 -0700 Subject: negative indices for sequence types References: Message-ID: <3F5B8E87.99452C9A@alcyone.com> dan wrote: > I was recently surprised, and quite shocked in fact, to find that > Python treats negative indices into sequence types as if they were > mod(length-of-sequence), at least up to -len(seq). That is not the behavior of negative indices. Negative indices mean index from the end of the sequence. So -1 means the _last_ element in the list, -2 means the second to last element in the list, and so on. -n (for n = len(seq) is the first element in the list. > This fact is *deeply* buried in the docs, and is not at all intuitive. It's mentioned prominently (and early) in all the tutorials and books on Python I've read, and it's a very common and convenient convention, so I'm not sure how far you could have gotten through learning Python and never been exposed to it. > One of the big advantages of a high-level language such as Python is > the ability to provide run-time bounds checking on array-type > constructs. To achieve this I will now have to subclass my objects > and add it myself, which seems silly and will add significant > overhead. If you want this behavior, how hard is it to say a = b[x % > len(b)] ?? That's simply not true. Negative indices have similar bounds requirements. If you have a sequence of length n, then indices 0 through (n - 1) map to the elements of the sequence in order from left to right, and indices -1 through -n map to the elements in order from right to left. Indices greater than n or less than -n generate IndexErrors. Bounds checking is always done, whether on positive or negative indices. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Then you give me that Judas Kiss / Could you hurt me more than this \__/ Lamya From jepler at unpythonic.net Tue Sep 16 17:11:48 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 16 Sep 2003 16:11:48 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <5CH9b.81$2k.16@reader1.news.jippii.net> References: <3F632226.2010607@earthlink.net> <5CH9b.81$2k.16@reader1.news.jippii.net> Message-ID: <20030916211148.GD29089@unpythonic.net> On Tue, Sep 16, 2003 at 08:22:41PM +0300, Harri Pesonen wrote: > It is more efficient to have one process and several threads, than > several processes each having one thread. If it's easier to code "several processes each having one thread", then I'll sure do it. I've accepted a 2x-100x speed hit by using Python, so if it's a 25% difference in efficiency, I won't sign up to wait for code that doesn't exist yet. Jeff From cliechti at gmx.net Wed Sep 10 14:25:33 2003 From: cliechti at gmx.net (Chris Liechti) Date: 10 Sep 2003 20:25:33 +0200 Subject: Same GUI in both CPython and Jython? References: Message-ID: York wrote in news:bjni2a$i06$1 at pegasus.csx.cam.ac.uk: > Hi, everybody, > > Is it possible to write GUI applicaitons (in pure python code) that > can run Both in CPython and in Jython? search for "anygui" http://anygui.sourceforge.net/ chris -- Chris From tl_nntp at webcrumb.com Tue Sep 2 10:03:52 2003 From: tl_nntp at webcrumb.com (Tom Lee) Date: Tue, 02 Sep 2003 14:03:52 GMT Subject: Overloading objects In-Reply-To: References: <3f5469c4@news.comindico.com.au> Message-ID: <3f54a347@news.comindico.com.au> Chad Netzer wrote: > On Tue, 2003-09-02 at 02:58, Tom Lee wrote: > >>Batista, Facundo wrote: > > >>>I thought using defaults: >>> >>>def myMethod (self, name, age=None): >>> self.name = name >>> if age not None: >>> self.age = age >>> >>> >>>but I'm concerned about the scalability of this. > > > In general, it isn't a problem. You really don't want methods with LOTS > of arguments. If you need variable numbers of arguments, where the > default value system doesn't help you, just use *args, and do things > positionally by counting the length of the argument list. > > In Python, you can always use argument keywords when you call your > method, so you don't need to remember the positions. Learn to rely on > keyword arguments, and your life with Python will be happier. > > Also, you can use a dictionary to hold and pass your arguments around > easily, and can have it automatically substitute the keyword values when > you call the function (using **kwds). If you need LOTS of arguments, > use a dictionary or class, and pass THAT to your method. > > >>>What's the most pythonic way to do this? Using something like *args or >>>**args? > > > Yes. It is easy and powerful once you see some examples. > > > [Tom Lee] > >>Scalability doesn't even come into this question - if you're really >>worried about performance, don't use Python. > > > I assume the original poster was concerned with the scaling of the > number of arguments, and it becoming unmanagable to use and maintain. > Not anything to do with speed (ie. a different kind of 'scaling') Ah, cheers. > > >>Anyway, you have two or three choices: >> >>1. Do it the way you're doing it. > > yep. > > >>2. Check parameter types at runtime using type() and the is keyword. e.g. >>if type( somevar ) is int: >> self.do_int_stuff( somevar ) >>else: >> self.do_other_stuff( somevar ) > > > Rather than doing explicit type checks, it is somehat more robust to try > to operate on the argument as if it were a valid type, and be prepared > to handle exceptions. Only coerce to another to another type when you > need to: > > try: > self.do_int_stuff( int( some_int_like_var ) ) > except TypeError: > [handle the other cases or error] > > If you do want to have set types (as one often does), try to test based > on behavior, since many objects can act similarly and interact together, > without being the same type (and so type checking will always be overly > restrictive and reduce the utility of your design) > > Anyway, it is a tangential, and somewhat more advanced topic than this > thread was started to cover. > Along the same lines of the argument against isinstance right? Makes sense. > >>3. Use similar names for similar methods. wxPython does this. e.g. > > > yep. Although that's not my favorite design. Just makes it harder to > learn things by introspection (requires more reference manual searching > than using fewer methods with more option arguments, (IMO)) It's a > tricky balance, sometimes. > Yeah, but by the same token it makes your methods a little easier to read. I agree, however. From eduardo.aguiar.developer at bol.com.br Tue Sep 9 13:44:07 2003 From: eduardo.aguiar.developer at bol.com.br (eduardo.aguiar.developer) Date: Tue, 9 Sep 2003 14:44:07 -0300 Subject: os.listdir Message-ID: > "Michael Peuser" wrote in message news:... > > "Graham Fawcett" > > > Hari wrote: > > > > > >What I wanted to know was, is it guaranteed that between 2 calls > > > >os.listdir any files added to the directory are appended and the > > > >earlier order is maintained? > > > > As others pinted out, this is jighly improbably, espacially under windows > > > > > > > There's no need for such sequence guarantees, though. It's probably not > > > the most efficient but here's a way to do it: > > > > > > import os > > > import time > > > > > > somedir = '/tmp' > > > snapshot1 = os.listdir(somedir) > > > time.sleep(...) > > > snapshot2 = os.listdir(somedir) > > > > > > newfiles = [f for f in snapshot2 if not f in snapshot1] > > > > > > Pretty efficient, really: that's an O(n) comparison if I remember my > > > Python internals correctly. Which I don't, so don't trust my word for > > > it. ;-) > > > > > > You are wright to mistrust it ;-) > > Though 'f in list' looks harmless it itself is o(n) because there seems to > > be a linear search (This is different whith 'f in dict' of course). So your > > list comprehension is of o(n*n). > > > > Kindly > > Michael P > > D'oh! Thanks, Michael, I *knew* I'd messed that up... > > I'll repeat "list searches linear, dict lookups constant..." a hundred > times before bed tonight. I think you got something to repeat the night after also :-) "list searches linear, dict lookups log2(n)" __________________________________________________________________________ Acabe com aquelas janelinhas que pulam na sua tela. AntiPop-up UOL - ? gr?tis! http://antipopup.uol.com.br/ From tim at remove_if_not_spam.digitig.co.uk Mon Sep 15 14:41:15 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Mon, 15 Sep 2003 19:41:15 +0100 Subject: Powerset Message-ID: <8q1cmvg6t1mtcqf6nac7u1ff0i2ds89od8@4ax.com> Has anybody written a good powerset function for that nice new set datatype we now have? I've found a powerset operator for Python lists on the net, but that depends on lists being indexable which sets aren't. I suppose one answer is to iterate the set into a list, use the powerset I've got, then iterate the answer back int a set... From mpeuser at web.de Sat Sep 6 04:41:58 2003 From: mpeuser at web.de (Michael Peuser) Date: Sat, 6 Sep 2003 10:41:58 +0200 Subject: OT: best book in years References: <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <3F5868BA.85F506B4@engcorp.com> Message-ID: "Nick Vargish" schrieb im Newsbeitrag news:m3brty8vs2.fsf at tanelorn.bandersnatch.org... > "Michael Peuser" writes: > > > So I should contribute another classical book: > > Hofstadter: Goedel Escher Bach > > Good god, man! The guy's already going to be in the hospital. GEB is > something that should be tackled at full health. > May be not! I had been in hospital last year and I remember how my thoughts were spinning around. I think it is a good oportunity to dig into self-referential matters where our brain is not made for in its healthy state ;-) Kindly Michael P From zanesdad at bellsouth.net Tue Sep 2 14:50:19 2003 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 2 Sep 2003 14:50:19 -0400 Subject: Python REST framework? Message-ID: <20030902145019.B18621@cerberus.liberty> Does anyone know if there exists a Python REST (web services) framework? I've googled and come up short. I don't think it should be that hard to do if one doesn't exist (famous last words). I guess one could subclass BaseHTTPServer and have specified things to do depending on the path and the method? Jeremy Jones From Scott.Daniels at Acm.Org Fri Sep 5 15:34:43 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 05 Sep 2003 12:34:43 -0700 Subject: compiling python In-Reply-To: References: Message-ID: <3f58e550$1@nntp0.pdx.net> Birgit Rahm wrote: > Hallo newsgroup, > because so many people helped me, I hope for help onesmore. > If I compile a python py file to a pyc file, will there the paths of the > included files (or other paths) hardly be written to the pyc file and why. > (Does not find this import file without this path anymore?) > Which sense is behind there? > TIA,Birgit The model is that you import "modules" not files. As a result, where you find the module is kind of accidental. For example, when I am working on a largish program, I'll have several modules in my 'current development' directory, get the application to work with with those updated modules, and then check the modules back in to the central directories. If the .pyc files remebered locations, I might accidentally be testing the accepted code, rather than my new implementations. -Scott David Daniels Scott.Daniels at Acm.Org From jennyw at dangerousideas.com Tue Sep 23 16:21:45 2003 From: jennyw at dangerousideas.com (jennyw) Date: Tue, 23 Sep 2003 13:21:45 -0700 Subject: Barcode generator for Python? Message-ID: <20030923202144.GA8187@dangerousideas.com> Does anyone know of a barcode generator for Python? I'm looking to do this on Windows. It would be nice to find something free, but that's not necessary (so long as it's reasonable). It doesn't have to be Python-specific, either, so long as I can call it from Python. I'd love to hear any suggestions. I've seen bookland.py, but the kind of barcodes I'm looking to generate are not ISBN barcodes. Thanks! Jen From aahz at pythoncraft.com Mon Sep 8 15:32:04 2003 From: aahz at pythoncraft.com (Aahz) Date: 8 Sep 2003 15:32:04 -0400 Subject: Eureka! (Re: Comments on Python Redesign) References: Message-ID: In article , Skip Montanaro wrote: > > >> http://tinyurl.com/mlcv > > aahz> Many people, me included, won't follow tinyurl links; > >Why? Because I don't like going to random sites. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From richie at entrian.com Fri Sep 19 12:23:17 2003 From: richie at entrian.com (Richie Hindle) Date: Fri, 19 Sep 2003 17:23:17 +0100 Subject: pop3 email header classifier? In-Reply-To: References: Message-ID: <6cammvoibfes7scnan7kkorctoi55n4d57@4ax.com> [Robin] > Hi, I'm getting vast numbers of fake upgrade emails containing some kind > of virus. My rather old client can be made to reject these based on some > patterns in the subject line. They're nearly all based on the word > 'New', 'Latest', 'Microsoft', 'Patch', 'Pack', ... etc etc. > > Is there a python tool that can be made to delete these from my POP3 > mail box rather than let my client reject? I have a webmail application that can be made to delete messages based on regular expressions, at http://entrian.com/cgi-bin/pop3.py I wrote it in response to a similar problem, whereby a spammer used my address as his From address, and I received a couple of thousand bounce messages a day. You can set up regular expression filters on To, From and Subject, and set it to either mark messages for deletion (so you get to review them before deleting them) or delete them straight away (via the "I'm either brave or stupid" checkbox, TM 8-) You can save your filters for later use. Take EXTREME CARE with this, particularly if you check the "I'm either brave or stupid" box. 8-) There is no way to recover a deleted message. Don't sue me if it eats your hamster's emails. You probably need something like (untested): From: microsoft|ms\b Subject: patch|latest|microsoft|update|upgrade|pack There's no SSL version of this, so your POP3 account details will pass in plain text over the internet (in theory my provider has a scheme whereby you can access the site over SSL using their certificate, but it doesn't work for some reason - if there's any interest I'll see whether I can make it work). (And no, I'm not going to harvest your POP3 account details. They never even hit the hard drive.) -- Richie Hindle richie at entrian.com From gillet at scripps.edu Tue Sep 30 12:42:55 2003 From: gillet at scripps.edu (Alexandre Gillet) Date: Tue, 30 Sep 2003 09:42:55 -0700 Subject: build a static python executable on linux? In-Reply-To: <16249.36161.620488.759202@montanaro.dyndns.org> References: <16249.36161.620488.759202@montanaro.dyndns.org> Message-ID: <3F79B28F.9040005@scripps.edu> Thanks for the hints. But I think it will too much work to do now and not enough time. So I will probably build my interperter with a older version of glibc so I am sure it will run on all the linux platform and not only the one using glibc 2.3 Thanks Alex Skip Montanaro wrote: > Alex> I am able to compile a static interpreter (using -static > Alex> -static-libgcc) but I can not build the extensions correctly. > > You effectively need to transport yourself back in time before distutils > existed, and modify Modules/Setup (or more correctly, Modules/Setup.local) > appropriately to define the build commands for all the extension modules you > want to include in your interpreter. It's a little tedious the first time > (it will probably take a few iterations to get everything correct), but once > you get the hang of it, it's easy to do. Use the compile and link commands > output by distutils to give yourself a head start on -I, -L and -l flags to > include in your definitions. Many of the commented out definitions are > probably also close. > > If you identify some modules with no commented out build definitions in the > Setup file, please file a bug report on SourceForge. > > Skip > > -- o Alexandre Gillet email: gillet at scripps.edu / The Scripps Research Institute, o Dept. Molecular Biology, MB-5, \ 10550 North Torrey Pines Road, o La Jolla, CA 92037-1000, USA. / tel: (858) 784-2053 o fax: (858) 784-2860 From dtolton at yahoo.com Fri Sep 26 11:46:09 2003 From: dtolton at yahoo.com (Doug Tolton) Date: Fri, 26 Sep 2003 15:46:09 GMT Subject: PIL: Group4 Tiff Images Message-ID: Does PIL still not have a Group4 Tiff decoder available? I can load a group4 Tiff just fine, but when I attempt to show it I get: >>> im = Image.open('images/00000001.tif') >>> im.show() Traceback (most recent call last): File "", line 1, in ? File "C:\PYTHON23\Lib\site-packages\PIL\Image.py", line 1192, in show _showxv(self, title, command) File "C:\PYTHON23\Lib\site-packages\PIL\Image.py", line 1739, in _showxv file = self._dump(format=format) File "C:\PYTHON23\Lib\site-packages\PIL\Image.py", line 410, in _dump self.load() File "C:\PYTHON23\Lib\site-packages\PIL\ImageFile.py", line 165, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "C:\PYTHON23\Lib\site-packages\PIL\Image.py", line 309, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder group4 not available I have been able to load a group4 tif into the wxImage class, but I get tag errors when attempting to do so. Is there a better way of working with Group4 Tiffs? I have a huge volume of Tiffs and decompressing them isn't a good option for me. Any ideas on the best way to tackle this problem? Doug Tolton (format t "~a@~a~a.~a" "dtolton" "ya" "hoo" "com") From pfleonard at hotmail.com Mon Sep 22 05:22:44 2003 From: pfleonard at hotmail.com (peter leonard) Date: Mon, 22 Sep 2003 02:22:44 -0700 Subject: Begineer Question : Global string substitution with re Message-ID: Hi, This is a basic question but I can't figure out what is wron - even after reading the documentation. I have a script that normalizes strings. One of the steps is to convert all fractions too the tag 'fraction'. For example : import re line = "This is the first ratio, 170/37, and this is the second 170/37 " def normalise(text): #Tag fractions fraction = r'(\s+\d+\/\d+\s+)' regfr = re.compile(fraction) text = regfr.sub(" |fraction| ",text) #Remove punctuation punc = r'\,' regpunc = re.compile(punc) text = regpunc.sub("",text) return text print line,"\n" print normalise(line),"\n" The output from this script is : This is the first ratio, 170/37, and this is the second 170/37 This is the first ratio 170/37 and this is the second |fraction| I can't understand why only one of the fractions gets substituted. The documentation for sub states that the default argument for sub is 0 which means replace all occurences. The output of my script should be : This is the first ratio |fraction| and this is the second |fraction| Any help appreciated. Peter _________________________________________________________________ Add MSN 8 Internet Software to your existing Internet access and enjoy patented spam protection and more. Sign up now! http://join.msn.com/?page=dept/byoa From secun at yahoo.com Thu Sep 25 08:41:24 2003 From: secun at yahoo.com (Sector Unknown) Date: 25 Sep 2003 05:41:24 -0700 Subject: Help with dialog box Message-ID: I've written a Python script that runs a MS Windows program using popen. However, at the end of the Windows program, a dialog box appears and asks for the user to click on OK. Is there a way to have Python set focus on the dialog box and click OK so my script can continue? Does anyone have an example? From farmenta at pillardata.com Fri Sep 19 16:04:18 2003 From: farmenta at pillardata.com (Fernando Armenta) Date: Fri, 19 Sep 2003 13:04:18 -0700 Subject: Help with parsing and matching a character Message-ID: <36504F2E352484458C5D574719DC8372BAC617@caex01.trans.corp> Hello, I need some help matching a file to a path. This is my code: # I open an expect script to log into a linux system and get the version (6.5) MGMTP_IP = x.x.x.x p = os.popen('./remcmd.exp ' + MGMT_IP + ' ver ' + ' | grep Management > ' + ' build ') # I create a file call build with the version information I want to match the build information to an specific path /home/build90 or /home/build91 How can I do that in Python? Thanks for your help. -F -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at andreweland.org Fri Sep 5 07:20:59 2003 From: google at andreweland.org (Andrew Eland) Date: 5 Sep 2003 04:20:59 -0700 Subject: newbie question about dictionnary ? References: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Message-ID: <6817af2.0309050320.49f262e@posting.google.com> "Sophie All?on" wrote in message news:<3f582f90$0$20952$7a628cd7 at news.club-internet.fr>... > for doing this I thought the dictionary was excellent but the key is a > string while I want it > to be the 2 points forming the edge ? How to do it ? Unlike perl, the keys used for a Python dictionary can be arbitary objects. You're not forced to use strings. If you represent edges as a tuple of the form (startPoint,endPoint), you can do the following: >>> start=(1,1) >>> end=(2,2) >>> edges={} >>> edges[(start,end)]=1 >>> if (start,end) in edges: ... print "Edge exists" ... Edge exists If you're using Python 2.3, you can use the new sets module, which will give you an object repesenting a set, which is a little neater than just using a dictionary. -- Andrew (http://www.andreweland.org) From SBrunning at trisystems.co.uk Mon Sep 22 09:32:43 2003 From: SBrunning at trisystems.co.uk (SBrunning at trisystems.co.uk) Date: Mon, 22 Sep 2003 14:32:43 +0100 Subject: Mutable strings Message-ID: <31575A892FF6D1118F5800600846864D014B294E@intrepid> > From: Alex Martelli [SMTP:aleax at aleax.it] > Hans-Joachim Widmaier wrote: > > > I don't think strings are immutable because they ought to be that way > > (e.g. some CS guru teaches that "mutable strings are the root of all > > evil"). They're immutable because they allow them to be used as > > dictionary keys. And it was found that this doesn't affect the > > usefulness of the language too much. > > Wrong. Consider Java, even back from the very first version: it had > no dictionaries on which string might be keys, yet it still decided > to make its strings immutable. This should make it obvious that the > interest of using keys as dict keys cannot possibly be the sole > motivation for the decision to make strings immutable in a language. > Rather, the deeper motivation is connected to wanting strings to be > ATOMIC, ELEMENTARY types, just like numbers; and to lots of useful > practical returns of that choice. All you lose is the "ability" to > "confuse" (type-pun) between strings and arrays of bytes in many > situations, but that's an ability best lost in many cases. It's not > an issue of "evil" -- a close-to-the-hardware low-level language > like C has excellent reasons to choose a different, close-to-HW > semantics -- but in a higher-level language I think Python's and > Java's choice to have strings immutable works better than (e.g.) > Perl's and Ruby's to have them mutable. I came across a good write up of this principle today - . Cheers, Simon Brunning, http://www.brunningonline.net/simon/blog/ --LongSig ----------------------------------------------------------------------- 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 kmkstyle at hotmail.com Tue Sep 16 07:41:03 2003 From: kmkstyle at hotmail.com (Kathleen Kudzma) Date: Tue, 16 Sep 2003 07:41:03 -0400 Subject: (no subject) Message-ID: Does anyone know how to embed a Pygame window in a Tkinter widget? _________________________________________________________________ Get 10MB of e-mail storage! Sign up for Hotmail Extra Storage. http://join.msn.com/?PAGE=features/es From mwh at python.net Thu Sep 25 07:23:40 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 25 Sep 2003 11:23:40 GMT Subject: Memory profiling References: Message-ID: <7h34qz12k1d.fsf@pc150.maths.bris.ac.uk> Rune Froysa writes: > Does Python provide any tools that can help in determining where the > memory is used? *Memory*, no. Especially in a debug build, there are tools for finding out where the objects are, though. > Ideally, I would like to see a tool that can list all objects by > memory-usage, but any tool that can return the number of bytes used > by an arbitrary object would be of great help. Even something that > could find all allocated dicts&lists and return their size+name > would help. In a debug build, look at sys.getobjects. In a recent release build, look at gc.get_objects. Cheers, mwh -- something happens, what I'm not exactly sure. -- PyPy debugging fun From tim.hochberg at ieee.org Tue Sep 23 15:08:04 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Tue, 23 Sep 2003 12:08:04 -0700 Subject: Thoughts on PEP284 In-Reply-To: References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: Stephen Horne wrote: > On Tue, 23 Sep 2003 08:44:13 -0700, Tim Hochberg > wrote: > > >>FWIW, Psyco recognizes this structure and removes the overhead >>associated with it. > > > I went looking for Psyco yesterday, and all I could find was broken > links. Was sourceforge just having bad day, or is there a new site > that hasn't made it into Google yet? Probably the former. I just checked at http://psyco.sourceforge.net/ and everything seemed to be working. -tim From sheershion at mailexpire.com Wed Sep 10 17:47:36 2003 From: sheershion at mailexpire.com (Robert Amesz) Date: Wed, 10 Sep 2003 21:47:36 -0000 Subject: Python reading output from a running, external process References: Message-ID: Matt Goodall wrote: > Basically, os.popen() would allow you to execute the simulation > tool and have its output channelled back to the GUI application > through a file-like object. > > I don't know wx much but it is generally possible to attach a file > (i.e. the file returned by popen) to the GUI's event queue so that > one of your event handlers is called when there is new output from > the simulation tool. It should be easy enough to parse that to > update the UI. In my experience it is *not* a good idea to use popen() in wxPython apps, at least not under Windows: there seems to be some buffering going on in popen(), totally ruining any sense of concurrency. Also, reading the streams returned by popen() block, something to be avoided at all costs in a GUI program. Finally, the process exit code is lost when using popen(). Fortunately, in wxPython you can use a wxProcess, which doesn't buffer or block, and can be polled using timer or idle events. There's an example of how to use it in the wxPython demo. Robert Amesz From stuart at bmsi.com Mon Sep 22 20:54:24 2003 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 22 Sep 2003 20:54:24 -0400 Subject: Mandrake Linux 9: Why isn't bsddb working? References: Message-ID: On Fri, 19 Sep 2003 18:04:15 -0400, Dfenestr8 wrote: > On Thu, 18 Sep 2003 09:26:49 +0000, Skip Montanaro wrote: > > >> >> What might I have done wrong, and/or what should I do to fix it? >> >> Skip> You probably don't have the necessary -devel RPM installed. >> >> >> That might have been true while I was using the rpm package. >> >> >> But currently I'm using the source package Python-2.3.tgz. >> >> Doesn't matter. The _bsddb module can't be built if the relevant >> header files and libraries are not in place. >> >> Skip > > The rpm -devel package just won't install unless it detects I have > python itself installed as an rpm. And I kind of like the version of > IDLE that comes with Python 2.3, so I'd rather keep it. (Also, I'm not > completely sure how to uninstall it. "make uninstall" doesn't work). Skip is talking about the devel RPMs for bsddb. For instance, do you have db3-devel installed? Or db4-devel? On RedHat 7, the default bsd db is db3-3.2.9. You would need db3-devel installed to get the bsddb module built. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From bblancett at hotmail.com Fri Sep 19 17:33:05 2003 From: bblancett at hotmail.com (Bill) Date: 19 Sep 2003 14:33:05 -0700 Subject: SMTPlib Emailing Attachments References: <4fd6e92.0309170849.287e86b6@posting.google.com> <4fd6e92.0309190518.3b226735@posting.google.com> Message-ID: <4fd6e92.0309191333.20114e3@posting.google.com> Karl Scalet wrote in message news:... > Bill wrote: > > > [...] > > path = 'C:\\YourPath\\YourFile.txt' > > filename = 'YourFile.txt' > > is this correct? Shouldn't path contain the directory only? > Otherwise what's the content of YourFile.txt then. > > Karl Well I believe you need the file as well b/c the mimetypes function checks the extension to see what type of file it is. I am sure you can modify it to be more efficient. But it works as is. From bgailer at alum.rpi.edu Wed Sep 24 13:12:34 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 24 Sep 2003 11:12:34 -0600 Subject: Pre-PEP: reverse iteration methods In-Reply-To: References: Message-ID: <6.0.0.22.0.20030924111106.02790b58@66.28.54.253> At 06:30 PM 9/23/2003, you wrote: >Here is a discussion draft of a potential PEP. >The ideas grew out of the discussion on pep-284. >Comments are invited. Dart throwing is optional. > >The discussion so far has focused on how to modify the operand of for x in. > >There is another viewpoint: consider that we are modifying the behavior of >for x in > >In APL we often modify the behavior of a primitive operator by adding >something to the operator itself. For example >+/A means apply + along the last last dimension of the array A. (e.g. sum >the elements in each row of the matrix A) >To sum along the columns change the expression to =+/[1]A where the index >modifies the / operator. > >Could this open the door to some fundamentally new Python syntax that >would support the modification of keyword behavior? e.g.: > >for x in[-1] list: >for[-1] x in list: >for x in[-1] list:for x in[-1] list: >for.reverse x in list: >for x out list: >rof x in list: > >Let's brainstorm? Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From mcfletch at rogers.com Fri Sep 12 00:01:37 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 12 Sep 2003 00:01:37 -0400 Subject: getting ttf font/family name; fontTools? In-Reply-To: References: <3F60F508.8030300@rogers.com> Message-ID: <3F614521.7060302@rogers.com> John Hunter wrote: >>>>>>"Mike" == Mike C Fletcher writes: >>>>>> >>>>>> >This looks useful -- thanks. There apparently is an error in >family_query.py > > Hmm, yes, bit-rot due to the fact that I only ever use it from within OpenGLContext (which does it's own setup of a registry object). new,failed = registry.scan( printErrors = 1, force = 0) is how it should read instead of: new,failed = registry.scan( directories, printErrors = 1, force = 0) I've checked the change into CVS. That'll teach me to open my big mouth :) . Have fun, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From alanmk at hotmail.com Sun Sep 21 12:08:20 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 21 Sep 2003 17:08:20 +0100 Subject: Server-side programming References: Message-ID: <3F6DCCF4.9C1FBCC5@hotmail.com> Timo Virkkala wrote: > I'm creating a system with Python CGIs, that connect to a database. I'm > wondering about input validation. Of course I will check the length of > the passed parameters, to (hopefully) prevent any DOS attacks. What else > do I need to check? Do I need to remove any SQL from the inputs? > Anything else I might have overlooked? You might not need to remove SQL from your field values. Doing so would probably be a non-trivial string parsing exercise. Most "SQL injection" attacks would be where a cracker hopes that you are going to embed the contents of "username" and "password" fields right into a string containing an SQL query, like so mySQLString = """ select * from users where uname = "%s" and password = "%s" """ % (username, password) If the query returns a non-zero number of rows, then that username/password combination is deemed to be valid. The problem comes when the cracker deliberately subverts the content of the fields, supplying values like these, for example username='alan' password='" or 0=0 or password="' Which when embedded into the SQL query string gives the following final SQL query: select * from users where uname = "alan" and password = "" or 0=0 or password="" Which will return at least 1 row, assuming that "alan" is a valid username. Now, trying to parse the syntax of the password field, looking for SQL keywords such as "or", could be complex: there are quite a few possible ways in which the query can be textually subverted. AFAIK, the most effective way to prevent such attacks is to disable any quote characters that may be present in the password, so that they are treated as a part of the password string, not as delimiters in the SQL query string. For example import re password = re.escape(password) Which for the values given above would now give an SQL query of select * from users where uname = "alan" and password = "\"\ or\ 0\=0\ or\ password\=\"" Does anyone know of a more effective approach to preventing SQL injection attacks? Another potential attack is the "Cross Site Scripting (XSS) Attack", whereby the attacker inserts javascript into a field value, which is then embedded into the HTML transmitted by a web app to another user, for example as a post in a message board. This hostile javascript can do any number of nasty things to users browsers including stealing cookies, or url-rewritten session IDs, so that the innocent users login session can be hijacked and abused. Here is an article about XSS attacks. http://www.cgisecurity.net/articles/xss-faq.shtml AFAIK, the most effective solution to preventing XSS attacks is to ban HTML/tags/javascript from being inserted into text strings that will be displayed as part of a HTML page. This could be done by 1. Parsing the string as HTML, and stripping out > > And opened it in IE6.0 on WinXP. Unfortunately, it doesn't show > anything. > > After googling, I tried "pyscript.py --debug" and the trace collector > shows: > > Object with win32trace dispatcher created (object=None) > in _InvokeEx_ with GetInterfaceSafetyOptions 0 1 > (IID('{BB1A2AE2-A4F9-11CF-8F20-00805F2CD064}'),) None None > in _InvokeEx_ with GetInterfaceSafetyOptions 0 1 > (IID('{BB1A2AE1-A4F9-11CF-8F20-00805F2CD064}'),) None None > > Am I doing something stupid? > > Jane Try pyscript_rexec.py instead, with the line 184(raise) of rexec.py commented out. From paul.moore at atosorigin.com Mon Sep 15 11:07:07 2003 From: paul.moore at atosorigin.com (Paul Moore) Date: 15 Sep 2003 08:07:07 -0700 Subject: Datetime utility functions Message-ID: <182bcf76.0309150707.3a8c0482@posting.google.com> I was just writing some code which did date/time manipulations, and I found that the Python 2.3 datetime module does not supply a number of fairly basic functions. I understand the reasoning (the datetime module provides a set of datatypes, and doesn't attempt to get into the murky waters of date algorithms) but as these things can be quite tricky to get right, I was wondering if anyone has already implemented any date algorithms, or alternatively if I'd missed some easy way of doing what I'm after. My specific requirements were: 1. Get the last day of the month contatining a given date(time). I really was surprised to find this one missing, as it seems to me that the datetime module must know what the last day for each month is, so exposing it wouldn't have been hard. 2. Add a number of months to a date. This is messy, as there are options (what is one month after 31st Jan). The trouble is that the calculation, while simple, is tricky to get right (month is 1-based, so off-by-1 errors are easy to make, and divmod isn't as useful as you'd first think). Other "nice to have" functions which I didn't need for this program, but which I have found useful in the past, are - Round a date(time) to a {year,month,day,quarter,week,...} Or truncate. Or (occasionally) chop to the next higher boundary (ceiling). - Calculate the number of {years,months,days,...} between two dates. (Which is more or less the equivalent of rounding a timedelta). These latter two aren't very well defined right now, because I have no immediate use case. In the absence of anything else, I'll probably write a "date utilities" module for myself at some point. But I'd hate to be reinventing the wheel. Paul. From peter at engcorp.com Tue Sep 23 09:35:01 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Sep 2003 09:35:01 -0400 Subject: General Password questions References: <3F6F86A2.DC29472A@engcorp.com> Message-ID: <3F704C05.2932235F@engcorp.com> Richard Brodie wrote: > > "Riccardo Attilio Galli" wrote in message > news:pan.2003.09.23.13.26.53.712668 at riquito.matrix... > > On Mon, 22 Sep 2003 19:32:50 -0400, Peter Hansen wrote: > > > I don't want to ask to the user every time the account password, but also > > I don't want to store it as plain text. > > > Do you know what is the usual practice in these cases? > > The usual practice is to store the password in some trivially breakable encryption > scheme, preserving some illusion of security. Hah! :-) True... sadly. I'll say what I said a moment ago in the other response, but in a different way. If it is possible to retrieve the plaintext password, whether because it was stored in plaintext or because it was stored with some trivially breakable encryption scheme (or even if it was stored with an incredibly sophisticated encyprtion scheme), the system is broken. Nobody, adminstrators included, should ever be able to retrieve the plaintext password of a user, and even with a fancy encryption scheme, there is always a separate password or key which can be used to reverse the encryption. Use hashes. -Peter From skip at pobox.com Mon Sep 8 17:38:56 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 8 Sep 2003 16:38:56 -0500 Subject: Eureka! In-Reply-To: <8LPX/kKkX89D092yn@gnosis.cx> References: <3F5CD10B.2020709@teksavvy.com> <200309072018.05589.dave@pythonapocrypha.com> <3F5CF116.2F755AA6@engcorp.com> <8LPX/kKkX89D092yn@gnosis.cx> Message-ID: <16220.63216.458481.826762@montanaro.dyndns.org> David> Peter Hansen wrote previously: David> |* You can't tell ahead of time what site you are going to be redirected to. David> | As a result, you lose complete freedom to choose whether or not you should David> | follow the link. David> As Dave Brueck noted, the same is true of ANY URL. I use a few David> redirects on my own website, ... Ditto here, including a couple for pages that started out in my Python Bits tree but migrated elsewhere, like to the Python Wiki. Clearly the opportunity for abuse using tiny urls is somewhat higher because they are much easier to create, but I've never had a problem. You judge the context and the presumed source of the URL and take your chances. Skip From adalke at mindspring.com Sat Sep 27 22:05:54 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 28 Sep 2003 02:05:54 GMT Subject: Important news For all webmaster,newsmaster References: Message-ID: <6mrdb.6136$RW4.449@newsread4.news.pas.earthlink.net> Wazo at that.bug.you.on.net.com> wrote: > To fight Copyright and illegal usagers of Newsgroups > it's recommand to set all you News server to receive and send > only 32 kbytes of article for all newsgroups (250 lines) Well that would restrict about 2/3rd of Alex's posts. ;) Actually, there's only post in the last couple weeks over 32Kb, and Alex has the 4th largest post at 14Kb. Not that a limit would change anything; back in the old days, newsreaders included features to merge uuencoded binaries from multiple, smaller postings. I've not needed it now that the web is a much better source for posting large files. But for that old time feel, search Google Groups for "Python 0.9.1 part" http://groups.google.com/groups?q=%22Python+0.9.1+part%22&hl=en&lr=&ie=UTF-8 &oe=UTF-8&scoring=d&start=10&sa=N&filter=0 and download all 20 parts (part 2 wasn't needed.). Andrew dalke at dalkescientific.com (Hah! Knew I could make the response on-topic.) From tzot at sil-tec.gr Tue Sep 16 12:21:53 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 16 Sep 2003 19:21:53 +0300 Subject: Datetime utility functions References: Message-ID: On Tue, 16 Sep 2003 11:28:58 -0400, rumours say that "Tim Peters" might have written: >[Christos TZOTZIOY Georgiou] >> I sent my own version without having seen your own --and mine might >> seem obfuscated, compared to yours. Only a minor suggestion: don't >> use dt.replace, use dt.__class__ instead, since you wouldn't want your >> function to have side-effects (that is, don't destroy the actual >> object that dt is bound to.) > >It's OK to use replace: datetime and date (also time and timedelta) objects >are immutable -- their values can't be changed after initialization. In >particular, x.replace() doesn't mutate x. In some strange, unprecedented and inexplicable way, you are right... ...again :) RTFM-F virus not removed yet. PS That bang thingie (!) in Ruby is pythonic. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From phil_nospam_schmidt at yahoo.com Thu Sep 18 13:10:00 2003 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 18 Sep 2003 10:10:00 -0700 Subject: Money data type References: Message-ID: <221e7b06.0309180910.79da3932@posting.google.com> Try this: ------------------------- import types class USD: """ This class represents money in US Dollars, does math on it, prints it, etc. All dollar amounts are stored in cents, and no fractional cents are allowed. Rounding is supported for fractional cent values that are passed in. """ def __init__(self, value=0): """U.S. Dollars, stored in cents.""" if isinstance(value, USD): self.value = value.value else: self.value = int(round(value * 100)) def __repr__(self): """This is returns a string that may be exec'ed to get a duplicate.""" s = '%03i' % self.value s = 'USD(%s.%s)' % (s[:-2], s[-2:]) return s def __str__(self): """return a nice formatted printable string""" return '$%9.2f' % (float(self.value) / 100) def STR(self): """return a 'raw' formatted printable string""" return '%0.2f' % (float(self.value) / 100) def __add__(self, value): """perform self + value""" # handle the case where value is a string if type(value) is types.StringType: return self.__str__() + value # otherwise it's assumed to be a numeric type m = USD(value) m.value += self.value return m def __radd__(self, value): """perform value + self""" # handle the case where value is a string if type(value) is types.StringType: return value + self.__str__() # otherwise it's assumed to be a numeric type m = USD(value) m.value += self.value return m def __sub__(self, value): """returns a USD instance containing the difference between self and value""" m = USD(value) m.value = self.value - m.value return m def __rsub__(self, value): """returns a USD instance containing the difference between value and self""" m = USD(value) m.value -= self.value return m def __iadd__(self, value): """perform self += value""" m = USD(value) self.value += m.value return self def __isub__(self, value): """perform self -= value""" m = USD(value) self.value -= m.value return self def __neg__(self): """return negated self""" m = USD() m.value = -self.value return m def __pos__(self): """return self""" m = USD() m.value = self.value return m def __lt__(self, value): """perform self < value""" m = USD(value) return self.value < m.value def __gt__(self, value): """perform self > value""" m = USD(value) return self.value > m.value def __eq__(self, value): """perform self == value""" m = USD(value) return self.value == m.value def __ne__(self, value): """perform self != value""" m = USD(value) return self.value != m.value def __le__(self, value): """perform self < value""" m = USD(value) return self.value <= m.value def __ge__(self, value): """perform self < value""" m = USD(value) return self.value >= m.value From llothar at web.de Sat Sep 6 19:34:21 2003 From: llothar at web.de (Lothar Scholz) Date: 6 Sep 2003 16:34:21 -0700 Subject: Any tools to print source code call hierarchy References: Message-ID: <6ee58e07.0309061534.5f8cf00f@posting.google.com> Scott Chapman wrote in message news:... > I'm sure I'm not using the conventional names for this tool, more of a > cross-referencer?. I couldn't find it on Google, I think for this reason. > > I need a tool that will go through a python module (ClientForm in this case) > and allow me to specify a starting module to parse and tell me what all it > uses. > > What I'm trying to do is to take ClientForm apart enough to pull out just the > html form parsing code in it and use it elsewhere. It would be MUCH easier > when approaching someone elses code if I could see what all functions are > called by a given function, etc. Because python is a dynamical typed non image language there is no tool that can do this and there never will be any (at least one that is not using heuristics or sampled data from previous runs). From glingl at aon.at Sun Sep 21 05:00:26 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun, 21 Sep 2003 11:00:26 +0200 Subject: None??? In-Reply-To: References: Message-ID: <3F6D68AA.9070603@aon.at> Heather Coppersmith schrieb: > >>weekly_income = income/52 > > >>def compute(income, percent): >> result = income*percent/100 >> print result > Additionally please notice, that your program will produce incorrect and probably at first irritating results: **** example output: **** How much do you make a year after taxes? 5199 What percent of your income do you want to put aside? 1 Ok, Gregor Lingl This is how much you should put away a week: $ 0 **** This comes from using integer-constants together with inputting integers, which causes the /-operator to perform integer division. A simple way to avoid this would be to use 52.0 and 100.0 instead of 52 and 100 Regards, Gregor From donn at drizzle.com Sat Sep 20 21:01:30 2003 From: donn at drizzle.com (Donn Cave) Date: Sun, 21 Sep 2003 01:01:30 -0000 Subject: spam killing with poplib References: Message-ID: <1064106088.798812@yasure> Quoth "Phil Weldon" : | At best that will identify less than a third of the messages produced by | this worm. A permutating and mutating bogus 'Undeliverable e-mail' message | carrying the infection package is more common than the HTML message. Either | type is over 100 KBytes, and will quickly clog a mailbox. | | Expect the HTML message body, FROM and SUBJECT to mutate also. I've been getting one every two minutes or so for the last couple of days, so I had to do something this morning. Luckily I have shell access and fairly conventional UNIX mail delivery, so I put in a filter on delivery. My criterion is nowhere near as complicated as the rest of you folks, but after about 6 hours it caught 157 and missed no more than a dozen. I just look for 'boundary="[a-z]' in the header. Of course that could easily turn out to catch a legitimate email ... but of course, with an attachment, and I don't want your stupid Word document anyway. The filter is 38 lines of awk (with comments), and a C program to lock the folder and invoke the awk program. Donn Cave, donn at drizzle.com From srijit at yahoo.com Thu Sep 18 11:16:57 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 18 Sep 2003 08:16:57 -0700 Subject: SciTE Message-ID: <221d8dbe.0309180716.17d73ae2@posting.google.com> Hello, I am unable to access http://www.scintilla.org/tags2api.py? May I have a copy of the program? Regards, Srijit From jjl at pobox.com Tue Sep 2 17:59:03 2003 From: jjl at pobox.com (John J. Lee) Date: 02 Sep 2003 22:59:03 +0100 Subject: htmllib.py and parsing malformed HTML References: Message-ID: <873cfeyhqw.fsf@pobox.com> KC writes: > Thomas G?ttler wrote: > > Hi, > > You could use tidy (http://www.w3.org/People/Raggett/tidy/) before > > you > > parse the html. > > I appreciate the suggestion but unfortunately this will not work well > for me as the parser runs as part of a cron job. I wouldn't be able > to review the tidy error log in a timely fashion if there was a > problem. [...] So, what about *your* code's error log (or the equivalent -- presumably an unhandled traceback)?? It's not obvious that your solution (in a later post) will be any more robust than just piping everything through HTMLTidy. In fact, since you will find a great variety of nonsense in 'HTML as deployed', it seems likely that HTMLTidy will do the better job. John From gerrit at nl.linux.org Mon Sep 29 16:41:43 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 29 Sep 2003 22:41:43 +0200 Subject: isNumber? check In-Reply-To: <5B71DD32-F2BB-11D7-9145-003065F081D2@cs.brown.edu> References: <20030929142027.GA6750@nl.linux.org> <5B71DD32-F2BB-11D7-9145-003065F081D2@cs.brown.edu> Message-ID: <20030929204143.GA8765@nl.linux.org> Rob Hunter wrote: > On Monday, September 29, 2003, at 10:20 AM, Gerrit Holl wrote: > >Rob Hunter wrote: > >>How do I check if a value is a number in Python? > >> > >>One way is (x == type(1)) and (x == type(1.2)) and (x == > >>type(2387482734274)) and ... > >> > >>but this seems kludgy. Any better way? > > > >Why do you want to do so? > > > I am writing an interpreter, and my parser has to decide if an > expression is a number or not. So you actually have a string... Maybe you could do something like this: if expr.strip("0123456789.e") == "": print "May be a number!" if expr.strip("0123456789") == "": print "Surely a number!" Gerrit. -- 249. If any one hire an ox, and God strike it that it die, the man who hired it shall swear by God and be considered guiltless. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From python at sarcastic-horse.com Tue Sep 9 11:18:35 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Tue, 9 Sep 2003 11:18:35 -0400 (EDT) Subject: I need to make Excel/Powerpoint-style charts. Message-ID: <56665.199.169.240.132.1063120715.squirrel@svr1.turboweb.net> Hi- My office produces a lot of charts based on time-series data. We use MS powerpoint and excel to make these charts. The data gets updated regularly, but there doesn't seem to be an easy way to automate updating the charts using these packages. So, we spend a non-trivial amount of time manually updating lots of spreadsheets to redraw the charts we need. I hope to find some sort of python graphics library that can make charts similar to Excel and Powerpoint, and then I can start automating these tasks. Here is an example of the charts we make: http://www.sarcastic-horse.com/example.pdf #52k size file. Are there any packages that can do similar charts? I need to be able to chart time-series data with occasional missing observations. I also need to be able to shade some regions of the charts, and add text titles, captions and notes. I'm (slowly) learning the reportlab package, and it looks good, but I wanted to check if there was an even better solution out there. Thanks for the help. From bblancett at hotmail.com Wed Sep 17 12:49:01 2003 From: bblancett at hotmail.com (Bill) Date: 17 Sep 2003 09:49:01 -0700 Subject: SMTPlib Emailing Attachments Message-ID: <4fd6e92.0309170849.287e86b6@posting.google.com> I am trying to have the capability to email attachments. Specifically I want to be able to email a specific attachment that I name that may be a PDF document, text doc, etc. I already have a working piece of code that emails jpg attachments but does not work with any other types of attachments. Could someone tell me how to modify this code to send other types of attachments like the one's stated above(especially PDF's)? Also how do I determine the name of the attachment? Right now it defaults to Attach0. Here is the current code I have below: _________________________________________________ import sys, smtplib, MimeWriter, base64, StringIO message = StringIO.StringIO() writer = MimeWriter.MimeWriter(message) writer.addheader('Subject', 'The Text test') writer.startmultipartbody('mixed') # start off with a text/plain part part = writer.nextpart() body = part.startbody('text/plain') body.write('This is a picture of chess, enjoy :)') # now add an image part part = writer.nextpart() part.addheader('Content-Transfer-Encoding', 'base64') body = part.startbody('image/jpeg') #body = part.startbody('text/plain') base64.encode(open('c:\email\chess01.jpg', 'rb'), body) # finish off writer.lastpart() # send the mail smtp = smtplib.SMTP('fc.hbu.edu') smtp.sendmail('bblancett at hbu.edu', 'bblancett at hbu.edu', message.getvalue()) smtp.quit() __________________________________________________________________________ From hankc at nospam.com Fri Sep 19 00:36:54 2003 From: hankc at nospam.com (HankC) Date: Fri, 19 Sep 2003 04:36:54 GMT Subject: advice choosing IDE References: Message-ID: <3f6a84c6.49006998@news.la.sbcglobal.net> On Mon, 18 Aug 2003 14:18:48 +0200, "Michael Peuser" wrote: > >Well, I think you will have a hard time ahead. No one who has ever used >Delphi, VB or RealBasic can really understand in what poore shape Python >(and Perl is no better) support is ;-) > I beg to differ. I've been programming Delphi professionally for about six years so I know the tool well. For Win32 development of *anything* other than device drivers it's hands down the best development tool, IMO. However, 'shape' can be determined by requirements. I'm in the process of switching to BOA/Python... - Cross platform applications will make me a lot of money. - Execution speed isn't a huge issue for me. What's wrong with Borland/Delphi? - Because of their rapidly expanding product line, including big money makers like JBuilder, Delphi is getting less attention (waiting, waiting for bug fixes) - Kylix is virtually dead, and never was good for generally distributed application development because of it's release cycle. Granted, BOA/Python has nowhere near the polish of Delphi but OTOH Python has better staying power and better cross-platform support. >From my POV, Python is in better shape than Delphi (VB is in even worse shape). From jcjouffre at bigfoot.com Thu Sep 18 05:25:23 2003 From: jcjouffre at bigfoot.com (jcj) Date: 18 Sep 2003 02:25:23 -0700 Subject: variable to be transmitted from a CGI script to a module Message-ID: <4568052b.0309180125.5fd4919a@posting.google.com> hello, is it possible to have something like : script.cgi #!/usr/local/bin/python # -*-python-*- global MY_VARIABLE MY_VARIABLE = "myvalue" import module1 module1.my_function() module1.py # -*-python-*- global MY_VARIABLE if MY_VARIABLE: print 'variable defined' else: print 'variable NOT defined' def my_function(): print 'my_function' when I try to compile the module, I obtain this message : Traceback (most recent call last): File "", line 1, in ? File "module1.py", line 3, in ? if MY_VARIABLE: NameError: global name 'MY_VARIABLE' is not defined same error when executing the python CGI script thanks in advance Jean-Claude From jwdillworth at yahoo.com Tue Sep 23 09:17:54 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Tue, 23 Sep 2003 06:17:54 -0700 (PDT) Subject: Need arguments for "Python vs. Perl as an OOPL" In-Reply-To: Message-ID: <20030923131754.19143.qmail@web41108.mail.yahoo.com> Actually, Perl does have a "super" construct. Take this Python script: class Base1(object): def method(self): print "Base1.method called" class Base2(object): def method(self): print "Base2.method called" class Sub(Base1, Base2): def method(self): print "Sub.method called" super(Sub, self).method() obj = Sub() obj.method() Sub.method is called, and it calls Base1.method (but not Base2.method). This Perl script does exactly the same thing: package Base1; sub method { print "Base1::method called\n"; } package Base2; sub method { print "Base2::method called\n"; } package Sub; use base qw(Base1 Base2); sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } sub method { my $self = shift; print "Sub::method called\n"; $self->SUPER::method(); } package main; my $obj = new Sub(); $obj->method(); Actually, I think I like Perl's super-as-a-property-of-self a tad better than Python's super-as-a-builtin. Anyway, if you argue that Perl doesn't have this or that and aren't sure, you could lose credibility if you're wrong. Maybe you could find someone in your office well-versed in OO-Perl that's sympathetic. Or perhaps you could have a look at Manning's book on OO-Perl by Conway (the PDF is $21). I don't think Perl's exception handling is very OO (if at all). Also, errors can very easily pass silently in Perl if you don't explicitly ask it to make a fuss. I'd argue that Python's class syntax is simpler and more intuitive than Perl's, and that should count for something. If it didn't, everyone would follow the gtk+ folks and be writing object oriented programs in C :) (not bashing gtk+ at all, but you have to admit OO-C is unorthodox and a little bit of a hack) --- Raymond Hettinger wrote: > > "Roy Smith" wrote in message > news:roy-002696.23242122092003 at reader2.panix.com... > > I'm working on a prototype of a new application in Python. At some > > point, if this ever turns into a product, the powers that be will almost > > certainly demand that it be done in Perl. My job will be to convince > > them otherwise. > > > > The basic design of the application is object oriented. I've never used > > Perl's OO features, so I'm not in a good position to make a comparison > > of the two languages from an OO point of view. Can somebody who's done > > OOP in both Python and Perl help me out? > > > > I certainly know why Perl sucks in general, but for this purpose, I need > > to specifically compare the OO features of the two. I'm looking for > > something more fundamental than "->{} is ugly". > > If you're to find a major difference in OO implementations, it will likely > be with Python's new style classes. So, the advantages are: > > * easy implementation of metaclasses through __metaclass__ > * super() for cooperative superclasses > * a method resolution order that supports cooperative superclasses > and complex inheritance hierarchies > * __slots__ for lightweight instances > * o.__getattribute__ for easy intercepts of method calls and attribute lookup > * descriptors which make easy work of otherwise hard tasks > * the fruits of descriptors: class methods, static methods, and properties > (which make it possible to avoid coding many getters and setters). > > Other than the new-style gizmos, it's mostly the same candy in a different > wrapper. > > > Raymond Hettinger > > > -- > http://mail.python.org/mailman/listinfo/python-list From axel at pizza.home.kosnet.com Tue Sep 9 15:52:03 2003 From: axel at pizza.home.kosnet.com (Axel Straschil) Date: Tue, 9 Sep 2003 21:52:03 +0200 Subject: Codesample for xml/xslt transforming References: <871xupg5uk.fsf@pobox.com> Message-ID: Hello! > That looks like Python code to me, Axel, not XSLT . It's Yeah, I've ordered it, I've got it! > writing the XSLT that's the pain, not interpreting it (though that can Mhh, XSLT is not very usefull for programming, but I don't think that it hurts so much. > XML is good because it's an widely-understood, easy-to-read, > not-to-complicated, *non*-loathesome standard that gets the job done. > XSLT... well, it's a standard. And it has an 'X' in the name, of > course, which is the killer feature . I agree with you that all the X* things are an marketing killer feature. Let mit tell you the little story how I came to the whole X-Biest: Im programming with Zope/Python/PostgreSQL to produce dynamic content for Webpages. I realy was fu**ed up of the whole PHP shit, where content and source was sticked together. Zope makes thinks better, but not perfekt. I didn't want to switch to XSLT, becouse of speed. But I didn't found anything better if you want to bring the content in an blackbox to the webdesigner. I was also booring always digging around in the sources when the design of an site changed. So, with XSLT, if design is changing, I don't care. I even don't care about XSLT, becouse I should be the designers work to change it. I see XLST as an "scripting language". -- Lg, Axel. From dave at 3dex.com Tue Sep 16 22:38:09 2003 From: dave at 3dex.com (Dave Benjamin) Date: Wed, 17 Sep 2003 02:38:09 GMT Subject: scoping with lambda in loops References: <7f9e1817.0309161338.20fbdcbc@posting.google.com> Message-ID: "martin z" wrote in message news:KvP9b.49089$DZ.34699 at news04.bloor.is.net.cable.rogers.com... > > a = [] > > for index in range(5): > > a.append(lambda index=index: index) > > > > or maybe more concisely > > > > a = [lambda index=index: index for index in range(5)] > > You know how Python is supposed to be executable pseudocode? Well that > stuff is farking ugly. If I handed pseudocode like that into any TA in one > of my classes, I'd be toast. Is there any way to do that in a legible > manner? The following reads pretty well to me: >>> produce_value = lambda value: lambda: value >>> a = [produce_value(index) for index in range(5)] >>> a[3]() 3 Dave From Olivier.POYEN at clf-dexia.com Tue Sep 30 07:28:21 2003 From: Olivier.POYEN at clf-dexia.com (POYEN OP Olivier (DCL)) Date: Tue, 30 Sep 2003 13:28:21 +0200 Subject: [ANN] pylint-0.2 Message-ID: <8963D6370B323E4AA3241200F0EAF73123566F@FCEXVEXM002.dcl.int.dexwired.net> > -----Message d'origine----- > De : Mark Hahn [mailto:mark at hahnca.com] > Envoy? : mardi 30 septembre 2003 06:39 > ? : python-list at python.org > Objet : Re: [ANN] pylint-0.2 > > > They not only feel no need to document, they also feel no > need to follow ANN > threads they start. > Or they might just live in France (as in logilab.FR), have a different time schedule, and being in bed while you're posting that ! Or even not working today ! Or event not daily-reading c.l.p, but just fr.comp.lang.python. As for the documentation, just go to logilab web site, as Peter H said. --OPQ, Long signature following.... -------------- next part -------------- ----------------------------------------------------------------- Ce message est confidentiel ; son contenu ne represente en aucun cas un engagement de la part de Dexia Credit Local ou de Dexia CLF Banque. Toute publication, utilisation ou diffusion, meme partielle, doit etre autorisee prealablement par l'emetteur. Si vous n'etes pas destinataire de ce message, merci d'en avertir immediatement l'expediteur. This message is confidential ; its contents do not constitute a commitment by Dexia Credit Local or Dexia CLF Banque. Any unauthorised disclosure, use or dissemination, either whole or partial, is prohibited. If you are not the intended recipient of the message, please notify the sender immediately. ----------------------------------------------------------------- Consultez notre site internet www.dexia-clf.fr La cle d'une gestion optimisee du secteur public local ----------------------------------------------------------------- From martin at v.loewis.de Sat Sep 20 09:29:26 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 20 Sep 2003 15:29:26 +0200 Subject: Help Compiling 64bit Python References: Message-ID: John Abel writes: > >>c++ -o python \ > >> Modules/python.o \ > >> libpython2.3.a -lresolv -lsocket -lnsl -lrt -ldl > >>-lpthread -lm [...] > I seem to be missing something really obvious here. I've modified the > Makefile so it looks like this: > > CONFIG_ARGS= 'CC=gcc -mcpu=v9 -m64 -D_LARGEFILE64_SOURCE=1' > 'LDFLAGS=-mcpu=v9 -m64' > > ran the make, and it still comes up with the same error. I've even > tried running it with LDFLAGS=-64, with the same result. The really obvious thing you are missing is that "c++" is used to link python, so setting "CC" has no effect. I really encourage you to read the Makefile. Regards, Martin From zefram at wolverine.lohacker.invalid Wed Sep 24 10:37:01 2003 From: zefram at wolverine.lohacker.invalid (Emmanuele Bassi) Date: Wed, 24 Sep 2003 14:37:01 GMT Subject: Pygtk, widget refreshing References: Message-ID: * Arne Schwabe [2003-09-23 22:33]: > But my problem is that this area is not updated while my program is running. > Is there a way I can force pygtk to refresh to widgets? while gtk.events_pending(): gtk.main_iteration() Bye, Emmanuele. -- Emmanuele Bassi | [ http://digilander.libero.it/ebassi/ ] emmanuele.bassi(at)iol.it | Linux User #170621, http://counter.li.org GnuPG Key fingerprint = 4DD0 C90D 4070 F071 5738 08BD 8ECC DB8F A432 0FF4 From mwilson at the-wire.com Fri Sep 5 10:35:02 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 05 Sep 2003 10:35:02 -0400 Subject: Difference of hash and __hash__() References: Message-ID: In article , Michael Chermside wrote: >So submit the bugreport, but I'm guessing that slices will remain >unhashable. IIRC, Guido felt that the risk of confusion (folks >thinking that {}[1:2] would return some part or subset of the dict) >was greater than the utility of using slices as keys in a dict >(for which, I believe, he was unable to come up with a single >plausible use case). Anybody with one might have to settle for a_dict [repr (a_slice)] ... Regards. Mel. From steve at ferg.org Tue Sep 2 09:17:09 2003 From: steve at ferg.org (Stephen Ferg) Date: 2 Sep 2003 06:17:09 -0700 Subject: Win32 documentation in CHM? References: <3f5262ea$0$1667$e4fe514c@dreader3.news.xs4all.nl> Message-ID: > I built a CHM file for Python 2.3 ... Got it! Thanks mucho! From joshway_without_spam at myway.com Wed Sep 10 15:09:51 2003 From: joshway_without_spam at myway.com (JCM) Date: Wed, 10 Sep 2003 19:09:51 +0000 (UTC) Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> Message-ID: JCM wrote: > Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: >> 1. I pointed out that this is an advantage of the C# system, which I >> was proposing to imitate. >> >> : The C# solution uses a modifier keyword, but that keyword must be >> : specified in both the function definition *and* the call. For >> : instance... >> >> ... >> >> : The rationale for this in C#, I assume, is mostly about clarity and >> : maintainability - the caller can't be surprised when value type >> : parameters are changed in a function as he had to explicitly allow it. >> >> >> 2. You quoted the example I labelled as "(roughly) what I'd like to >> be able to do" and ignored the one where I adopted the C# >> approach... > I enitirely missed the second half of your original post. Oops. And given that I wrote the same pseudo-Python as you without seeing it or the C# code tells me I agree with your proposal :) From david.bear at asu.edu Mon Sep 22 21:29:08 2003 From: david.bear at asu.edu (David Bear) Date: 22 Sep 2003 18:29:08 -0700 Subject: parsing windows event files Message-ID: I did a cursory look at google but couldn't seem to find what I wanted. I need a script that can parse and create a proper record structure for windows event logs that are saved as tab delimited format. The event logs they produce seem unnecessarily complicated. Was hoping someone had already made something like this. I'd like to avoid using win32api. From tjreedy at udel.edu Tue Sep 2 13:44:38 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 2 Sep 2003 13:44:38 -0400 Subject: **kwds behavior? References: <924a9f9c.0309020652.212c54eb@posting.google.com> <2S25b.841$I_2.211334@news20.bellglobal.com> Message-ID: <6DqdnYAKS6SbSsmiXTWJhA@comcast.com> "Sean Ross" wrote in message news:2S25b.841$I_2.211334 at news20.bellglobal.com... > better if attempting to write to an non-writable dict raised an exception, > but that is not the current behaviour. The dict returned by locals(), even within a function, *is* writable >>> def f(): ... l = locals() ... l[5] = 6 ... print l ... >>> f() {5: 6} However, it is only a dict copy of the local namespace, (which in CPython happens to not be a dict of any sort). > So, your call to update has no effect > on the local namespace and, thus, 'x' is not yet defined locally. So d=locals() can be used for what it is -- a dict initialized from the local namespace at a particular time, but which is thereafter independent from the local namespace. Terry J. Reedy From __peter__ at web.de Thu Sep 11 18:57:10 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 Sep 2003 00:57:10 +0200 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: Message-ID: Michael Chermside wrote: >>> if copying is costly and only >> sometimes necessary, wrap the item into a copy-on-write proxy for every >> logically distinct but physically identical instance. > > Excellent idea! But, how do I write a copy-on-write proxy in Python? > Seems like this would make an excellent cookbook recipie, but I couldn't > figure out how to do it. Proxying is easy, but how does one distinguish > between mutating and non-mutating methods? Does the proxy need to be > customized for each class to be wrapped? > I have to admit that the generic copy-on-write proxy is still vaporware :-( However, I've come up with a way to make a class its own proxy, with relatively small overhead and no need for advanced stuff like metaclasses (which I have yet to master). class COW(object): def __init__(self, template=None): self._template = template def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: return getattr(self._template, name) def __str__(self): return "--%s---\n" % self._name + "\n".join(["%s = %r" % (n, getattr(self, n)) for n in "a b".split()]) def proxy(self): return COW(self) def printBoth(): print "%s\n\n%s\n---\n" % (o1, o2) o1 = COW() o1.a = "default A" o1.b = "default B" o1._name = "Obj1" o2 = o1.proxy() # same as o2 = COW(o1) o2._name = "Obj2" printBoth() o1.a = "override" # seen in both o1 and o2 printBoth() o2.a = "shade" # hides o1.a printBoth() del o2.a # o1.a visible again printBoth() print o2.nonExistent # misleading error message All methods are identical for proxy and original by design. Attributes are rather shaded than copied, and thus there is no need to copy the whole attribute set if two instances differ only in a single attribute. The overhead in the class definition is not that large: one method plus one attribute. There are some loose ends: - Should mutable attributes be recursively proxied? - How does the above behave in an inheritance tree? - Performance may suffer as the "proxy chain" grows - I've got a hunch that one could come up with an even more general/less intrusive solution using metaclasses Always-speculatingly yours, Peter From jjl at pobox.com Fri Sep 26 13:09:42 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Sep 2003 18:09:42 +0100 Subject: Access to database other web sites References: <87n0crbi8z.fsf@pobox.com> Message-ID: <87brt7xyqx.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: > tibi87 at hanmail.net (Jenny) writes: > > > I am doing research about realationship between sales rates and > > discounted prices or recommendation frequency. To do this, I need to > > access the database of commercial web sites via internet. I think this [...] Forgot to say: if you don't already know, Google Groups can be worth its weight in round tuits. Try some searches there, in comp.lang.python, on the stuff I mentioned. John From johnfabel at btinternet.com Sat Sep 6 04:56:32 2003 From: johnfabel at btinternet.com (John Abel) Date: Sat, 06 Sep 2003 09:56:32 +0100 Subject: Standard Lib To Use New-Style Classes? Message-ID: <3F59A140.30608@btinternet.com> A while back, I saw a thread asking if the standard lib modules would be modified to use the new logging module, and it got me thinking. As the new-style classes will be default for 2.4, will the standard lib modules be modified accordingly? Thanks John From davecook at nowhere.net Wed Sep 3 12:15:20 2003 From: davecook at nowhere.net (David M. Cook) Date: Wed, 03 Sep 2003 16:15:20 GMT Subject: Writing solid code book References: Message-ID: In article , post400 wrote: > there is another famous book 'Writing solid code' but does it apply to > Python ? Or it's usable only by Microsoft C programmers ? The author > seems to be an ex-Microsoft guy ! It mainly deals with C-specific issues. http://tinyurl.com/m3ta However, the Code Complete book by McConnel is quite general. Dave Cook From mwh at python.net Mon Sep 1 07:21:31 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 1 Sep 2003 11:21:31 GMT Subject: method (a, b = '', *c, **d): gets a syntax error? References: <3F4F644D.2060003@uni-bonn.de> <3dqcndZe5u2g4NKiXTWJiA@comcast.com> Message-ID: <7h33cfg4v0r.fsf@pc150.maths.bris.ac.uk> Andreas Neudecker writes: [comma inconsistencies] > Still it puzzles me that in one case it is okay in the other one > not. Seems unlogical to me. Can anyone enlighten me to why this is so? Because that's what the grammar says. The chances of this being deliberate are, I would hazard, pretty tiny. > Thanks to all of you who bothered to point me to my stupid error of > forgetting the 'def' and discussing with me the comma problem. If it's any consolation, it took quite a bit of staring at it before I noticed the flaw... Cheers, mwh -- I located the link but haven't bothered to re-read the article, preferring to post nonsense to usenet before checking my facts. -- Ben Wolfson, comp.lang.python From mwh at python.net Mon Sep 1 08:24:25 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 1 Sep 2003 12:24:25 GMT Subject: Python Documentation? References: Message-ID: <7h3oey43djh.fsf@pc150.maths.bris.ac.uk> "Daniel R. Smorey Jr." writes: > I'm looking for a good place for Python documentation. In addition to what others said, there's Thomas Heller's pyhelp.cgi thingy: http://starship.python.net/crew/theller/pyhelp.cgi and Mark Hammond's Mozilla sidebar: http://starship.python.net/crew/mhammond/mozilla/index.html (which provides an interface to Thomas' script). > I'm really lost on why it's so hard to find anything when it comes > to me looking up a particular function in Python. My example would > be the split() function of the string module. You mean you weren't born knowing what that did? Sheesh, kids these days... . Cheers, mwh -- Never meddle in the affairs of NT. It is slow to boot and quick to crash. -- Stephen Harris -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From eppstein at ics.uci.edu Tue Sep 23 00:00:32 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 22 Sep 2003 21:00:32 -0700 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: In article , "Sean Ross" wrote: > > Some more looping thoughts - this time on integer for loops... > > Hi. > How about the following: > > for i in 0...10: > # suite > > where 0...10 works something like xrange(10). I can't find the message you're replying to, so am responding here only to yours. I personally am uninterested in an integer for-loop syntax that is limited to the unintuitiveness of range and xrange's arguments -- they're great for looping forwards through the indices into a list, not so great for almost anything else. If that's all the loop syntax can do, why not just keep the current "for i in range(10):" syntax? "Explicit is better than implicit." But anyway, PEP 284 has been kind of moribund since Guido dissed it in his Parade of PEPs. I'm not sure what (if anything) it would take to revive it, but convoluted syntax like "for i in 0...10.by(2):" is probably not it. "for i in 0:10:2:" would be more Pythonic, but has a little ambiguity problem ("for i in 0:10:2" without the colon seems like it should execute the statement "2" ten times) and again doesn't add much in readability or power to what we can already do with range. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From piet at cs.uu.nl Wed Sep 10 06:24:30 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 10 Sep 2003 12:24:30 +0200 Subject: Read file that starts with '\xff\xfe' References: <3F5BD4DD.57D90AF5@alcyone.com> <3F5BFC19.D098115B@alcyone.com> Message-ID: >>>>> Bob Gailer (BG) wrote: BG> On Win 2K the Task Scheduler writes a log file that appears to be encoded. BG> The first line is: BG> '\xff\xfe"\x00T\x00a\x00s\x00k\x00 BG> \x00S\x00c\x00h\x00e\x00d\x00u\x00l\x00e\x00r\x00 BG> \x00S\x00e\x00r\x00v\x00i\x00c\x00e\x00"\x00\r\x00\n' BG> My goal is to read this file and process it using Python string BG> processing. BG> I am disappointed in the codecs module documentation. I had hoped to find BG> the answer there, but can't. BG> I presume this is an encoding, and that '\xff\xfe' defines the encoding. BG> How does one map '\xff\xfe' to an "encoding". It's Unicode, actually Little Endian UTF-16, which is the standard encoding on Win2K. The '\xff\xfe' is the Byte Order mark (BOM) which signifies it as Little Endian. >>> import codecs >>> codecs.BOM_UTF16_LE '\xff\xfe' But there is a trailing 0 byte missing (it should have an even number of bytes, as each character occupies two bytes). Of course this comes because you think a line ends with '\n', whereas in UTF-16LE it ends with '\n\x00'. This also means you cannot read them with methods like readline(). >>> st='\xff\xfe"\x00T\x00a\x00s\x00k\x00 \x00S\x00c\x00h\x00e\x00d\x00u\x00l\x00e\x00r\x00 \x00S\x00e\x00r\x00v\x00i\x00c\x00e\x00"\x00\r\x00\n\x00' >>> stu=unicode(st,"utf_16le") >>> stu u'"Task Scheduler Service"\r\n' >>> stu.encode('iso-8859-1') '"Task Scheduler Service"\r\n' -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From indigomoonBLINDERS at bonbon.net Wed Sep 17 10:13:07 2003 From: indigomoonBLINDERS at bonbon.net (Indigo Moon Man) Date: Wed, 17 Sep 2003 08:13:07 -0600 Subject: Python exercises References: <3d19203b.0309162207.153b9922@posting.google.com> Message-ID: Gordon spake thusly: > Hi, > > I was wondering if someone could point me in the direction of some > online exercises to help me learn to program (in Python). > > I'm currently working through Magnus Hetland's Practical Python, which > doesn't have any exercises/problem sets (for the beginning chapters on > things like string manipulation etc). I'd rather not get another book. > I'm a Python beginner and I'm working through 'How to Think Like a Computer Scientist' at http://www.ibiblio.org/obp/thinkCSpy/ and there are exercises given as you go through the text to illustrate points. -- Remove BLINDERS to email me. Audio Bible Online: http://www.audio-bible.com/ From dave at pythonapocrypha.com Wed Sep 24 09:21:44 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 24 Sep 2003 07:21:44 -0600 Subject: Stuck building a Python extension In-Reply-To: References: Message-ID: <200309240721.44277.dave@pythonapocrypha.com> On Thursday 25 September 2003 07:07 am, David Hughes wrote: > I'm nearly there building a Python extension module to access a set of > functions in a .dll, but I'm getting an unresolved external error for one > of the function calls (using MS Visual C++ V6). [snip] Hi David, I apologize that this isn't a direct answer to your question, but have you tried using ctypes? If you're accessing functions in a Windows DLL then with ctypes you can often avoid writing a Python extension altogether. For example, if your DLL was named foo.dll and it had an exported C function int MyFunc(int a, char *b) then calling it could be as simple as: from ctypes import * val = windll.foo.MyFunc(5, 'hello') Much more convenient than writing an extension! :) http://starship.python.net/crew/theller/ctypes/ -Dave From afriere at yahoo.co.uk Tue Sep 30 04:22:05 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 30 Sep 2003 01:22:05 -0700 Subject: Question: Inheritance from a buil-in type References: <3F7848C6.8070306@snafu.de> Message-ID: <38ec68a6.0309300022.3c8e3304@posting.google.com> Duncan Booth wrote in message news:... > > There are two rules. Generally, immutable objects get their initial values > from the constructor (__new__) while mutable objects are constructed with a > default value (e.g. empty list or dict) and are then set by the initialiser > (__init__) method. A few types which you might expect to be immutable are > actually mutable (e.g. property). > What is the thinking behind that? I mean you /can/ pass initial values to a mutable using __new__, eg class MyList (list) : def __new__(cls, *args, **kwargs) : return list.__new__(cls, *args, **kwargs) or __init__ to pass values to a newly created immutable, eg class MyTuple (tuple) : def __init__(self, *args, **kwargs) : return super(tuple, self).__init__(*args, **kwargs) can't you? What's the pitfall? From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Sep 26 10:43:41 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 15:43:41 +0100 Subject: Equivalent of std::set References: Message-ID: On Fri, 26 Sep 2003 10:07:20 -0400, Nicolas Fleury wrote: >Hi, > >I haven't work so much in python and I was wondering what python >programmers use for string collections, like an equivalent of C++ >std::set. Do you use a dictionary with dummy values? Tuple/list? Is >there any other structure in some module with uniqueness ensured and >lookup optimised? I'm only interested in storing strings in that structure. > >Thx for help > >Nicolas A set type was introduced in Python 2.3... http://www.python.org/doc/2.3/whatsnew/whatsnew23.html http://www.python.org/doc/2.3/lib/module-sets.html There are other ways, depending on what you are doing with the strings, though. For instance, although you can iterate a set, the iteration will not necessarily be in order (I assume it uses hashing internally, probably by using a dictionary internally). If you need to access the strings in order (and there aren't too many of them) you can keep the items in a sorted list, in which case the bisect module will probably be a big help. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From mwh at python.net Thu Sep 4 09:41:25 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 4 Sep 2003 13:41:25 GMT Subject: built with --enable-shared but get error: libpython2.3.so.1.0: can't open shared object file References: Message-ID: <7h3vfs84qtt.fsf@pc150.maths.bris.ac.uk> turner at mmedia.is (Douglass Turner) writes: > Please release me from my own private hell. OK, just install the non-shared library build. > Platform: SuSE 8.1 > > I'm installing python 2.3 tarball as follows: > > ./configure --enable-shared > make > make install > > When I simply type: > > % python > > I get: > > python: error while loading shared libraries: libpython2.3.so.1.0: > cannot open shared object file: No such file or directory > > This is really, really, frustrating. The file does in fact live in > /usr/local/lib. Is that in /etc/ld.so.conf? Maybe you should set LD_LIBRARY_RUN_PATH (or whatever it's called). > Interestingly this is outside PYTHONHOME. How do I fix this silly > problem (which the python install process should *never* let happen > in the first place). Unclear what Python can do. If you want to install a shared library somewhere that the system doesn't look for it by default, you have to do something to get it to look there. I guess there's probably some way of putting an absolute path in the executable, but that leads to its own form of entertainment (like, I would imagine, not being able to run the interpreter until you install it). Cheers, mwh -- It could be argued that since Suitespot is infinitely terrible, that anything else, by very definition of being anything else, is infinitely superior. -- ".", alt.sysadmin.recovery From timr at probo.com Mon Sep 1 00:39:24 2003 From: timr at probo.com (Tim Roberts) Date: Sun, 31 Aug 2003 21:39:24 -0700 Subject: Pyhton 2.3 does not work References: <3f504a34$1@news.012.net.il> Message-ID: <48j5lv8hcfj9rfbd9dbn2g5p2gctlpdb1o@4ax.com> "Avner Ben" wrote: > >I need help with Python 2.3 installation in Windows. > >I installed Python 2.3 on both my computers (one running Windows XP and the >other running Windows 98), after first uninstalling Python 2.2.3. In both >computers, Python 2.3. keeps looking for "python22.dll" and would not work. >This happens when running IDLE and when running python.exe and trying to >import anything. > >I removed all mentions of pyhton22.dll from the registry and repaired it >(with Registry Mechanic) - no help. >I looked at PYTHONPATH and it has no mention of python22. > >Obviously, there is something left in my configurations that uninstalling >2.2.3 would not amend. > >The only extensions to Python installed earlier were py2exe and wxPython. I >took care to uninstall them first. Did you download 2.3-compatible versions of py2exe and wxPython? wxPython includes several DLLs. Those DLLs include references to a specific version of Python. If you reinstall the 2.2 version of wxPython, the DLLs will try to load python22.dll. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mack at incise.org Sat Sep 6 10:58:39 2003 From: mack at incise.org (Nick Welch) Date: Sat, 6 Sep 2003 09:58:39 -0500 Subject: in CGI, how to include html pages? In-Reply-To: <20030906110544.78d7ea33.python@sarcastic-horse.com> References: <20030906110544.78d7ea33.python@sarcastic-horse.com> Message-ID: <20030906145839.GL16821@incise.org> On Sat, Sep 06, 2003 at 11:05:44AM -0400, python wrote: > Hi- > > I'm writing some CGI stuff and I'm doing it in python to force myself to > learn the language. Anyway, I want to include some html at the top of > every page but I'm not sure how. > > If the header is in header.html, what is the python-ese way of printing > that out in my html? > > Thanks for the help. > > -- > http://mail.python.org/mailman/listinfo/python-list f = file("header.html") for line in file: print line, f.close() And of course you could easily write a function to wrap this so you could just include("header.html"). HTH, -- Nick Welch aka mackstann | mack @ incise.org | http://incise.org If you have a procedure with 10 parameters, you probably missed some. From vivek at cs.unipune.ernet.in Fri Sep 5 10:22:36 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Fri, 5 Sep 2003 19:52:36 +0530 Subject: Why the 'self' argument? In-Reply-To: ; from gstaniak@inka.zagiel.pl on Fri, Sep 05, 2003 at 01:58:41PM +0000 References: Message-ID: <20030905195236.A12223@cs.unipune.ernet.in> On Fri, Sep 05, 2003 at 01:58:41PM +0000, Grzegorz Staniak wrote: > Hello, > > I'm a newbie Python user, a systems administrator - I've been trying > to switch from Perl to Python for administrative tasks - and one thing > I cannot understand so far is why I need the special 'self' (or anything > esle) argument in class method definitions. I might have missed an > explanation in the docs, a quick Google search did not help. Is there > somewhere on the web you could direct me to? > > Thanks, > > -- > Grzegorz Staniak > -- > http://mail.python.org/mailman/listinfo/python-list The first argument in a class method is a reference to that class itself. It is same as "this" pointer in c++ and java. Using this argument you can access the class variables. ex: class test: def __init__(self,arg1,arg2): #this acts as class constructor self.name=arg1 self.value=arg2 def changeName(self,newName): #here we change the name class variable self.name=newName ..........and so on regards Vivek Kumar From link0937 at hotmail.com Wed Sep 17 21:08:38 2003 From: link0937 at hotmail.com (Link) Date: Thu, 18 Sep 2003 09:08:38 +0800 Subject: About Python's C API Message-ID: Dear sir, I am used to developing C program on MSVC7.0 platform. This is my first time to use Python for calling by C program. Now, it is hard to deal with the problem about extracting the variable which be definied in Python. That how can I do? I have gotten the JPython 's sample that the following code can be looked. Have anyone help me to obtain same results that be called by Python's C API? What do I mean? See attached the following code. // JPython code ======================================= import org.python.util.PythonInterpreter; import org.python.core.*; public class SimpleEmbedded { public static void main(String []args) throws PyException { PythonInterpreter interp = new PythonInterpreter(); System.out.println("Hello, brave new world"); interp.exec("import sys"); interp.exec("print sys"); interp.set("a", new PyInteger(42)); interp.exec("print a"); interp.exec("x = 2+2"); PyObject x = interp.get("x"); System.out.println("x: "+x); System.out.println("Goodbye, cruel world"); } } I would like to re-write those program to Python. // C Language code ============================== void main() { Py_Initialize(); printf("Hello, brave new world"); PyRun_SimpleString("import sys"); PyRun_SimpleString("print sys"); // interp.set("a", new PyInteger(42)); PyRun_SimpleString("print a"); PyRun_SimpleString("x = 2+2"); // PyObject x = interp.get("x"); // System.out.println("x: "+x); Py_Finalize(); printf("Goodbye, cruel world"); } See the above C Language code, After running the statement PyRun_SimpleString("x = 2+2"), the variable x can be definied and be assigned value 4 in Python. Meanwhile, next one, I would like to get the x porinter. Could you help me how can I do? Or show me the other way to reach my purpose. Sincerely yours, Link From falted at openlc.org Mon Sep 1 03:48:10 2003 From: falted at openlc.org (Francesc Alted) Date: Mon, 1 Sep 2003 07:48:10 +0000 (UTC) Subject: Hunting a memory leak References: <7h3oey84qho.fsf@pc150.maths.bris.ac.uk> Message-ID: On 2003-08-30, Edward K. Ream wrote: >> I would appreciate some ideas. > > I doubt many people will be willing to rummage through your app's code to do > your debugging for you. Here are two general ideas: Thanks for the words of encouragement. After the weekend I'm more fresh and try to follow your suggestions (and those of Earl Nightingale ;-). Cheers, Francesc Alted From Mike at DeleteThis.Geary.com Sun Sep 7 01:51:37 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 6 Sep 2003 22:51:37 -0700 Subject: Redesign of Python site References: Message-ID: Martin Maney wrote: > They look very nice if you're just taking in the view: they look like > crap if you want to actually read the content. I've posted a more > detailed complaint there, but in brief "I say it's spinach..." Hey, I *like* spinach. :-) But I'm glad I'm not the only one who is dismayed by the unreadable text in this redesign. I got a chuckle out of your "getting just the right shade of gray" and posted a follow-up with some more contrast measurements: http://www.pollenation.net/journal/index.php?p=37&c=1 -Mike From twic at urchin.earth.li Tue Sep 23 11:52:18 2003 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 23 Sep 2003 16:52:18 +0100 Subject: Need arguments for "Python vs. Perl as an OOPL" In-Reply-To: References: <3F7049D3.14C48D43@engcorp.com> Message-ID: On Tue, 23 Sep 2003, Roy Smith wrote: > Peter Hansen wrote: > > > Roy Smith wrote: > > > > > > I'm working on a prototype of a new application in Python. At some > > > point, if this ever turns into a product, the powers that be will almost > > > certainly demand that it be done in Perl. My job will be to convince > > > them otherwise. > > > > Do you need to convince them now, to allow you to continue working on it > > in Python, or are you just preparing for the time when they will come and > > ask for it to be done in Perl? > > The latter. It's currently a bit of a skunk works project. At some > point, when the time comes to actually allocate resources to this, some > PHB will undoubtedly declare that it has to be done in Perl. At that > point, I'll need to be able to argue coherently why that's a bad idea. why will they want it rewritten? usually, management want to maximise productive output and minimise cost. rewriting it would have a definite positive cost, so either they think the perl version will be superior in some way, or they think it will save costs later on. if you (or we) know what their motives are, you (or we) can get closer to getting them to do what we want. tom -- skills to pay the bills! From __peter__ at web.de Mon Sep 15 11:05:09 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 Sep 2003 17:05:09 +0200 Subject: Loading modules at startup in IDLE References: Message-ID: Daniel Klein wrote: > Does anyone know a way to automatically load modules in IDLE at > startup? > > I can set %PYTHONSTARTUP% but this only works for the interactive > prompt, not in IDLE. I tried doing the same thing with %IDLESTARTUP% > but received no joy. > > What am I missing? Or has this capability been removed on 2.3? Quoth the usage message (idle -h): -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else From fawcett at teksavvy.com Mon Sep 8 01:02:21 2003 From: fawcett at teksavvy.com (Graham Fawcett) Date: Mon, 08 Sep 2003 01:02:21 -0400 Subject: Eureka! (Re: Comments on Python Redesign) In-Reply-To: References: Message-ID: <3F5C0D5D.5090000@teksavvy.com> Y2KYZFR1 wrote: >"Tim Parkin" wrote in message news:... > > [snip] > > >>also >>it's designed to project an image to set Python alongside existing >>enterprise programming langagues (apologies for using the e word) >> >> > >try picking a web site that is useable over the graphical corporate >fluff for the home page. > >then put a big obvious link that says, NON-TECHNICAL PEOPLE THAT WANT >PYTHIN INFORMATION CLICK THIS! or some such thing. > > Here. I think I've solved the problem once and for all. Rather than throw stones, I have created a *brand new design* design for Python.org. I am certain that will satisfy both the technical users and the suit-wearing investigators. It borrows the time-honoured stylings of the old Python site, and blends them with some upscale business moxy. Take a look: http://tinyurl.com/mlcv Sorry, there's no comments page. Please send your opinions to the marketing SIG. P.S. It's not an image! Feel free to check out my kewl HTML coding skills. I used CSS and everything. Yours, -- Graham From edcjones at erols.com Sat Sep 27 17:34:19 2003 From: edcjones at erols.com (Edward C. Jones) Date: Sat, 27 Sep 2003 17:34:19 -0400 Subject: Microbiology and/or image analysis tools In-Reply-To: <45bbfad.0309271119.386ded65@posting.google.com> References: <45bbfad.0309271119.386ded65@posting.google.com> Message-ID: A good place to start is http://www-2.cs.cmu.edu/~cil/vision.html In some fields of science, the data behind a paper is made accessible. In computer vision the data, in this case, software, is usually not available. In most cases, I think the authors don't want to bother making the software good enough for others to use. BW Glitch wrote: > Hello all, > > I've been searching on the web for microbiology and or image analysis > tools in any language (but I would prefer to be in Python ;), but I > haven't found anything useful. Almost every library I've found is > commercial. The only one I've seen open source is OpenEV ( > http://openev.sourceforge.net/ ). > > Is there any library open source available in these areas? > > Thank you very much, > > Andres Rosado From BjornPettersen at fairisaac.com Tue Sep 16 17:48:45 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Tue, 16 Sep 2003 16:48:45 -0500 Subject: scoping with lambda in loops Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624AE7@stpmsg00.corp.fairisaac.com> > From: Ian McMeans [mailto:imcmeans at telus.net] > > I was bitten by a bug today that depended on how lambda works. It took > me quite a while to realize what was going on. > > First, I made multiple lambda functions inside a loop, each of which > depended on the current loop variable. > > >>> a = [] > >>> for index in range(5): > a.append(lambda: index) a.append(lambda index=index: index) > Now, see if you can guess what the output was for each of the > functions in the list a: > >>> a[0](), a[1](), a[2](), a[3](), a[4]() > I had expected it to be (0, 1, 2, 3, 4), but actually, it's: > > (4, 4, 4, 4, 4) > > This really surprised me. I guess what is happening is that each > lambda knows what the context of execution is where it was defined, > and doesn't actually evaluate until the function is called, and when > it does evaluate, it uses the current value of the variable. yes. > Is this related to static scoping? Probably... depending on what you're asking . [...] -- bjorn From hat at se-126.se.wtb.tue.nl Tue Sep 16 09:27:23 2003 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Tue, 16 Sep 2003 13:27:23 +0000 (UTC) Subject: Pipe problem References: <9GH8b.2074$Cu3.689@edtnps84> Message-ID: On Sat, 13 Sep 2003 16:34:13 GMT, Doug wrote: > This works with a small string, but not a large one (read returns an > empty string if i pass a large html file to tidy): > > > >>> iin , iiout = popen2("tidy.exe -asxml") > >>> iin.write(str) > >>> iin.close() > >>> iiout.read() > '' > > I am using windows and tried the standard pipe and win32pipe as well. Probably the standard pipe buffering problem. As you know computer systems have a finite amount of memory, which is used for many things, including buffering data written to a pipe. The write(str) returns when you have written the entire contents out. Since it is big, and tidy.exe also uses finite buffering, the latter starts processing and returning data while you are writing. Since you are not reading incoming data, the pipe in the other direction gets full, tidy.exe becomes blocked, which in turn means your write() becomes blocked. Solution: read and write at the same time. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From jjl at pobox.com Sat Sep 27 16:05:54 2003 From: jjl at pobox.com (John J. Lee) Date: 27 Sep 2003 21:05:54 +0100 Subject: Access to database other web sites References: <87n0crbi8z.fsf@pobox.com> Message-ID: <87eky2574t.fsf@pobox.com> claird at lairds.com (Cameron Laird) writes: > In article <87n0crbi8z.fsf at pobox.com>, John J. Lee wrote: > >tibi87 at hanmail.net (Jenny) writes: [...] > I'm ... reserved about the prospects for the proposed research. The commercial > sites you want to study are, in my experience, some of the most difficult to > "scrape". Which (ATM, anyway) is a good reason for doing it with browser automation. > Complementing that difficulty is the poverty of inference I antici- > pate you'll be able to ground on what you find there; their commerce has a lot > more noise than signal, as I see it. What do you mean 'their commerce has more noise than signal'? > 'Twould be great, though, for you to > uncover something real. Good luck. What I was wondering was where the sales data are going to come from. John From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 00:07:07 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 05:07:07 +0100 Subject: Thoughts on PEP315 References: Message-ID: On Tue, 23 Sep 2003 15:55:06 +1200, Paul Foley wrote: >On Tue, 23 Sep 2003 01:47:03 +0100, Stephen Horne wrote: > >> In terms of flexible loops, Ada is basically the Daddy. > >http://www.lispworks.com/reference/HyperSpec/Body/m_loop.htm Ah - OK - Ada is basically the wannabe Daddy that still lags a long way behind Lisp in terms of flexibility. But it's still way ahead of the imperitive languages I'm most familiar with. Sorry about that. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From tzot at sil-tec.gr Wed Sep 10 17:03:45 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 11 Sep 2003 00:03:45 +0300 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> Message-ID: <6a4vlvkjk3tttac61gg10gbtk8iah5457g@4ax.com> On Wed, 10 Sep 2003 20:19:35 GMT, rumours say that "Dave Benjamin" might have written: >> Perhaps a new Python statement "suck"? > >Oh come on, now, just because Java does it... QOTW +1 :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From newsgroups at jhrothjr.com Sun Sep 28 16:42:21 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 28 Sep 2003 16:42:21 -0400 Subject: overriding built-ins References: Message-ID: "dan" wrote in message news:fbf8d8f2.0309281120.564ec9d5 at posting.google.com... > I really have two related questions. > > 1) Is it possible (without recompiling and changing the core Python > behavior) to write functions that utilize the same syntax as built-in > functions? IE, can I create a function that does this: > > >>>printCaps "hello" #note no parentheses > HELLO There is no special syntax for built-in functions. If you really meant your example the way you wrote it, that's a statement, not a function, in which case the answer is a categorical no. Built-in functions are simply functions that are in a special dictionary that Python searches after not finding the requested function anywhere else. If you want to replace one, feel free. Then don't feel slighted when nobody else wants to deal with your program... [grin.] The Python developers are considering making at least some built-ins immutable and not overridable, though. That is, not changable at run time. The reason is performance - a large number of built-ins are simply calls to magic methods, so there's a performance gain to avoiding the search and extra method invocation required to go through the built-in dictionary for functions like len(). > 2) Is it possible to do this with the built-in keywords themselves, ie > override functions such as print? No. John Roth > > thanks in advance - From joshway_without_spam at myway.com Wed Sep 10 15:05:20 2003 From: joshway_without_spam at myway.com (JCM) Date: Wed, 10 Sep 2003 19:05:20 +0000 (UTC) Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> Message-ID: Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: > 1. I pointed out that this is an advantage of the C# system, which I > was proposing to imitate. > > : The C# solution uses a modifier keyword, but that keyword must be > : specified in both the function definition *and* the call. For > : instance... > > ... > > : The rationale for this in C#, I assume, is mostly about clarity and > : maintainability - the caller can't be surprised when value type > : parameters are changed in a function as he had to explicitly allow it. > > > 2. You quoted the example I labelled as "(roughly) what I'd like to > be able to do" and ignored the one where I adopted the C# > approach... I enitirely missed the second half of your original post. Oops. From avera at coes.org.pe Thu Sep 18 10:52:43 2003 From: avera at coes.org.pe (Alberto Vera) Date: Thu, 18 Sep 2003 09:52:43 -0500 Subject: win32comm Message-ID: <003e01c37df4$84129b50$1603a8c0@pc22> Hello: Could you tell me How I can solve this problem? Regards import win32com.client ImportError: No module named win32com.clieny -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Sep 7 02:32:21 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 7 Sep 2003 02:32:21 -0400 Subject: Redesign of Python site References: Message-ID: "rt lange" wrote in message news:Xns93EEDC144D362whiteywidowyahoocom at 216.77.188.17... > came across this page searching feedster. > dont know whether this is the official resdesign or just a proposal; > but the mockups look very nice. YUCK< YUCK< YUCK. > http://www.pollenation.net/journal/index.php?p=37&c=1 > > main page mockup: > http://www.pollenation.net/assets/public/python-main.html The old site is very readable. Using IE6, I need a magnifying glass to read this page. This is done in the arrogant style of 'we know better than you what type size you should have'. Also known as the 'control the user experience' school. Awful. For me, one of the worse pages I have ever seen. Anti-Pythonic. > interior page: > http://www.pollenation.net/assets/public/python-interior.html Only slightly better. The low contrast gray-on-gray comments page is also barely readable. (Others reported the same.) For my less-than-perfect 50+ year-old eyes, it is physically the WORST comments page I have ever seen. It is a case study in anti-accessibility design. The person responsible should not touch our site. Terry J. Reedy Terry J. Reedy only slightly better. From vivek at cs.unipune.ernet.in Fri Sep 12 09:39:35 2003 From: vivek at cs.unipune.ernet.in (vivek at cs.unipune.ernet.in) Date: Fri, 12 Sep 2003 19:09:35 +0530 Subject: RAD with Python In-Reply-To: <17d520f6.0309120509.491e4d7c@posting.google.com>; from ubaidullahnubar@hotmail.com on Fri, Sep 12, 2003 at 06:09:02AM -0700 References: <17d520f6.0309120509.491e4d7c@posting.google.com> Message-ID: <20030912190935.A6787@cs.unipune.ernet.in> On Fri, Sep 12, 2003 at 06:09:02AM -0700, Ubaidullah Nubar wrote: > Hi, > > How well is Python suited for developing database based applications? U will find python interfaces for almost all mainly used databases. And as the nature of Python it is very easy to interact with databases in Python. > I am new to Python so please bear with me if some of the questions are > too simple. I specifically have the following questions: > > > 2. There seem to be a number of GUI frameworks available? Which one is > good for use on Windows and Linux? If u are new to Python and have no previous experience with C++ then I think Tkinter is the best place to start. If you are comfortable with C++ then u can use wxPython. (Actually there is no seperate documentation for wxPython, it a wrapper around the wxWindows library) > > 3. Can Python apps be compiled to an exe? Can the resulting executable > be distributed commercially? > Yes, using McMillan and py2exe. > 4. What types of applications are not suitable to be written in > Python? > System side softwares > I have good knowledge of many languages including C++, Assembler, > Java, etc. My preferred development tool is Clarion currently. If > anybody with a Clarion background can share their experience with > Python, that will be very helpful. > > Appreciate your answers... > > Thanks & Regards, > Ubaidullah Nubar. > -- > http://mail.python.org/mailman/listinfo/python-list Regards Vivek Kumar From adalke at mindspring.com Thu Sep 25 03:41:31 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 25 Sep 2003 07:41:31 GMT Subject: Pre-PEP: reverse iteration methods References: <4bc2nv07g7hcfd9nm291n3s3aarkifu1a7@4ax.com> Message-ID: Stephen Horne: > I disagree with this. IMO something that modifies a value in place > should be named using a verb (such as reverse, or sort, or update...). You are correct. And I can't even blame it on lack of sleep. ;) Andrew dalke at dalkescientific.com From gillet at scripps.edu Mon Sep 29 18:42:34 2003 From: gillet at scripps.edu (Alexandre Gillet) Date: Mon, 29 Sep 2003 15:42:34 -0700 Subject: build a static python executable on linux? Message-ID: Hi, I am trying to build a python interpreter that is static link. My python interpreter was build on RedHat 8.0 using gcc 2.3 and GLIBC 2.3 When running on other linux flavor that still have GLIBC 2.2, the interpreter won't start. (error message: /lib/libc.so.6: version `GLIBC_2.3' not found (required by /mgl/python/i86Linux2/bin/python2.3) Is there a way to build a static python interpreter using gcc 2.3 that can run on any machine and won't need a shared library at runtime? I want to be able to build my interpreter on my redhat machine and distribute my executable that can then be run on other machine without having to worry about the version of glibc. Thanks for any help or idea in advances. Alex gillet at scripps.edu From __peter__ at web.de Thu Sep 18 13:18:01 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2003 19:18:01 +0200 Subject: file object: seek and close? References: Message-ID: Shu-Hsien Sheu wrote: > Does the seek method would close the file object after using a for loop? > My program looks like this: > > f = open('somefile', 'r') > for lines in f: > some operations > f.seek(0) > > for lines in f: > other operations > > Python gave me an IOErros saying that the file object is already closed. > I am now opening the file again under another file object. > > Am I doing something wrong or it's a bug? The code you posted works here (I substituted "other operations" with "print lines"). Please reduce your actual code to the minimum that still fails and repost together with cut and pasted traceback. Peter From christoph.lehmann at gmx.ch Thu Sep 4 13:25:20 2003 From: christoph.lehmann at gmx.ch (Christoph Lehmann) Date: Thu, 04 Sep 2003 19:25:20 +0200 Subject: newbie question Message-ID: <1062696320.1182.60.camel@christophl> hi I need to read in a textfile, where in each line are two strings: e.g aa 1 bb 0 cc 1 aa 0 dd 0 how can I read in each line and put the first string into one variable, the second into another variable with just one string per line, I did: f = open(myfile, 'r') for filename in f.readlines(): mylist.append(string.rstrip(filename)) #remove \n or \r\n f.close() many thanks -- Christoph Lehmann From max at nospam.com Mon Sep 29 15:21:44 2003 From: max at nospam.com (max) Date: Mon, 29 Sep 2003 19:21:44 GMT Subject: wxImage and Group 4 Tiffs? In-Reply-To: <924a9f9c.0309290721.35301892@posting.google.com> References: <924a9f9c.0309290721.35301892@posting.google.com> Message-ID: Paradox wrote: > I am using wxImage to display Tiffs and it works great except that it > displays a message box for each unrecognized tag in the header. Is > there a way to suppress these message boxes. > > > Thanks Joey this is what libtiff does by default on windows. you can recomplie wx's libtiff module and change the warning handler. From petejereb at yahoo.com Sat Sep 20 22:57:20 2003 From: petejereb at yahoo.com (Pete Jereb) Date: 20 Sep 2003 19:57:20 -0700 Subject: How you chomp in python References: Message-ID: <681f9321.0309201857.25631b6a@posting.google.com> "Fernando Armenta" wrote in message news:... > How you cut off the ^M at the end of a line? rstrip is not working. > > > > string.rstrip(build number) > Do you mean the newline character? If your string variable is named build_number, then build_number = build_number.rstrip('/n') works. Sorry if this isn't what you meant. But the format should be the same. If you did mean ^M then perhaps a hex or octal representation? From balachandra at covansys.co.in Sat Sep 6 15:02:00 2003 From: balachandra at covansys.co.in (Balachandra) Date: Sat, 06 Sep 2003 19:02:00 GMT Subject: Great Book on Web Services References: Message-ID: http://www.amazon.com/exec/obidos/ASIN/1558609008/india From cnetzer at sonic.net Tue Sep 9 16:35:37 2003 From: cnetzer at sonic.net (Chad Netzer) Date: Tue, 09 Sep 2003 13:35:37 -0700 Subject: How to instatiate a class of which the name is only known at runtime? In-Reply-To: <20030909194508.GV16821@incise.org> References: <20030909193530.GA2218@darkstar.localdomain.fake> <20030909194508.GV16821@incise.org> Message-ID: <1063139737.1862.5.camel@adsl-209.204.179.133.sonic.net> On Tue, 2003-09-09 at 12:45, Nick Welch wrote: > > 2. How to write such code to instantiate? > > class = getattr(modulename, classname) > or > class = globals()[classname] "class" is a keyword, and so the above won't work, but the idea is sound. (Just use a different identifier than 'class') > and then: > > an_instance = class() > > Although this all seems really dirty to me. Maybe there are better ways > to do it. The first form, using getattr, is perfectly idiomatic, and that is what I use. Also, regarding the earlier import question, there is the builtin __import__ function: help(__import__) -- Chad Netzer From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Sep 22 20:51:54 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 01:51:54 +0100 Subject: Thoughts on PEP284 Message-ID: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Some more looping thoughts - this time on integer for loops... There may be some hint towards PEP284 (integer for loops) in a review of ideas from other languages, but I'm damned if i can figure it out. I spent some time thinking about it and couldn't find anything that would cover the issue. All I came up with was the recognition that some other languages have 'for' and 'foreach' loops. But Python went down the route of using 'for' for looping over lists/iterators a long time ago. Maybe a new keyword or combination could help, such as... for range i in 0 <= i < 10 : or... for range 0 <= i < 10 : or dropping the PEP284 concept in favor of something C based... for i yield i = 0; i < 10; i += 1 : but I don't much like any of those, to be honest. I did come up with something, though... I doubt the need for exclusive ranges in integer for loops. I also doubt the need for switching between different range systems (inclusive, exclusive, half-open). IMO there is more confusion than anything down those routes. Although I haven't had problems with inclusive loops (Basic, Ada) my preference is toward half-open loops if a choice needs to be made. And it occurs to me that Python programmers do specify integer ranges in a half-open way on a regular basis - when doing slicing on lists and strings. Perhaps the 'int' and 'long' types could support a slicing to generate a list or iterator over the range? If so, we could write... for i in int[0:10] : ... If the syntax creates an iterator rather than a list, it could even be used as follows... for i in long[0:] : ... break if : ... We could have some basic in-step looping with... for i, j in zip(int[0:], int[len(list)-1::-1] : ... break if i > l : ... but this is probably an argument against. What would be good, however, is that it can be useful outside of looping for free - list comprehensions, for instance... [i*i for i in int[0:10]] It would need some slight restrictions compared with normal slicing (it needs to know the value to start at, even if not where to stop) but what the hell. At least I'm not going to be accused of trying to turn Python into another language - AFAIK this slice-of-a-type idea is original. This could be my first time being accused of trying to turn Python into a language that doesn't exist yet, of course ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From p.useldinger at myrealbox.com Fri Sep 12 03:21:58 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Fri, 12 Sep 2003 09:21:58 +0200 Subject: Web server with Python References: Message-ID: On Thu, 11 Sep 2003 17:19:50 -0700, Dave Kuhlman wrote: > >Twisted is more than Web apps, by the way. Does Twisted work well with Python 2.3? -pu From newsgroups at jhrothjr.com Sun Sep 7 13:18:57 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 7 Sep 2003 13:18:57 -0400 Subject: Question on Standard Types References: Message-ID: "hostmaster" wrote in message news:mailman.1062951612.13844.python-list at python.org... > Hi, > > I'm quite new to Python and I am reading this book called 'Core Python > Programming' by Wesley J. Chun. I think that this is not a new book but > I believe some of the points are still valid. > > There is this part in the book where it says: > > "In Python, standard types are not classes, so creating integers and > strings does not involve instantiation". > > But later in the book, it talks about 'numeric objects' created when a > numeric literal is assigned to a reference. > > So my question now is, if standard types are objects, shouldn't they > have classes as well ? Isn't it that a class is the blueprint of an > object? If they don't have a class to begin with, how are these objects > created? He's trying to make a fairly subtle point. At least, it's subtle until you get into the nuts and bolts. The point is that class instances are a single type, regardless of the class. So while it's perfectly true to say what he did, it has very little practical meaning unless you attempt to do an operation on, say, an integer that depends on something that's unique to an instance. John Roth > > Thanks. > > > Al > From tjreedy at udel.edu Mon Sep 15 19:20:00 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Sep 2003 19:20:00 -0400 Subject: No "side effect" assignment! References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> <75b7596ef938ab8af18b663ddd7eaf50@news.teranews.com> <3F6511CD.EF0909CB@alcyone.com> <87smmyndi1.fsf@pobox.com> Message-ID: <6LKcneLGNNG81PuiXTWJgA@comcast.com> "John J. Lee" wrote in message news:87smmyndi1.fsf at pobox.com... > def f(): return raw_input() > > for x in iter(f, ""): > print x Nice -- I keep forgetting about iter() -- except that the wrapper adds nothing that I can see. >>> for l in iter(raw_input, ''): print '*', l, '*' ... aksjf * aksjf * jslfkj * jslfkj * >>> Terry J. Reedy From max at alcyone.com Tue Sep 30 15:01:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 30 Sep 2003 12:01:07 -0700 Subject: I, monster: nethack-like game References: Message-ID: <3F79D2F3.4F4FB1DD@alcyone.com> AK wrote: > Hi, I coded a little game in curses, loosely based on nethack but > where > you command the monsters against the hero (and his dog). You might want to mention this in the rec.games.roguelike.development newsgroup. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ We grow in time to trust the future for our answers. \__/ Ruth Benedict From mark at hahnca.com Wed Sep 17 11:27:43 2003 From: mark at hahnca.com (Mark Hahn) Date: Wed, 17 Sep 2003 08:27:43 -0700 Subject: wanted($): mac and linux python gui coders for porting References: <8dsfmvo15uftg7qvc0oivmsg6eeeqelvtm@4ax.com> <6ee58e07.0309170528.9c81592@posting.google.com> Message-ID: >With his marketing skills Whose skills are you reffering to? "Lothar Scholz" wrote in message news:6ee58e07.0309170528.9c81592 at posting.google.com... > Tim Roberts wrote in message news:<8dsfmvo15uftg7qvc0oivmsg6eeeqelvtm at 4ax.com>... > > > The problem is that 10% of your shareware revenue stream is likely to come > > to approximately $1 per month. > > > > Further, the shareware revenue stream from your Linux port is almost > > certainly going to be $0 per month. Linux users do not pay for software > > tools like this. There's just too much outstanding stuff available for > > free. > > With his marketing skills it will be $0 even for the windows version. > And with a connection that gives me 2Kb/sec on a fast DSL line even > the download will be 0. From a.clarke11 at ntlworld.com Fri Sep 12 10:52:44 2003 From: a.clarke11 at ntlworld.com (Tony Clarke) Date: 12 Sep 2003 07:52:44 -0700 Subject: Computer Programming for Everybody, a Newbie Project References: <8e6e8e5d.0309111939.4f1bf1d7@posting.google.com> Message-ID: <3353cd1e.0309120652.5b195944@posting.google.com> rdsteph at earthlink.net (Ron Stephens) wrote in message news:<8e6e8e5d.0309111939.4f1bf1d7 at posting.google.com>... > As most of you know, the founder and creator of Python has stated an > interest in bringing the joys of computer programming to a wider > audience, and he has coined the phrase "Computer Programming for > Everybody" to sort of sum up this concept. I fit in this category, for > prior to about 3 yrs ago, my programming experience and knowledge was > next-to-none. After 3 yrs of enjoying Python as a hobby in my limited > spare time, I have created a program, which I call askMerlin, that is > simple enough for a newbie to understand, yet interesting and > different. > > Having greatly cleaned up the original code, the basic program is now > a class Decision() that allows one to simply analyze any decision one > needs to make. The other modules are subclasses of Decision() and are > sort of ultra-mini expert systems on how to decide what to eat for > lunch, who to vote for in an election, how to predict who will win a > given basketball game, football game, and how to answer yes or no type > questions. The last two modules apply the same technique but also > utilize the internet to gather data used to analyze and make > decisions. > > I think it is a fun little program. Newbies can not only understand > it, but can add simple modules, in any area of their expertise, by > simply subclassing Decision(), or by simply creating an instance of > Decision and over-riding a few key methods, or perhaps more simply by > imitating the functional logic. > > OK, that's my spiel. The program can be found at my web site at > http://www.awaretek.com/plf.html > > Ron Stephens, humbly-yet-fearlessly-treading-where-he-ought-not-ly-yours > > P.S. of course I am still adding to this program, especially the > internet-enabled part, and welcome ideas / contributions from any and > all, especially relative newbies who need a place to start. > > P.S.S. to Newbies, the best way to understand this program is just to > run it a few times. It is a command line program, and although I have > cleaned up the code, I also removed for the time being the > documentation and comments, that were becoming unwieldy after three > years of fiddling. I think the code speaks for itself, especially > after you run it a few times and see how it works. And yes, I do > intend to add some simple comments back into the code ;-))) > eventually. Also, I apologize in advance for any indentation errors > anyone has after downloading or cutting and pasting the code; just run > the program and let the Python error messages help you sort out any > formatting or indentation errors you may encounter. > > The basic idea is to choose between a few options or alternatives, by > basing your choice on a few good criteria, with each criteria having a > weight, or relative-importance-factor, and then, by various means, > determining a score for each option on each criteria. There, that's > the documentation for now ;-))) > > And lastly, yes, I do realize it isn't much to show for three years of > part time work, but hey, I give me A's for persistence. > > Ron Stephens Excellent Ron, As one long term newbie to another! Worked first time, I downloaded from the page source info, perhaps that helped. Now give us the GUI! Tony Clarke From member40504 at dbforums.com Sat Sep 20 07:59:14 2003 From: member40504 at dbforums.com (nvm1980_in) Date: Sat, 20 Sep 2003 07:59:14 -0400 Subject: Visual Basic Procedure Names Message-ID: <3394230.1064059154@dbforums.com> I am writting an error hander module which should log Calling Subroutine/Function which caused Subroutine or raised an error. I would aso like to store Error Source, Description and Number. can any one help me for this. -- Posted via http://dbforums.com From andrew-pythonlist at puzzling.org Mon Sep 15 21:54:02 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 16 Sep 2003 11:54:02 +1000 Subject: stripping a string In-Reply-To: References: Message-ID: <20030916015402.GC4093@frobozz> Peter Otten wrote: > Tim Williams wrote: > > > > I don't understand. What's wrong with > > > >>>> import re > >>>> s = 'ANL LN32' > >>>> s=re.sub('[0-9]', '', s) > >>>> print s > > ANL LN > > Nothing is *wrong*, but > > >>> import re > >>> s = 'AN21 LN32' [...] > >>> import string > >>> print s.rstrip(string.digits) > AN21 LN > > is *different*. In that case, you could do: >>> import re >>> s = 'AN21 LN32' >>> print re.sub('[0-9]*$', '', s) AN21 LN > translate() gives the same result as re.sub(), but should be much faster > (haven't timed it though). I can never remember off the top of my head how to use maketrans or whatever it's called so that I can use translate (it's not that it's hard, it's simply that I can never remember it without looking it up). Despite their flaws, I find it easier to remember how to write regular expressions. -Andrew. From phil_nospam_schmidt at yahoo.com Fri Sep 5 16:35:52 2003 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 5 Sep 2003 13:35:52 -0700 Subject: I need a little help with Tkinter Entry widget Message-ID: <221e7b06.0309051235.2d5b4868@posting.google.com> I'm trying to make a custom entry widget, as in the code that follows. There are two problems I'm trying to fix: 1) I would like the widget to behave as myEntry.Escape() does now, except that it happens on loss of focus, not when pressing Esc. 2) TABbing between multiple entry fields does undesired things with the selection, and with cursor placement. Can anyone offer any suggestions for how to fix this? I'm attemting to replicate, more or less, the behavior one would get with, for example, MS Excel, in navigating and entering data in an array of entry fields. Also, I'd appreciate any critique of my overall technique, particularly in how I've implemented the "undo" behavior - it works, but doesn't seem particularly clean. Thanks! ------------------------------------------------------ from Tkinter import * class history: """this is a mixin for my custom widgets, providing for "infinite" undo.""" LOG = [] COUNT = {} def log(self): history.LOG.append((self, self.value)) history.COUNT.setdefault(id(self), 0) history.COUNT[id(self)] += 1 def undo(self): try: s, v = history.LOG.pop() if history.COUNT[id(s)]: s.value = v history.COUNT[id(s)] -= 1 if not history.COUNT[id(s)]: del history.COUNT[id(s)] s.Show() except IndexError: pass class myEntry(Entry, history): """ This works pretty well, with one exception: I would like the widget to behave as Escape() does now, except that it happens on loss of focus, not when pressing Esc. Also, TABbing between entry fields causes the text in the next widget to be selected, with the cursor at the end of the text. When keys are pressed, the text is appended to the selected text, rather than replacing the selection as would be expected. """ def __init__(self, master=None, state=NORMAL, **config): Entry.__init__(self, master, **config) if master == None: self.pack() self.insert(INSERT, str(self)) self.bind('', self.Return) self.bind('', self.Escape) self.bind('', self.Key) self.bind('', self.ctrl_z) self.mode = 'display' if state == DISABLED: self.config(state=DISABLED) def Show(self): self.delete(0, END) self.insert(INSERT, str(self)) self.mode = 'display' try: history.COUNT[id(self)] # fails if no history (changes) self.config(bg='pink', fg='black') except: self.config(bg='white', fg='black') def Key(self, event): try: x = ord(event.char) # fails if not an ASCII key if event.keysym == 'Tab': self.Return(None) elif self.mode == 'display': self.config(bg='red', fg='white') self.mode = 'entry' E, I = self.index(END), self.index(INSERT) self.delete(0, END) self.insert(INSERT, self.STR()) i = self.index(END) self.icursor(i - (E - I)) except: pass def Return(self, event): if self.focus_get(): self.Validate(self.get()) self.Show() def Escape(self, event): self.Show() def ctrl_z(self, event): self.undo() def Validate(self, value): pass class gui_int(myEntry): def __init__(self, value=0, master=None, **config): self.value = 0 myEntry.__init__(self, master, **config) def Validate(self, value): try: v = int(value) if v != self.value: self.log() self.value = v except: pass def __str__(self): return 'INT: ' + str(self.value) def STR(self): return str(self.value) x=gui_int(value=22.34, font='Courier 12', state=DISABLED, width=11, justify=RIGHT) y=gui_int(font='Courier 12', width=11, justify=RIGHT) z=gui_int(value=10.99, font='Courier 12', width=11, justify=RIGHT) From fperez528 at yahoo.com Sun Sep 7 15:29:34 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Sun, 07 Sep 2003 13:29:34 -0600 Subject: Comments on Python Redesign References: Message-ID: Aahz wrote: > In article , > Fernando Perez wrote: >> >>And if you feel like people are being overly harsh, don't worry. It's >>usenet after all :) > > Well, no, it's not Usenet, not in the sense you mean. Someone dragged a > discussion from a mailing list here, and I think that beating Tim up in > public is unfair. FWIW, I made a point of NOT beating anyone up, and tried to offer specific, IMHO constructive comments. And since the starting thread of the discussion was a post by Tim himself, that seemed a perfectly fair thing to do. It may have been dragged here from elsewhere, but the first 'Comments ...' post was by Tim, and he's been responding in the discussion actively. As long as the comments were civil (which I actively tried to do, after seeing some of the tone of the discussion elsewhere), I didn't see any problem there. Cheers, f From jblazi at hotmail.com Mon Sep 22 10:21:37 2003 From: jblazi at hotmail.com (jblazi) Date: Mon, 22 Sep 2003 16:21:37 +0200 Subject: Problems with string and lists (searching and replaceing) References: Message-ID: On Mon, 22 Sep 2003 11:30:07 +0200, Ulrich Petri wrote: > Yeah your right, but with your code there is no indication of a right letter > in the wrong position. > I guess one has to use a decorate-undecorate thing... This is what I did in the code snippet I posted in this thread (though I did it in a cumbersome way). JB From bgailer at alum.rpi.edu Tue Sep 23 09:51:48 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 23 Sep 2003 07:51:48 -0600 Subject: command line or idle? In-Reply-To: References: Message-ID: <6.0.0.22.0.20030923075127.00a14520@66.28.54.253> At 07:17 AM 9/23/2003, sjf wrote: >Is it possible to distinguish if script is running on python command line >(python.exe) or IDLE? search archive; several threads on this recently. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From fgeiger at datec.at Tue Sep 30 09:49:01 2003 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 30 Sep 2003 15:49:01 +0200 Subject: [PMW] Rename a notebook's page - how? Message-ID: <3f798986@news.swissonline.ch> Hi again, I'd like to rename a page of a notebook. Deleting the page and adding a new one is not really an option, because the page is filled with other controls already. So I looked into Pmw.Notebook. There are quite a few lists and dicts which were to be changed and I wasn't successful in the first try. However, if nobody has ever done this, I'd have to rebuild the whole page after deleting/adding. I really hope there's an other way to go. Kind regards Franz GEIGER From Scott.Daniels at Acm.Org Thu Sep 11 19:33:38 2003 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 11 Sep 2003 16:33:38 -0700 Subject: list to string In-Reply-To: References: Message-ID: <3f610652$1@nntp0.pdx.net> Graham Nicholls wrote: > Hi. Sorry if this is really dim, but I'm trying to do something like: > > main (args): > fhand=open(args[1:],"r+") > > and get an error that open is expecting a string not a list. > > I _have_ looked at the docs online, and in the books, but to no avail, so > thanks for looking! > > Graham If your program was called with: python myprog.py one two Then sys.argv will be the list: ['myprog.py' 'one' 'two'] and sys.argv[1:] ['one' 'two'] To find out about this kind of thing, instrument your program as follows: main (args): print 'main called with args = %r' % args fhand=open(args[1:],"r+") This should make it obvious what is going on. -Scott David Daniels Scott.Daniels at AcmOrg From john.abel at pa.press.net Sat Sep 20 11:28:54 2003 From: john.abel at pa.press.net (John Abel) Date: Sat, 20 Sep 2003 16:28:54 +0100 Subject: Help Compiling 64bit Python In-Reply-To: References: Message-ID: <3F6C7236.4090404@pa.press.net> Martin v. L?wis wrote: >John Abel writes: > > > >>>>c++ -o python \ >>>> Modules/python.o \ >>>> libpython2.3.a -lresolv -lsocket -lnsl -lrt -ldl >>>>-lpthread -lm >>>> >>>> >[...] > > >>I seem to be missing something really obvious here. I've modified the >>Makefile so it looks like this: >> >>CONFIG_ARGS= 'CC=gcc -mcpu=v9 -m64 -D_LARGEFILE64_SOURCE=1' >>'LDFLAGS=-mcpu=v9 -m64' >> >>ran the make, and it still comes up with the same error. I've even >>tried running it with LDFLAGS=-64, with the same result. >> >> > >The really obvious thing you are missing is that "c++" is used to link >python, so setting "CC" has no effect. > >I really encourage you to read the Makefile. > >Regards, >Martin > > Sorted. I ended up setting the following: export CC="gcc -mcpu=v9 -m64 -D_LARGEFILE64_SOURCE=1" export LDFLAGS='-mcpu=v9 -m64' export LDDFLAGS='-mcpu=v9 -m64 -G' Thanks to Martin for the pointers. Regards John From oren-py-l at hishome.net Mon Sep 29 06:42:05 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Mon, 29 Sep 2003 06:42:05 -0400 Subject: Checking for invalid keyword arguments? In-Reply-To: References: Message-ID: <20030929104205.GA28017@hishome.net> On Sun, Sep 28, 2003 at 05:06:11PM -0400, Roy Smith wrote: > I've got a function that takes a couple of optional keyword arguments. > I want to check to make sure I didn't get passed an argument I didn't > expect. Right now I'm doing: > > conversion = None > drop = False > for key, value in kwArgs.items(): > if key == 'conversion': > conversion = value > elif key == 'drop': > drop = value > else: > raise TypeError ('Unexpected keyword argument %s' % key) > > which seems kind of verbose. Is there a neater way to do this check? Python's built-in default argument mechanism does exactly that: def f(conversion=None, drop=False, ...): ... I assume that you have some good reason for using kwargs instead such as passing a bunch of arguments together as a dict but you can unpack this bunch by calling another function: def f(**kwargs): def f2(conversion=None, drop=False): ... return f2(**kwargs) Oren From steve at ferg.org Thu Sep 25 19:50:49 2003 From: steve at ferg.org (Stephen Ferg) Date: 25 Sep 2003 16:50:49 -0700 Subject: When did Windows start accepting forward slash as a path separator? Message-ID: I have a question that is not directly Python-related. But I thought I'd ask the most erudite group that I know... :-) When did Windows start accepting the forward slash as a path separator character? At one time, it was accepted as a truism that Windows (like MS-DOS) was different from Unix because Windows used the backslash as the path separator character, whereas Unix used the forward slash. But now, among a small group of cognoscenti, it is a truism that this is a myth, and that Windows will allow you to use either the forward or the backward slash as a pathname separator. I hypothesize that originally Windows accepted only the backslash, and then at some time it changed to accept the forward slash as well. Does anyone know when that change occurred? Was it with the introduction of support for long filenames in NT and Win95? From eppstein at ics.uci.edu Tue Sep 23 00:53:15 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 22 Sep 2003 21:53:15 -0700 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: In article , Paul Foley wrote: > > There may be some hint towards PEP284 (integer for loops) in a review > > of ideas from other languages, but I'm damned if i can figure it out. > > I spent some time thinking about it and couldn't find anything that > > would cover the issue. > > > All I came up with was the recognition that some other languages have > > 'for' and 'foreach' loops. But Python went down the route of using > > 'for' for looping over lists/iterators a long time ago. Maybe a new > > keyword or combination could help, such as... > > > for range i in 0 <= i < 10 : The idea behind the specific syntax of PEP284 was simply the following observation: one way of reading "for i in iterator" is that it loops over the values for which the expression "i in iterator" is true. What types of expressions other than the "in" operator could be substituted in the same context and do something useful? -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From aleax at aleax.it Mon Sep 22 10:25:11 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 14:25:11 GMT Subject: using poplib to retrieve messages sent from a certain address References: Message-ID: Rybread wrote: > Real quick, I have account X and I want a python script that goes in > and looks for emails sent from Y and then to save them. i'm trying to > go off the swen killer I have listed below (which i took from someone > on this NG): I was the "someone", and to retrieve the headers (and the first little bit of a message) you could use 'top' method of Pop3 objects. However, the docs warn you: """ top(which, howmuch) Retrieves the message header plus howmuch lines of the message after the header of message number which. Result is in form (response, ['line', ...], octets). The POP3 TOP command this method uses, unlike the RETR command, doesn't set the message's seen flag; unfortunately, TOP is poorly specified in the RFCs and is frequently broken in off-brand servers. Test this method by hand against the POP3 servers you will use before trusting it. """ So, you'd be using that at your own risk. If you KNOW it works well with your server, then, basically: > for sms in messages[1]: > sid, ssize = sms.split() > if minsize <= int(ssize) < maxsize: resp, lines, octets = ps.top(sid, 1) if "From: foo at bar.com" in lines: > message = ps.retr(sid) > print 'retrieving and deleting msg#%s, %d bytes, %d lines' % ( > sid, message[-1], len(message[1])) > logfile.write(fromtag % time.asctime()) > for line in message[1]: > logfile.write(line) > logfile.write("\n") > logfile.write('\n') > ps.dele(sid) > > ps.quit() > > print 'Done at', time.asctime() > print or thereabouts (untested). You'll probably want to comment-out the call to ps.dele until you're very secure that it all works...;-). BTW, for generic tests of POP I find Garshol's popserve.py quite useful, see http://www.garshol.priv.no/download/software/python/popserve.py . I think that, as coded, it doesn't support the TOP command (which you need above), but it does mention a "more full-featured descendant" that, for all I know, might. Alex From domma at procoders.net Wed Sep 17 06:06:26 2003 From: domma at procoders.net (Achim Domma) Date: Wed, 17 Sep 2003 12:06:26 +0200 Subject: htmllib.HTMLParser and unicode Message-ID: Hi, should the HTMLParser be able to handle unicode input? I get the following traceback: self.feed(self.data) File "C:\Python23\lib\sgmllib.py", line 94, in feed self.goahead(0) File "C:\Python23\lib\sgmllib.py", line 183, in goahead self.handle_entityref(name) File "C:\Python23\lib\sgmllib.py", line 390, in handle_entityref self.handle_data(table[name]) File "C:\Python23\lib\htmllib.py", line 49, in handle_data self.savedata = self.savedata + data UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) The input is a html page from the web, encoded as utf8. I converted the string via data.decode('utf8'). The result is passed to the feed function. regards, Achim From emile at fenx.com Sun Sep 7 18:56:39 2003 From: emile at fenx.com (Emile van Sebille) Date: Sun, 7 Sep 2003 15:56:39 -0700 Subject: CSV Module questions. References: Message-ID: John D. asks: [snip question and most of questionable example] > someiterable = {'john d': 'john d', 'fred': 'fred'} > # make the writer. > writer = csv.writer(file("some.csv", "w")) > for row in someiterable: > writer.writerow(row) [snip] > Here is what I want... > > "john d", "john d" > "fred", "fred" > > How to I write to a file in this way? Is is possible? > I expect you'll get further passing a list, as passing a dictionary also requires setting up field names. So instead try one of: import csv someiterable = [['john d', 'john d'], ['fred', 'fred']] writer = csv.writer(file("somelist.csv", "wb")) writer.writerows(someiterable) #--- or --- someiterable = [{'name': 'john d', 'addr':"123 Main"}, {'name': 'fred', 'addr':"456 Spruce"}] writer = csv.DictWriter(file("somedict.csv", "wb"), fieldnames =['name', 'addr']) writer.writerows(someiterable) HTH Emile van Sebille emile at fenx.com From ark at acm.org Tue Sep 16 18:13:08 2003 From: ark at acm.org (Andrew Koenig) Date: Tue, 16 Sep 2003 22:13:08 GMT Subject: scoping with lambda in loops References: <7f9e1817.0309161338.20fbdcbc@posting.google.com> Message-ID: Ian> First, I made multiple lambda functions inside a loop, each of which Ian> depended on the current loop variable. >>>> a = [] >>>> for index in range(5): >>>> a.append(lambda: index) Ian> Now, see if you can guess what the output was for each of the Ian> functions in the list a: >>>> a[0](), a[1](), a[2](), a[3](), a[4]() Ian> I had expected it to be (0, 1, 2, 3, 4), but actually, it's: Ian> (4, 4, 4, 4, 4) Ian> This really surprised me. Suppose you did it this way: a = [] for index in range(5): def foo(): return index a.append(foo) What result would you expect now, and why? -- Andrew Koenig, ark at acm.org From tjreedy at udel.edu Tue Sep 2 09:57:22 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 2 Sep 2003 09:57:22 -0400 Subject: Which is the better way to parse this file? References: <10c662fe.0309020436.559d513d@posting.google.com> Message-ID: "Roberto A. F. De Almeida" wrote in message news:10c662fe.0309020436.559d513d at posting.google.com... > I'm interested in parsing a file containing this "structure": > > """dataset { > int catalog_number; > sequence { > string experimenter; > int32 time; > structure { > float64 latitude; > float64 longitude; > } location; > sequence { > float depth; > float temperature; > } xbt; > } casts; > } data;""" I suspect that what you actually want to do is parse structures 'like' the above, as defined be a grammar not shown ;-) You did not specify whether you will get such files from an uncontrolable external source or whether you control the input format. If the later, there is no obvious reason for separate database, sequence, and structure productions since all three result in dictionaries with no functional difference. > I want to obtain a dictionary like this: > > >>> pprint.pprint(data) > {'casts': {'experimenter': None, > 'location': {'latitude': None, 'longitude': None}, > 'time': None, > 'xbt': {'depth': None, 'temperature': None}}, > 'catalog_number': None} > The values ('None') will be filled later. Using None as placeholders either tosses the type information or requires that it be recorded elsewhere. Use the int and float type objects instead. Note that standard Python cannot differentiate between float and float64. > I tried to do the parsing > using regular expressions, but things became too complicated. REs are great for linear repetition but not for indefinite nesting. > I had > more success using SimpleParse, but I'm interested in more insights on > different ways of parsing this file. I know nothing of SimpleParse (and therefore, of what would be different). If the grammar is as simple as I infer from the sample -- dataset and sequences containing sequences, structures, and types -- I would reread about recursive-descent parsing and maybe try that. The type_entry function would return a (name, typeobject) pair and the structure, sequence, and database functions a (name, dict) pair. But as hinted above, I would think about simplifying the grammar before worryinng about parsing. If you only have sequences of sequences and type entries, parsing is trivial. Terry J. Reedy From tcronj at ananzi.co.za Tue Sep 30 04:36:48 2003 From: tcronj at ananzi.co.za (Tertius) Date: Tue, 30 Sep 2003 10:36:48 +0200 Subject: append special chars with "\" In-Reply-To: References: <3f793544$0$64721@hades.is.co.za> Message-ID: <3f794cfe$0$64728@hades.is.co.za> Alex Martelli wrote: > tertius wrote: > > >>Is there a better way to append certain chars in a string with a >>backslash that the example below? >> >>chr = "#$%^&_{}" # special chars to look out for >>str = "123 45^ & 00 0_" # string to convert >>n = "" # init new string >>for i in str: >> if i in chr: # if special character in str >> n+='\\' # append it with a backslash >> n+=i >>print "old:",str >>print "new:",n > > > If you can afford some a priori preparation, make a dictionary > once and for all that maps each character (that isn't to be > represented by itself) to the string that represents it. E.g., > if you inevitably start with a chr string as above, you can > make the dictionary as follows: > > charmap = {} > for c in chr: charmap[c] = c+'\\' > > You can also write out the dict literal directly, and in > any case you only need to prepare this charmap once and > can then use it to prepare any number of translations. > > Once you have this charmap, you can use its get method to > get the translations -- and prepare a *LIST OF STRINGS* to > be joined up at the end, that's MUCH, *MUCH* faster than > a loop using += on a string: > > pieces = [charmap.get(c,c) for c in str] > > and finally: > > n = ''.join(pieces) > > > Alex > *MUCH* nicer :) Thanks! From nospam at nospam.com Mon Sep 29 16:04:43 2003 From: nospam at nospam.com (AK) Date: Mon, 29 Sep 2003 20:04:43 GMT Subject: append log file References: Message-ID: In article , Tom wrote: > Hi, > I have a log file and of course I want to add the new information to the > end of that log file. Unfortunately I always delete the old information > and only append the current info. > > Right now I do it like this: > I call a module which consists of a class and a function. It actually > doesn't matter, but I just included it for the sake of completeness. > The module looks like this: > > class log_C: > def errorlog(self, filename, Data, d): > LogFile = file(filename, 'w') Why not ... open(filename ... ? Then 'a' should work. (or at least works here). > ErrorInfo = Data[d+1] > LogFile.write(ErrorInfo) > LogFile.close() > > How can I add the new info without deleting the old info? > I tried the modes 'a' and 'a+' but they both didn't work. Actually the > data was totally unreadable! It was kind of messed up. :-( I don't know why. > > Thanks for your help. > Regards, Tom > From bokr at oz.net Sat Sep 6 14:24:31 2003 From: bokr at oz.net (Bengt Richter) Date: 6 Sep 2003 18:24:31 GMT Subject: OT: Americans love their guns References: Message-ID: On Sat, 06 Sep 2003 07:43:06 -0000, Steve Lamb wrote: >On 2003-08-28, Lulu of the Lotus-Eaters wrote: >> As for homicide, well, you're far more likely to be either a victim or a >> killer. If you are armed, it is quite possible that an angry loved one >> would have access to that gun.... and no doubt regret shooting you after >> his/her anger cooled. And should you be mugged on the street by a >> stranger, your chance of walking away dead (rather than just with less >> money), are MANY times higher if you pull a gun on your assailant. > > If guns were such a overriding factor why is it the UK has as high >if not higher rate of gun related violence than the US? For that matter I am highly skeptical of this, and wonder where you got your "info." ;-) >why is it in several other European nations (Netherlands and Switzerland >IIRC) where there is a legal requirement for all males over a certain >age to be armed (standing militia) that there is so little gun related >violence? > > When are people going to learn, it ain't the guns, its the education >and attitude surrounding them. It isn't guns that are the problem, it's >ignorance of guns thats the problem. Well, when someone "loses it" and ignorantly mistakes you for the devil, what would you rather see in their hand, a cocked "45" or a banana? If your best friend "loses it" in a spiral of despondency over a mistaken (or not) diagnosis of some kind, what would you rather know is in the drawer of their nightstand, a loaded "45" or a book? You seem to be hoping that education and attitude (which you don't mention a way of improving, enforcing, or QA-ing) will prevent all the temporary quasi-insanities that normally reasonable humans are capable of. (Sheesh, look at the violence-trolling in the middle east. Not everyone is equally capable of self-restraint, nor does culture/education/experience equally promote it. (They seem to be having a "losing it" chain reaction meltdown over there, exacerbated by antagonist leaders who have apparently "lost it" w.r.t. each other).) IMO the problem should be approached in terms of risk management, and risks are not either/or. There are risks in owning and operating cars. The risks vary according to operator and location etc. We require licensing and insurance -- which does not control all outcomes, but does modify probabilities of owner ship and behavior, and does mitigate some effects on surviving kin (and financial institutions holding car loans). There are risks in owning and operating firearms. The risks vary according to operator and location etc. We don't require licensing and insurance -- which would not control all outcomes, but which would modify probabilities of owner ship and behavior, and would mitigate some effects on surviving kin (and financial institutions holding car loans etc for the deceased). Wonder why the difference. It says, "must wear corrective lenses" on many drivers' licenses. Should not something similar apply to shooting within range of at least any other human (and is knowing that range less important than knowing how far high beams carry? Why not test knowledge of both for respective licensings?) OTOH, my grandfather was a deadeye shot, and there's a bunch of silver stuff somewhere to prove it ;-) Regards, Bengt Richter From bgailer at alum.rpi.edu Fri Sep 19 18:27:36 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 19 Sep 2003 16:27:36 -0600 Subject: Python API In-Reply-To: References: Message-ID: <6.0.0.22.0.20030919162532.03993be8@66.28.54.253> At 04:10 PM 9/19/2003, RR wrote: >Hello, where is nice site that would have python API documentation? >In particular I am trying to find documentation on the function >string.find http://www.python.org/doc/current/lib/module-string.html This is part of the string module. Be aware that for most string operations you no longer need this module; you can use the find method of a string e.g haystack.find('needle') (assuming haystack is a variable bound to a string.) Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From skip at pobox.com Fri Sep 19 15:19:22 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Sep 2003 14:19:22 -0500 Subject: \r for newline in readlines function In-Reply-To: References: Message-ID: <16235.22202.510046.740814@montanaro.dyndns.org> (warning - this note contains more than you bargained for...) Mark> Hi Skip : Thanks for replying. I can't find the function file Mark> anywhere And the error I get when I type in your statement Is Mark> 'str' object is not callable. Do You know where I can find info on Mark> the file Function ? Thanks. "file" is the newly proclaimed replacement for "open". If the version of Python you're running doesn't have a file builtin, it probably won't have universal newline support either. Try this instead: f = open("somefile.txt", "rU") and be prepared for it to barf. If it does, you can either upgrade to Python 2.3 or read the file in one fell swoop and split on "\r" as someone else recommended: f = open("somefile.txt", "rb") rawdata = f.read() lines = rawdata.split("\r") If you have a very old version of Python you may not even have string methods, in which case you will have to change the last line to: import string lines = string.split(rawdata, "\r") Note that the last line, if terminated by "\r" will leave you with an empty string at the end: >>> import string >>> s = "123\r456\r789\r" >>> string.split(s, "\r") ['123', '456', '789', ''] You can work around that a couple different ways. First, you can strip any trailing "\r" characters from the file prior to splitting: >>> string.split(string.rstrip(s, "\r"), "\r") ['123', '456', '789'] That's probably not acceptable if the file ends with several blank lines. Alternatively, you can test explicitly for an empty string at the end of the list: >>> if lst[-1:] == [""]: ... lst = lst[:-1] ... >>> lst ['123', '456', '789'] Note also that none of these solutions works exactly like the file object's readlines() function, since they strip the end-of-line sequence instead of replacing it with a newline. Here's a quickie comparison from my system which considers the first five lines of my /etc/hosts file. First, opening the file in universal newline mode and using readlines: >>> hosts = file("/etc/hosts", "rU") >>> hosts.readlines()[:5] ['##\n', '# Host Database\n', '# \n', '# Note that this file is consulted when the system is running in single-user\n', '# mode. At other times this information is handled by lookupd. By default,\n'] Now, reading the whole file and splitting it: >>> hosts = file("/etc/hosts", "rb") >>> hosts.read().split("\n")[:5] ['##', '# Host Database', '# ', '# Note that this file is consulted when the system is running in single-user', '# mode. At other times this information is handled by lookupd. By default,'] If you really want to be anal and split on the "\r" characters, mapping them to newlines, here's a little function: >>> import string >>> def readlines(f, spliton="\r"): ... data = f.read() ... lines = string.split(data, spliton) ... for i in range(len(lines)): ... lines[i] = lines[i] + "\n" ... return lines ... >>> # /User/skip/tmp/hosts is /etc/hosts with \r line endings >>> f = open("/Users/skip/tmp/hosts", "rb") >>> readlines(f)[:5] ['##\n', '# Host Database\n', '# \n', '# Note that this file is consulted when the system is running in single-user\n', '# mode. At other times this information is handled by lookupd. By default,\n'] I tried to be as conservative as possible in the constructs I used so that you wouldn't have to tweak the readlines() function to run on older versions of Python. Hence the lack of string methods or list comprehensions. Skip From NO-MAIL at hotmail.com Tue Sep 16 19:07:12 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 23:07:12 GMT Subject: why pass statement? References: <3377992.1063747732@dbforums.com> Message-ID: "Andrei" wrote in message news:3377992.1063747732 at dbforums.com... > I find "pass" shows that something could be there, sort of "insert stuff > here if you like/need to". A string as such doesn't have that effect. > Obviously you could always make up some useless statement instead of > pass, but pass just looks more elegant IMO. You probably should use it > if you plan on showing your code to others. I know, I do :-) It's too late to make a revolution. > -- > Contact info (decode with rot13): cebwrpg5 at bcrenznvy.pbz > Fcnzserr! Cyrnfr qb abg hfr va choyvp zrffntrf. V ernq gur yvfg, ab arrq gb PP. > > > Posted via http://dbforums.com From max at nospam.com Fri Sep 26 16:30:35 2003 From: max at nospam.com (max) Date: Fri, 26 Sep 2003 20:30:35 GMT Subject: py2exe In-Reply-To: References: Message-ID: Thomas Heller wrote: > There's a new py2exe version in the works, it is in the CVS sandbox > subdirectory. If you want it, I can mail you a binary for testing. me 2, please! max at cvisiontech.com > Thomas once we are on the topic, has there been any movement to do a monolith option for py2exe (e.g. there is only one exe, no dlls necessary). this is somewhat useful because the exe can be freely moved around without worrying about the dlls. thanks! max From tjland at iserv.net Mon Sep 1 15:46:41 2003 From: tjland at iserv.net (tjland at iserv.net) Date: Mon, 1 Sep 2003 15:46:41 -0400 (EDT) Subject: TKinter is driving me crazy! Message-ID: <3285.208.224.10.29.1062445601.squirrel@webmail.iserv.net> Okay now im pretty sure this is really easy and pretty stupid but i need to create this. To make it simple ill use another program as an example. A guessing game that has an input field and button and an output field that can display w/e. I know this is really easy in c++ but it needs ot be done in python. Can anyone start me off here or give me a skeleton structure on this is supposed to be arranged. Thanx in advance. When you see the net take the shot When you miss your shot shoot again When you make your shot you win! Just remember Offense sells tickets But defense wins championships! From hungjunglu at yahoo.com Fri Sep 19 03:28:49 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 19 Sep 2003 00:28:49 -0700 Subject: How to pass parameter to a module? References: Message-ID: <8ef9bea6.0309182328.5c040595@posting.google.com> "M-a-S" wrote in message news:... > I'd like to parametrize a module. That is, to set and pass > some values into the module, while it is being imported. There are many ways. (However, classes may fit your need better. "Passing parameters to a module" is not a common practice, as far as I know.) (1) Use a built-in namespace variable. import __builtin__ __builtin__.myvar = 3 print myvar This is a hack. I have been screamed at for mentioning it. :) (2) Hack your favorite (non-builtin) module. The module could be any of the standard library modules, or your own third module. import sys sys.myvar = 3 (3) Use environmental variables. import os os.environ['myvar'] = 'hello' You get the idea. Python has three namespaces: built-in, global, and local. Since global and local namespaces won't go over to the other module, you need to rely on the built-in namespace, one way or another. How you want to structure your data (by using the built-in namespace, a module, a class, a dictionary or any other entities that can hold a name entry), it's entirely up to you. Hung Jung From max at alcyone.com Fri Sep 19 16:03:52 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 19 Sep 2003 13:03:52 -0700 Subject: How do I learn operator overriding? References: Message-ID: <3F6B6128.49680D2@alcyone.com> John Roth wrote: > A new mass mailer worm hit the net at about 9:00 PM EST last night > (at least, that's when I started getting the spam from it.) It seems > to be > using a really old hole in Windows, meaning that if you've kept up to > date > with your patches, you should be safe from infection. Being completely safe from infection doesn't mean that you won't get hammered by the spam the worms generate. All you need to be is in the address book of someone whose machine was compromised. (My machines don't run Windows, so they certainly haven't bee compromised by a Windows worm, but I'm seeing tremendous spam loads nevertheless.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You and I / We've seen it all / Chasing our hearts' desire \__/ The Russian and Florence, _Chess_ From skip at pobox.com Fri Sep 19 16:23:58 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 19 Sep 2003 15:23:58 -0500 Subject: mutex? protecting global data/critical section In-Reply-To: <3F6B5491.9020907@sympatico.ca> References: <3F6B5491.9020907@sympatico.ca> Message-ID: <16235.26078.764664.277055@montanaro.dyndns.org> Brian> I am trying to protect some global data, which may, in the Brian> future, be accessed by threads. I'm not sure how to implement a Brian> locking mechanism in python. There's generally no need to roll your own locking. Start simple (Queue module) and get more sophisticated (threading module's Lock, RLock, Semaphore, Condition or Event classes). Almost all the time, a Queue object will do the trick: class resourceManager(object): def __init__(self): self.__queue = Queue.Queue() for i in range(100) self.__queue.put(None) def getResource(self): self.__queue.get() do my thing self.__queue.put(None) In the above case, you're not actually sharing anything, just using self.__queue to limit the number of simultaneous threads. More likely, you will either have a certain number of objects which are limited by the performance of your system (say, database connections) or some piece of global state which you need to control access to (e.g., some kind of blackboard object). Either one might look something like this: class resourceManager(object): def __init__(self, list_of_stuff): self.__queue = Queue.Queue() for item in list_of_stuff self.__queue.put(item) def apply(self, func): item = self.__queue.get() result = func(item) self.__queue.put(item) return result manager = resourceManager([blackboard]) ... manager.apply(write_on_blackboard) dbmanager = resourceManager([conn1, conn2, conn3]) ... dbmanager.apply(execute_sql) Of course, you will probably want a bit more general apply() method so you can pass other arguments to the function. Skip From jjl at pobox.com Mon Sep 22 13:29:23 2003 From: jjl at pobox.com (John J. Lee) Date: 22 Sep 2003 18:29:23 +0100 Subject: urls on securing python on a shared hosting ? References: <3f6c2f8a$0$20641$626a54ce@news.free.fr> Message-ID: <87n0cw91fw.fsf@pobox.com> Bruno Desthuilliers writes: > Could someone point me to infos about securing python for use as CGI > or mod_python for a shared hosting environnement ? > > I searched google, but did not find anything specific :( > > I'm not an admin myself, but I try to convince my hosting admins to > install Python. For now, their answser is that they don't know how to > secure this, and have not time to learn how to do it. (NB : this is a > 'cooperative' hosting service, not a commercial one...) I can't think of any security issues resulting from use of Python CGI scripts that aren't also present when using any other language for that purpose. Perl does have taint checking, which is a useful technique, but not really of interest from the point of view of the *administrators* of a system. Dunno about mod_python, though. John From chasm at rift.sytes.net Sun Sep 21 11:18:54 2003 From: chasm at rift.sytes.net (Julian Tibble) Date: Sun, 21 Sep 2003 15:18:54 +0000 (UTC) Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> Message-ID: In article , M-a-S wrote: > def factorial_iter(n): > s = 1 > for i in range(2,n+1): > s *= i > return s > Calculations of 950!, 1000 times each (xrange(1000)) -- > > recursion ..... 8.01 > reduction ..... 4.20 > iteration ..... 3.79 Be even faster if you used xrange for the factorial function. However, apparently reduce builds the list, thereby not benefitting from the use of xrange: recursion - 4.7 xrecursion - 0.5 reduction - 5.2 xreduction - 5.2 Can reduce be "fixed"? Julian (code I used:) def recursion(n): s = 1 for i in range(2, n+1): s *= i return s def xrecursion(n): s = 1 for i in xrange(2, n+1): s *= 1 return s def reduction(n): return reduce(long.__mul__, range(2, n+1), 1L) def xreduction(n): return reduce(long.__mul__, xrange(2, n+1), 1L) methods = [ recursion, xrecursion, reduction, xreduction] import time for method in methods: a = time.time() for i in xrange(1000): method(950) b = time.time() print "%s - %.1f" % (method.__name__, b - a) From toby at rcsreg.com Sun Sep 14 17:54:11 2003 From: toby at rcsreg.com (Tobiah) Date: Sun, 14 Sep 2003 21:54:11 GMT Subject: Huh?!?!? What is it that I'm seeing here? In-Reply-To: References: Message-ID: > performing properly (albeit somewhat inefficiently, since I haven't done > any tweaking yet) but one particular construct has me stumped. It looks > like this: > > if __name__ == '__main__': > run(argv[1:]) > This is used to check whether the script file is being run directly as a python script (as opposed to being imported as a module). One use of this is to put unit tests in each module filed. Then you can just do "python module.py" to run the code under the if statement. When you import the module, the test code will not be run. Tobiah From tjreedy at udel.edu Tue Sep 2 15:52:35 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 2 Sep 2003 15:52:35 -0400 Subject: **kwds behavior? References: <924a9f9c.0309020652.212c54eb@posting.google.com> Message-ID: <12OdnS7OZemZaMmiXTWJig@comcast.com> "Hans Nowak" wrote in message news:mailman.1062522376.29013.python-list at python.org... > Now, on to the yucky solution: > > >>> def g(**kwargs): > for key, value in kwargs.items(): > exec "%s = %s" % (key, repr(value)) > # test test... This is cute but limited. It only works when values == eval(repr(value)), which is to say, numbers, strings, and, recursively, tuples, lists, and dicts and some user-class instances. Others will raise syntax error. Terry J. Reedy From llothar at web.de Wed Sep 17 19:58:14 2003 From: llothar at web.de (Lothar Scholz) Date: 17 Sep 2003 16:58:14 -0700 Subject: Simple python cgi question References: Message-ID: <6ee58e07.0309171558.79b8748d@posting.google.com> Stephen Boulet wrote in message news:... > First of all, I'm not sure that the easiest way to do this is with > python ... > > I'd like to set up a web page that would accept a text file, process it > with a local program, and then make available generated pdf and > postscript files for downloading. > > I'd like to limit the size of the file to be uploaded. > > I have apache2 already up. Is this a job for (mod_)python? > > -- Stephen File upload size restriction is a job for apache. If you try to do this in a CGI handler its to late to protect against "Denial Of Service" attacks. With modpython you can check the content-length header and abort before you process the data. From bokr at oz.net Sat Sep 20 17:30:37 2003 From: bokr at oz.net (Bengt Richter) Date: 20 Sep 2003 21:30:37 GMT Subject: Problems with string and lists (searching and replaceing) References: Message-ID: On Sat, 20 Sep 2003 21:08:40 +0200, "jblazi" wrote: >"Anton Vredegoor" schrieb im Newsbeitrag >news:bkhnpn$hgc$1 at news.hccnet.nl... >> >Do I oversee something? >> >> Yes, UserString. The documentation is a bit sparse, but reading the >> module itself provides additional information. Below is a quick test >> script. >> >> from UserString import MutableString >> >> def test(): >> s = MutableString("helo world") >> print s >> x = 'helo' >> y = 'hello' >> i = s.find(x) >> s[i:i+len(x)] = y >> print s >> >> if __name__=='__main__': >> test() >> >> #output: >> #helo world >> #hello world > >Thx. >It would be quite diffcult to explain this akward procedure to beginners. >especially when they see that this can be done so simply in C. >It seems that I have stumbled upon one of the few cases when Python is >cumbersome and difficult to use. > For the above, what is wrong with >>> def test(): ... s = 'helo world' ... print s ... s = s.replace('helo','hello',1) ... print s ... >>> test() helo world hello world ? Regards, Bengt Richter From usenet_spam at janc.invalid Tue Sep 16 20:12:53 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 17 Sep 2003 00:12:53 GMT Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <17d520f6.0309130704.7944c876@posting.google.com> <877k4bk0i0.fsf@pobox.com> <6ee58e07.0309160009.1b6c9057@posting.google.com> Message-ID: llothar at web.de (Lothar Scholz) schreef: > JanC wrote in message news:... > >> According to their website they use native Windows API, but when I tried >> some Qt-programs I've seen those subtle differences with normal Windows- >> applications, which is very annoying at times. When something looks > > Thats what they say: native Windows API, not native Widgets. > > Maybe you should finetune your text reading precision level. If you read both of my messages you can see that I doubted they were using the Windows GUI (which is part of the Windows APIs), even if I didn't say that explicitly (that happens at 4:11am ;) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From posman at eval.ca Sun Sep 21 14:39:01 2003 From: posman at eval.ca (Paul Osman) Date: Sun, 21 Sep 2003 14:39:01 -0400 (EDT) Subject: Creating a new file In-Reply-To: References: Message-ID: On Sun, 21 Sep 2003, anthony polis wrote: > Hello, > > I'm new to Python. Is it possible to create a NEW file in Python? I read the > tutorial on file input in the documentation but it only explains how to work > with existing files. Can someone point me in the right direction? > > Thanks, > Anthony > Sure, just open a file in write mode, i.e.: fp = open("output.txt", "w") fp.write("Hello") fp.close() HTH, -- Paul Osman posman at eval.ca http://perl.eval.ca "Idealists...foolish enough to throw caution to the winds...have advanced mankind and have enriched the world." - Emma Goldman From lefevrol at yahoo.com Wed Sep 3 11:15:45 2003 From: lefevrol at yahoo.com (Olivier Lefevre) Date: 3 Sep 2003 08:15:45 -0700 Subject: Invisible function attributes Message-ID: <51809ae4.0309030715.7706cadb@posting.google.com> Python 2.3 >>> def foo(): ... foo.a = 1 ... >>> vars(foo) {} >>> foo() >>> vars(foo) {'a': 1} >>> So it would appear that function attributes are not really there until the first call to the function. If that is the intended behaviour, it is really weird. I couldn't find any explicit discussion of this topic in the LRM. Thanks if anyone can shed some light on this, -- O.L. From marklists at mceahern.com Thu Sep 4 09:12:06 2003 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 04 Sep 2003 08:12:06 -0500 Subject: Active Scripting in Python In-Reply-To: References: Message-ID: <1062681126.15727.11.camel@dev.internal> On Wed, 2003-09-03 at 23:23, Jane Austine wrote: > I donwloaded win32all for Python 2.3 and installed it. > > I manually run pyscript.py and it returned "successfully registered" > message. > > For a simple test(on client side), I created the following html: > > > > And opened it in IE6.0 on WinXP. Unfortunately, it doesn't show > anything. I can't test this right now because my Windows machine at home is dead (long story), but have you tried using: print "hello world" OR document.write("hello world") I guess my question is whether "alert" is available when you're using language="Python". // m From wrbt at email.com Tue Sep 16 15:30:15 2003 From: wrbt at email.com (Larry) Date: 16 Sep 2003 12:30:15 -0700 Subject: xmlrpclib/timeoutsocket not happy together in 2.3 Message-ID: <2ec1bc1c.0309161130.6ada9dda@posting.google.com> I've had a production system running for a long time that uses xmlrpclib with timeoutsocket, and with my recent upgrade to 2.3 it's no longer able to use xmlrpclib with the xmlrpc servers I communicate with. I can call remote procedures still, but as soon as I import timeoutsocket and the old socket switcharoo is done it's over. To add to the fun I can use xmlrpc w/timeoutsocket if calling functions at the ubiquitous betty.userland.com example, but not the servers I've been talking to for the last two years. Example: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import xmlrpclib >>> s=xmlrpclib.Server('http://myrpcserver/server') >>> s.version() 22 >>> s.localTime() '9/16/2003 12:16:38 PM' >>> import timeoutsocket >>> s.version() Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\xmlrpclib.py", line 1029, in __call__ return self.__send(self.__name, args) File "C:\Python23\lib\xmlrpclib.py", line 1316, in __request verbose=self.__verbose File "C:\Python23\lib\xmlrpclib.py", line 1080, in request return self._parse_response(h.getfile(), sock) File "C:\Python23\lib\xmlrpclib.py", line 1217, in _parse_response p.close() File "C:\Python23\lib\xmlrpclib.py", line 531, in close self._parser.Parse("", 1) # end of data xml.parsers.expat.ExpatError: no element found: line 1, column 0 >>> s.localTime() Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\xmlrpclib.py", line 1029, in __call__ return self.__send(self.__name, args) File "C:\Python23\lib\xmlrpclib.py", line 1316, in __request verbose=self.__verbose File "C:\Python23\lib\xmlrpclib.py", line 1080, in request return self._parse_response(h.getfile(), sock) File "C:\Python23\lib\xmlrpclib.py", line 1217, in _parse_response p.close() File "C:\Python23\lib\xmlrpclib.py", line 531, in close self._parser.Parse("", 1) # end of data xml.parsers.expat.ExpatError: no element found: line 1, column 0 >>> s=xmlrpclib.Server('http://betty.userland.com') >>> s.examples.getStateName(41) 'South Dakota' Obviously the bad element here is the remote servers I communicate with since userland works, but this just started with 2.3 and I'm curious if anyone else has had a similar problem before I start digging into this. Thanks. - Larry From theller at python.net Wed Sep 24 13:14:37 2003 From: theller at python.net (Thomas Heller) Date: Wed, 24 Sep 2003 19:14:37 +0200 Subject: RELEASED Python 2.3.1 References: Message-ID: "Cousin Stanley" writes: > | ... > | The Windows installer now ships with documentation > | in searchable htmlhelp format, rather than individual > | HTML files. > | ... > > Is the htmlhelp format optional for Windows ??? > > Sometimes I like to edit the individual HTML docs .... There's a checkbox which you can uncheck to disable installing the htmlhelp file. Then you can download the HTML archive and install it manually. Thomas From tzot at sil-tec.gr Wed Sep 24 12:32:41 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 24 Sep 2003 19:32:41 +0300 Subject: why the inconsistency? References: <4bh3nv0esljf8pkegog0lc4lmg87siv1oc@4ax.com> Message-ID: On Wed, 24 Sep 2003 19:26:41 +0300, rumours say that Christos "TZOTZIOY" Georgiou might have written: >If only math.log(2**64)/math.log(10) worked with longs without >converting them into floats first... :( And after reading the FM, if only def count_digits(x): return int(math.log(x, 10)) worked correctly for *all* large values, like 10**70... -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From user at invalid.domain Wed Sep 17 04:05:35 2003 From: user at invalid.domain (Invalid User) Date: Wed, 17 Sep 2003 10:05:35 +0200 Subject: Datetime utility functions In-Reply-To: <182bcf76.0309150707.3a8c0482@posting.google.com> References: <182bcf76.0309150707.3a8c0482@posting.google.com> Message-ID: <3F6815CF.6010106@invalid.domain> Try 'mxDateTime' available at http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Download-mxBASE It most likely has what you are looking for. Paul Moore wrote: > I was just writing some code which did date/time manipulations, and I > found that the Python 2.3 datetime module does not supply a number of > fairly basic functions. I understand the reasoning (the datetime > module provides a set of datatypes, and doesn't attempt to get into > the murky waters of date algorithms) but as these things can be quite > tricky to get right, I was wondering if anyone has already implemented > any date algorithms, or alternatively if I'd missed some easy way of > doing what I'm after. > > My specific requirements were: > > 1. Get the last day of the month contatining a given date(time). I > really was surprised to find this one missing, as it seems to me that > the datetime module must know what the last day for each month is, so > exposing it wouldn't have been hard. > > 2. Add a number of months to a date. This is messy, as there are > options (what is one month after 31st Jan). The trouble is that the > calculation, while simple, is tricky to get right (month is 1-based, > so off-by-1 errors are easy to make, and divmod isn't as useful as > you'd first think). > > Other "nice to have" functions which I didn't need for this program, > but which I have found useful in the past, are > > - Round a date(time) to a {year,month,day,quarter,week,...} Or > truncate. Or (occasionally) chop to the next higher boundary > (ceiling). > - Calculate the number of {years,months,days,...} between two dates. > (Which is more or less the equivalent of rounding a timedelta). > > These latter two aren't very well defined right now, because I have no > immediate use case. > > In the absence of anything else, I'll probably write a "date > utilities" module for myself at some point. But I'd hate to be > reinventing the wheel. > > Paul. From jcribbs at twmi.rr.com Fri Sep 5 20:19:12 2003 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Sat, 06 Sep 2003 00:19:12 GMT Subject: newbie question on which win32 GUI to choose In-Reply-To: <3F590B3F.35A7B5E6@easystreet.com> References: <3F590B3F.35A7B5E6@easystreet.com> Message-ID: <4K96b.1199$sd5.298934@twister.columbus.rr.com> achrist at easystreet.com wrote: > Are there any downloadable pygtk2 apps that are a good demo, ie > non-esoteric showoff apps that I can download and run under Windows > to see how it runs on my machine? > > > Al If you go to http://www.netpromi.com/mojoview.html, you will see some screenshots from an app I wrote using PyGTK 2. I took the screenshots while running it under Windows. You can download the app and run it yourself by clicking on the link on the page. I, too, have enjoyed good luck developing PyGTK2 apps under Windows. It has been very stable and responsive for me. Jamey Cribbs From logiplex at qwest.net Tue Sep 2 18:51:41 2003 From: logiplex at qwest.net (Cliff Wells) Date: Tue, 02 Sep 2003 15:51:41 -0700 Subject: Open Source leader? (was Re: Celebrity advice) In-Reply-To: <87y8x6x2op.fsf@pobox.com> References: <23891c90.0308280317.ac68b38@posting.google.com> <87y8x6x2op.fsf@pobox.com> Message-ID: <1062543101.28388.74.camel@software1.logiplex.internal> On Tue, 2003-09-02 at 15:09, John J. Lee wrote: > aahz at pythoncraft.com (Aahz) writes: > > > In article , > [...] > > OTOH, Perens is also (like me ;-) a self-described asshole. When I saw > > him at the Waterside Conference earlier this year, he basically claimed > > that only assholes could make significant progress in the Open Source > > community. > [...] > > Why? I think it's a less eloquent version of the George Bernard Shaw quote: "A reasonably thinking man expects to adapt to nature. An unreasonably thinking man expects nature to adapt to him. Thus, all progress is made by unreasonable men." Substitute "asshole" for "unreasonable" and the sentiment is similar. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From wade at lightlink.com Tue Sep 2 21:05:30 2003 From: wade at lightlink.com (Wade Leftwich) Date: 2 Sep 2003 18:05:30 -0700 Subject: utidylib won't import Message-ID: <5b4785ee.0309021705.7370353@posting.google.com> I've installed utidylib on Python 2.3, Win2K, using uTidylib-0.1.win32.exe from http://sourceforge.net/projects/utidylib . When I try to import tidy, I get: """ >>> import tidy Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\Lib\site-packages\tidy.py", line 38, in ? from tidylib.lib import parse, parseString File "C:\Python23\Lib\site-packages\tidylib\lib.py", line 80, in ? _tidy.lookupOption.restype=c.POINTER(_TidyOptionImpl) File "C:\Python23\Lib\site-packages\tidylib\lib.py", line 32, in __getattr__ return getattr(self.lib, name) File "C:\Python23\Lib\site-packages\ctypes\__init__.py", line 231, in __getattr__ func = self._CdeclFuncPtr(name, self) AttributeError: function 'lookupOption' not found """ ... though tidylib.lib does define lookupOption(). Any clues appreciated. -- Wade Leftwich Ithaca, NY From jdhunter at ace.bsd.uchicago.edu Fri Sep 5 14:51:03 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 05 Sep 2003 13:51:03 -0500 Subject: newbie question on which win32 GUI to choose In-Reply-To: (claird@lairds.com's message of "Fri, 05 Sep 2003 11:17:25 -0000") References: Message-ID: >>>>> "Cameron" == Cameron Laird writes: Cameron> experience inclines me to the former. I've found pyGTK Cameron> too immature under Win*. The people who claim success Cameron> with it are, from what I can tell, those who benefit from Cameron> consider- able prior GTK+ work. -- I haven't found this. I've written two applications in pygtk2 and one plotting library that run with no alterations on linux and win32, and I had no prior GTK+ experience, or any GUI experience for that matter. As for immaturity, the gimp runs under windows, and I *think* pygtk can do just about anything gtk can do, hence it's a pretty sophisticated toolkit under windows. What aspects do you find immature? And glade-2 is a nice RAD tool that runs under linux and win32. Here are a couple of screenshots of a pygtk app using VTK that runs on win32 and linux http://nitace.bsd.uchicago.edu:8080/summer/jdh/image_reader.png http://nitace.bsd.uchicago.edu:8080/summer/jdh/loc3djr_shot3.png John Hunter From CousinStanley at hotmail.com Tue Sep 2 18:20:06 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Tue, 2 Sep 2003 15:20:06 -0700 Subject: TKinter is driving me crazy! References: Message-ID: | Drop $50 at the local bookstore | and buy a copy of Python and Tkinter Programming. | ... Examples from the book are available for download and I've found reading the sources and running and tinkering with the examples very helpful ... http://www.manning.com/getpage.html?project=grayson&filename=Source.html -- Cousin Stanley Human Being Phoenix, Arizona From peter at engcorp.com Mon Sep 8 13:19:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Sep 2003 13:19:22 -0400 Subject: Ternary operator References: <3F5B6404.BD1A9709@engcorp.com> <4qznp862.fsf@yahoo.co.uk> Message-ID: <3F5CBA1A.754BDD5C@engcorp.com> John Roth wrote: > > "Paul Moore" wrote in message > > Maybe it's a shame that Guido's original PEP wasn't preserved > > unaltered. What's there now doesn't capture the flavour of the > > original. > > Agreed. There may be a copy floating around in someone's archives, > though. I'm not interested enough in assigning blame to go hunting, > we need a way to move forward that will get to a real agreement. http://groups.google.ca/groups?threadm=mailman.1044638179.4983.python-list%40python.org Complete with links to the other 746 articles on the topic... -Peter From eugene_druker at yahoo.com Fri Sep 19 17:28:40 2003 From: eugene_druker at yahoo.com (Eugene Druker) Date: 19 Sep 2003 14:28:40 -0700 Subject: numarray.linear_algebra.eigenvectors bug ? Message-ID: <37cbc1de.0309191328.1ff3e822@posting.google.com> Hi all, I need eigen values and vectors for symmetric matrices (like VCV). Solving with numarray and testing the results, I've got strange results - input and output matrices of some sizes are very different. That's an example of differencies: Size MaxDif(E.Val) MaxDif(E.Vect) 2 0 1.110223e-016 3 1.776357e-015 2.053913e-015 10 1.221245e-015 7.255307e-014 11 3.552714e-015 0.8455322 12 1.526557e-016 1.345035e-013 13 8.881784e-016 0.7796273 14 2.775558e-016 0.7504375 15 2.331468e-015 2.045031e-013 This is for numarray 0.7 on W2K. I hoped to have all the differencies below 1e-15 or so. What's wrong ? Program text is below. Thanks, Eugene Druker import numarray, numarray.linear_algebra EigenVectors = numarray.linear_algebra.eigenvectors Multiply = numarray.matrixmultiply Zeros = numarray.zeros Transpose = numarray.transpose def makeCovMat(size): covmat = Zeros((size,size),'f8') d,t = 0.9,0.8 for i in xrange(size): v = covmat[i,i] = d for j in xrange(i+1,size): v *= t covmat[i,j] = covmat[j,i] = v return covmat print 'Size MaxDif(E.Val) MaxDif(E.Vect)' for size in [2,3]+range(10,24): covmat = makeCovMat(size) eval,evec = EigenVectors(covmat) # Test S = V L V' mdiag = Zeros((size,size),'f8') # L for j in xrange(size): mdiag[j,j] = eval[j] testmat = Multiply(Transpose(evec),Multiply(mdiag,evec)) ival,ivec = EigenVectors(testmat) print ' %3d %-14.7g %-14.7g' % \ (size, (eval-ival).max(), (evec-ivec).max()) From dave at 3dex.com Wed Sep 10 16:19:35 2003 From: dave at 3dex.com (Dave Benjamin) Date: Wed, 10 Sep 2003 20:19:35 GMT Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> Message-ID: "Bob Gailer" wrote in message news:mailman.1063223955.7295.python-list at python.org... > At 01:40 PM 9/10/2003, achrist at easystreet.com wrote: > >The yield statement looks to be a big step toward some kind of > >lightweight concurrency-oriented programming in python. Is there > >any similarly nice way to do the opposite of yield, just sit around > >(perhaps in the middle of a loop) and wait until some other routine > >(unknown to the waiting module) hurls a value in? > > ... > > Perhaps a new Python statement "suck"? Oh come on, now, just because Java does it... From jacek.generowicz at cern.ch Wed Sep 17 07:24:54 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Sep 2003 13:24:54 +0200 Subject: Test message. Please ignore References: <3F61AAA0.62F58E97@engcorp.com> Message-ID: Peter Hansen writes: > Saqib Ali wrote: > > > > Testing. > > Use misc.test, Last time I tried that, I immediately got 12 spams, half of them claiming that they weren't spam, because I explicitly asked for them merely by posting to misc.test. That's really great, especially if you're just trying out your fresh and unknown-to-spammers email account :-) > not a regular newsgroup, for tests please. Are you sure he wasn't posting to the mailing list ? From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 16:36:26 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 21:36:26 +0100 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <8RScb.169633$R32.5449258@news2.tin.it> <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> <0acdb.128801$hE5.4391247@news1.tin.it> <1Xhdb.130593$hE5.4445587@news1.tin.it> <9tabnvgbc4etnpp1hm3oh5dkffkru9pv0d@4ax.com> Message-ID: <2tsbnvob1k6tt6bkb29cfc69a4ji0q4giv@4ax.com> On Sat, 27 Sep 2003 12:17:53 -0400, David Abrahams wrote: >Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: >> Somehow I think David is mistaken here - I cannot believe that >> dereferencing an iterator returns a different datatype depending on >> which item it happens to point to at runtime in statically typed >> C++, > >You didn't read carefully enough: I said std::pair, not >std::pair. > >> and without that ability to dereference the iterator (1) I cannot see >> the point of iterating through a pair, and (2) the 'iterator' would >> not be a true iterator as C++ iterators have to comply with one of a >> set of standard protocols (forward, bidirectional, random etc) which >> all include subscripting. > >I'm pretty well familiar with those protocols - I've been working on >the C++ standards committee since 1997 and have written several >related proposals, c.f. http://tinyurl.com/ovpe. OK - sorry for that. I remain surprised that this degree of specialisation occurs, but it's a case of live and learn I suppose. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From ialbert at mailblocks.com Sun Sep 7 21:00:41 2003 From: ialbert at mailblocks.com (Istvan Albert) Date: Sun, 07 Sep 2003 21:00:41 -0400 Subject: negative indices for sequence types In-Reply-To: References: Message-ID: <7NCdnTH349whScaiXTWJkg@giganews.com> dan wrote: > This fact is *deeply* buried in the docs, and is not at all intuitive. > One of the big advantages of a high-level language such as Python is > the ability to provide run-time bounds checking on array-type > constructs. Bounds checking means that the size is tracked for you and an exception is thrown if you are trying to access an element *beyond* that size. That's the natural way of thinking about it, and not "checking wether there is an index like this in the list". The python way of using negative numbers in indices is extremly handy as many have pointed out. It would be silly to forego all that expressivness just to save an if test in some rare cases. > To achieve this I will now have to subclass my objects > and add it myself, which seems silly and will add significant > overhead. I would guess that instead of paying for this every time, as you want to (subclassing), you could just as simply check the index at the time when you generate it and verify that it is correct. This way using the same list in differnt context will not make it less efficient. Istvan. From peter at engcorp.com Tue Sep 9 13:56:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 09 Sep 2003 13:56:13 -0400 Subject: Redesign of Python site References: <3F5E0171.B68BDE2F@engcorp.com> <_WydnXPHCO6oksOiRTvUqA@speakeasy.net> Message-ID: <3F5E143D.356E8CF1@engcorp.com> "A.M. Kuchling" wrote: > > On Tue, 09 Sep 2003 12:36:01 -0400, > Peter Hansen wrote: > > I think that's a distinct improvement, although I'd suggest putting > > the Documentation section (in the sidebar) _first_ rather than second > > after the Versions section. > > Really? I envision people wanting information on a specific version first, > only later going to the more generic items under "documentation". I suppose it depends a lot on which group we're trying to optimize for. I was thinking of newcomers, especially people we want to send to python.org so they will stop asking FAQs. The closer the intro stuff is to the top, provided it's a small set of links, the better, in my view. I can see the case you make as well. Ah, now I see that you misinterpreted my first comment, which was not actually suggesting moving those two links to the very top, but merely moving the FAQ link to just under the "What is" link, where the latter used to be. The best discoveries are often accidents: I like what you've done. I say keep the "versions" section right where you've got it, with the other two above like that. Excellent! > > (You mention different top navbar links but they look the same to > > me, if you're talking about the Home/Search/Download stuff at the top.) > > Oh, I'm an idiot and dropped an old version of the page on top of it. > Updated now, at same URL as before. The navbar changes are: 1) dropping > SIGs and Help, 2) adding a not-yet-written "Contact us" page and a link to > the site map. Looks good, too. Not that this point is necessarily worth considering, but I note that my brain perceived several of the vertically stacked pairs of links in that top navbar _together_, leading to a fraction of a second of confusion. They appeared to read "Download documentation", "Developers community", and "Search Site map". The old ones are even weirder when read this way: "Search Developers" and "Download Community"! :-) Perhaps a tiny bit of visual cruft to separate these would be worth considering, like maybe a bullet in front of each, or square brackets, or more vertical space. (Yeah, I'm really picking nits with this one. :-) -Peter From spahievi at vega.bg Mon Sep 1 14:40:47 2003 From: spahievi at vega.bg (Niki Spahiev) Date: Mon, 1 Sep 2003 21:40:47 +0300 Subject: Object Database (ODBMS) for Python In-Reply-To: <3f4f7af6_3@corp.newsgroups.com> References: <1DAECE9E8F34E04AA0E5699AF7D9FF090708D440@stpmsg00.corp.fairisaac.com> <3f4f7af6_3@corp.newsgroups.com> Message-ID: <984649225.20030901214047@vega.bg> 8/29/2003, 19:11:51, Paul D. Fernhout wrote: [...] PDF> Well, to chime in here, in a "friendly" competition / cooperation sort PDF> of way, the Pointrel Data Repository System, PDF> http://sourceforge.net/projects/pointrel/ PDF> while not quite an object database (and admittedly its case being PDF> easier) has a simple API in the bare minimum use case (it has more PDF> complex variants). Here is an example of its use (with fragments PDF> inspired in response to an earlier c.l.p poster's use case a few days ago): How it compares with e4graph? -- Best regards, Niki Spahiev From joshway_without_spam at myway.mathworks.com Wed Sep 17 09:43:49 2003 From: joshway_without_spam at myway.mathworks.com (JCM) Date: Wed, 17 Sep 2003 13:43:49 +0000 (UTC) Subject: why pass statement? References: Message-ID: M-a-S wrote: > Why is there the pass statement? I think, the expression statement would be enough: > class C: > None > while True: > None Because emacs python-mode knows to dedent the next line after a pass :) From lists at andreas-jung.com Mon Sep 1 04:34:51 2003 From: lists at andreas-jung.com (Andreas Jung) Date: Mon, 01 Sep 2003 10:34:51 +0200 Subject: logging module: passing more args to the smtp handler? Message-ID: <2147483647.1062412491@suxmac.local> I have something like try: do_something_evil() except: reason = '....' mylogger.critical('error with', exc_info=sys.exc_info()) my logginer.ini contains: [handler_smtp] ... level=CRITICAL args=('localhost', 'aj at bla.org', 'my subject') Is there a way to pass the 'reason' var to the Logger in order to be emitted as body of the mail? -aj From domma at procoders.net Thu Sep 25 07:52:42 2003 From: domma at procoders.net (Achim Domma) Date: Thu, 25 Sep 2003 13:52:42 +0200 Subject: adodbapi / string encoding problem Message-ID: Hi, I read a webpage via urllib2. The result of the 'read' call is of type 'str'. This string can be written to disc via file('out.html','w').write(html). Then I write the string into a Memofield in an Access database, using adodbapi. If I read the text back I get a unicode string, which can not written to disc via file(...) due to encoding problems. How do I have to decode the unicode string to get my original data back? regards, Achim From aahz at pythoncraft.com Mon Sep 8 13:41:55 2003 From: aahz at pythoncraft.com (Aahz) Date: 8 Sep 2003 13:41:55 -0400 Subject: "Python Redesign" (fwd) References: <87fzj7cvbv.fsf@pobox.com> Message-ID: In article , Terry Reedy wrote: >"John J. Lee" wrote in message >news:87fzj7cvbv.fsf at pobox.com... >> >> It seems fairly clear by now that the purpose of the mockup was to > >What we were directed to was *not* a mockup (model), but an image of a >mockup. That mislabeling was a source of misunderstanding which >generated part of the criticism. Please let us keep the useful >distinction between a thing and an image of the thing. And I'll repeat that in addition to Peter's valid point about differing definitions of mockups, Tim was not the person who pointed "us" at it. This has been an out-of-context review of a draft. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From peter at engcorp.com Tue Sep 23 18:04:26 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Sep 2003 18:04:26 -0400 Subject: string.rstrip References: <731fc603.0309221414.78a92789@posting.google.com> Message-ID: <3F70C36A.81007B7A@engcorp.com> Matthew Wilson wrote: > > What would be the best way to strip off the last "_asdf" from > "asdf_asdf_asdf"? s = "asdf_asdf_asdf" without_last_asdf = s[:-len("_asdf")] of course, that works only if you know it's there... if not, prepending with a test for s.endswith("_asdf") would do the trick. -Peter From theller at python.net Thu Sep 25 10:52:03 2003 From: theller at python.net (Thomas Heller) Date: Thu, 25 Sep 2003 16:52:03 +0200 Subject: RELEASED Python 2.3.1 References: Message-ID: "Terry Reedy" writes: >> "Cousin Stanley" writes: >> > Would it be feasible to eliminate the Python Docs >> > from the standard distribution and always download >> > separately if desired ???? >> > >> > This would eliminate downloading the docs twice >> > if the user wants the separate doc files and provide >> > a leaner download for non-programming Python users >> > that will never develop anything in Python themselves >> > but who want a run-time environment only .... > > I agree that a separate Windows run-only distribution (including .pyc > instead of .py files) would be a good idea. Why would you distribute .pyc instead of .py files? Most of the time they are not even smaller, and tracebacks would be problematic. > But someone has to volunteer the time or money to make it happen. If interesting ideas evolve, I might be interested. Thomas From cfox at cfconsulting.ca Sun Sep 21 08:23:26 2003 From: cfox at cfconsulting.ca (Colin Fox) Date: Sun, 21 Sep 2003 12:23:26 GMT Subject: XML/XSLT with Python References: Message-ID: On Sun, 21 Sep 2003 11:31:40 +0000, Colin Fox wrote: Hmm. I think my news client buggered up the linefeeds. Let me try again: #! /usr/bin/env python import time st = time.time() import libxml2, libxslt import cgi, os, sys query = cgi.FieldStorage() readtimestart = time.time() styledoc = libxml2.parseFile("page.xsl") style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseFile(query['script'].value) readtimeend = time.time() start_converting = time.time() result = style.applyStylesheet(doc, None) done_converting = time.time() html = result.serialize() print "Content-type: text/html" print print html style.freeStylesheet() doc.freeDoc() result.freeDoc() et = time.time() totaltime = et-st print "" % totaltime print "" %\ (done_converting-start_converting) print "" %\ (readtimeend-readtimestart) From bgailer at alum.rpi.edu Tue Sep 2 01:45:43 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 01 Sep 2003 23:45:43 -0600 Subject: printer friendly python tutorial In-Reply-To: References: Message-ID: <5.2.1.1.0.20030901234513.02e92120@66.28.54.253> At 01:08 AM 8/31/2003 +0000, winston wrote: >winston wrote: >>does anyone know where i can find a printer friendly version of the >>python tutorial release 2.3? >never mind i found it? Where? We'd like to know too. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From ulope at gmx.de Thu Sep 18 08:35:30 2003 From: ulope at gmx.de (Ulrich Petri) Date: Thu, 18 Sep 2003 14:35:30 +0200 Subject: Help with regular expression References: Message-ID: "anton muhin" schrieb im Newsbeitrag news:bkbssb$102f$1 at news.peterlink.ru... > Stephen Boulet wrote: > > > I'm trying to write an RE to match a string that might or might not be > > ther and everything past it up to another string that might or might not > > be there and everything past it to a third string that might or might > > not be there and everything past it. > > > > Try non-greedy wildcards: r'((STRING1.*?)(STRING2.*?)(STRING3.*?))' > - - - > Since you said that each of the three strings might or not be there you would need: r'((STRING1.*?)?(STRING2.*?)?(STRING3.*?)?)' Ciao Ulrich From gherron at islandtraining.com Fri Sep 12 11:41:24 2003 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 12 Sep 2003 08:41:24 -0700 Subject: RAD with Python In-Reply-To: References: <17d520f6.0309120509.491e4d7c@posting.google.com> Message-ID: <200309120841.24623.gherron@islandtraining.com> On Friday 12 September 2003 08:17 am, John wrote: > On 12 Sep 2003 06:09:02 -0700, Ubaidullah Nubar > > wrote: > > Hi, > > > > How well is Python suited for developing database based applications? > > I am new to Python so please bear with me if some of the questions are > > too simple. I specifically have the following questions: > > > > 1. Is there an example of a simple data-entry application written in > > Python using a GUI interface? Something like a simple address book app > > with a listbox displaying all addresses with the ability to > > add/modify/delete. > > > > 2. There seem to be a number of GUI frameworks available? Which one is > > good for use on Windows and Linux? I've used Tkinter for cross platform development with great success for years, but recently I've been playing with pyGTK (and the libraries it is built upon: GTK+, glade-2 and libglade), and I like the results very much. PyGTK works on both window and Linux/Unix, Comparing the two, it seems that PyGTK produces GUI's which look much better, and are *much* more responsive. And the GUI building tool, glade-2, is *very* easy and convenient to work with. New version have just come out in the last several days, so look for and install the latest. Gary Herron From indigomoonBLINDERS at bonbon.net Sat Sep 20 15:00:58 2003 From: indigomoonBLINDERS at bonbon.net (Indigo Moon Man) Date: Sat, 20 Sep 2003 13:00:58 -0600 Subject: I love this language! Message-ID: I'm a complete newbie to Python and have been working the tutorials for only about 4 days (I'm doing 'How to Think Like a Computer Scientist' right now) but I already love this language. It's much easier for me to learn so far than others I have tried, with the possible exception of BASIC. Anyway, I've picked up a lot of good hints from reading the group already and I just wanted to thank everyone that participates here for helping out. -- Remove BLINDERS to email me. Audio Bible Online: http://www.audio-bible.com/ From max at alcyone.com Thu Sep 11 17:18:25 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 11 Sep 2003 14:18:25 -0700 Subject: why is this failing? References: <9x58b.139$u07.2@newsread1.news.atl.earthlink.net> Message-ID: <3F60E6A1.BF2D9368@alcyone.com> Chris Curvey wrote: > I've looked at this so long that I must be looking right past it. > This > code: > > class Page: > ########################################################## > def write(self, value, row=None, col=None, len=None): ^^^ > print isinstance(value, str) > > # error occurs on this line > print len(value) You are overriding the name len, so this is equivalent to writing None(value) which is obviously an error. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ God is love, but get it in writing. \__/ Gypsy Rose Lee From richie at entrian.com Tue Sep 9 08:37:12 2003 From: richie at entrian.com (Richie Hindle) Date: Tue, 09 Sep 2003 13:37:12 +0100 Subject: Ternery operator In-Reply-To: <1063110398.3f5dc6fe94f18@mcherm.com> References: <1063110398.3f5dc6fe94f18@mcherm.com> Message-ID: <7uhrlvoduqfcg64nvccua3ee0hklrc4lb1@4ax.com> [Uwe] > Normaly you should simulate "C ? T : F" > > either by > [T,F][not C] > > or > > (C and [T] or [F])[0] > > in the first case T and F are evaluated allways, > the latter solution does short circuit evaluation, > which is according to the C/C++ semantics of the > ternary operator. [Michael, shouting] > NOT TRUE! > > NEITHER of your options does short-circuit evaluation. Er: >>> def one(): print 1 return 1 >>> def two(): print 2 return 2 >>> (True and [one()] or [two()])[0] 1 1 >>> (False and [one()] or [two()])[0] 2 2 >>> So it's lazy in the sense of "will not execute the branch not taken", which is I'm sure what Uwe meant. But it's also over-eager in the sense of "may execute the taken branch multiple times." [Not condoning the use of this idiom, just correcting a factual error.] -- Richie Hindle richie at entrian.com From jjl at pobox.com Sat Sep 6 18:39:05 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Sep 2003 23:39:05 +0100 Subject: Why python??? References: <87fzjalogu.fsf@pobox.com> <87vfs6unsx.fsf@pobox.com> Message-ID: <87r82tpmnq.fsf@pobox.com> Basile STARYNKEVITCH writes: > >>>>> "John" == John J Lee writes: > > [...] > > John> "Michael Peuser" writes: > > Michael>> Same argument holds for supercomputing as well. I may be > Michael>> wrong but I doubt that the ASCIs will ever see much > Michael>> Python in their production lifetime. > > John> ASICs, you mean? Well, no, but so what? I don't think > John> anybody has ever *claimed* that Python is suitable for that > John> kind of application. > > > No, ASCI are big US government (DoE or DoD) supercomputers (used > notably for nuclear weapons computations). OK. (actually, um, do ASICs have any code in them at all? can't actually remember what they are...) > However, contrarily to Michael's belief, it won't surprise me at all > that some big numerical computations are driven by scripting languages > (scripts which call big number crunching primitives coded in C or C++ > or Fortran). At least in Europe, several number crunching applications > are driven by scripts. Of course, a huge fraction of the CPU time (ie > >= 98%) is spend in numerical routines coded in Fortran or C. Only a > tiny fraction of the work is spent in interpreting scripts. [...] Indeed, IIRC David Beazley wrote SWIG for just that purpose (controlling molecular dynamics simulations of some kind from Python). I think there's a paper about it, probably on the SWIG site. Plenty of other examples, of course. Tcl is still quite popular for this purpose, since that's what Ousterhout designed it for! And I know Python has been ported to various Cray machines. John From schwerdy at web.de Fri Sep 5 04:41:03 2003 From: schwerdy at web.de (schwerdy) Date: 5 Sep 2003 01:41:03 -0700 Subject: file.close() freezes my script Message-ID: Hi Python-Fans I'm confused! :-( I created a script that handles SC and CSV files. To convert CSV (or in my case: pipe ('|') seperated values) to SC, I want to hunt my CSV lines through /usr/bin/psc. Therefore I did: tofilter, fromfilter, error = os.popen3("psc -S -L -d '|'") map(tofilter.write,lines) tofilter.close() For some CSV-files my script freezes at tofilter.close(). Removing some lines from the "lines" sequence (that represents the CSV-file) always helps. But imho "psc" is not the cause. Piping my CSV-file through psc in bash always works. Isn't it crazy? I tried python2.2 and python2.3 from the debian distribution. Anyone who has an explanation, workaround, hint or anything? Schwerdy From glenfant at NOSPAM.bigfoot.com Thu Sep 4 10:14:15 2003 From: glenfant at NOSPAM.bigfoot.com (Gilles Lenfant) Date: Thu, 4 Sep 2003 16:14:15 +0200 Subject: Zope mailing lists dead ? Message-ID: Hi, I didn't receive anything from the various Zope mailing lists I should receive. zope at zope.org zope-cmf at zope.org zope-dev at zope.org Other subscribers can confirm or have I got problems ? Cheers --Gilles From etexier at pdi.com Tue Sep 30 18:52:36 2003 From: etexier at pdi.com (Eric Texier) Date: Tue, 30 Sep 2003 22:52:36 GMT Subject: terminal character control clean up Message-ID: On linux, I am parsing the output of an executable that's returning color and font information, thing like \x1b[1m\x1b[31m. It's there a module that will help me clean up those control, or do I have to do it with regular expression. Thanks for your help From spam at magnetic-ink.dk Wed Sep 24 18:30:36 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Wed, 24 Sep 2003 22:30:36 +0000 (UTC) Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> <3f71395d-46f08129-996a-495d-a5ee-05fb1caef6e9@news.szn.dk> Message-ID: <3f721b0c-fce176ad-f4e1-4bdc-8527-cc05ef24ad42@news.szn.dk> Christos TZOTZIOY Georgiou wrote: > if you are not root and you are sure that your own processes > do not breed like rabbits, then you can be almost sure that > os.kill(pid, 0) will throw an EPERM if your child has died. That's too many ifs to my taste. Your own processes needn't breed like rabbits - other's processes can breed like rabbits, too, and if you're unlucky, your next spawn will have the same pid as a previous process of yours. Anyway you look at it, killing blindly is bad programming practice. // Klaus -- ><> unselfish actions pay back better From tjreedy at udel.edu Mon Sep 29 10:48:45 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2003 10:48:45 -0400 Subject: query References: <2003929-93022-80040@foorum.com> Message-ID: "drn" wrote in message news:2003929-93022-80040 at foorum.com... > as we are going to develop a educational s/w for children at preprimary level My daughter started with simple games at about age 3, so I know this can be productive. > we are facing some problems in deciding what platform to choose and what s/w to > use. so please help. > -we have more of graphics work. > -we have two students working simutaneously on one system. > -we will be having 4-5 systems in total in one classroom. > > -----shall we go for one system as a linux sever with somewhat higher ... > -----shall we go for individual terminals with Linux 7.3, and with a minimum of > around 600 MB of free space,Minimum requirement for RAM 32 MB. >Minimum requirement for Hard Disk 2.1GB, The cheapest machines you can buy in US (about $600) have much more than this. With duplicate machines, any program you develop on one will run on all. >There will be no networking even among machines at one location. I think this would be a mistake. Network cards cost US$10-20. An 8-port hub or router < $200, I think. When you write a program, it will be *much* easier to install on other machine with a network. The same will be mostly true for files downloaded from Internet. > -----which lanuage do you suggest - c/c++ or any browser based software like > php/python. Python is not browser based. It is a complete standalone language just like C/C++. It also has many free add-ons available, like PyGame, which you might find useful for games and other graphics work. > please help and send your suggestions as soon as possible. > my email id is bmproj2003 at yahoo.com Posted and CCed Terry J. Reedy From shlomme at gmx.net Mon Sep 1 09:22:46 2003 From: shlomme at gmx.net (Torsten Marek) Date: Mon, 01 Sep 2003 15:22:46 +0200 Subject: ANN: libtagedit and libtagedit-python 1.0 beta 2 released Message-ID: Hello, I am very glad to announce the release of libtagedit 1.0 beta2 and its python bindings. Libtagedit is a C++ library with Python bindings using sip (www.riverbankcomputing.co.uk) to make editing tags, information or comments in music files easy. It has a plugin infrastructure for easy extension and supports MP3 (ID3v2 reading/writing and ID3v1 reading), Ogg Vorbis and (new in this release!) FLAC files. .: Description: Due to the different structure and information stored in the several music formats, this library only supports the storage of the seven fields Title, Artist, Album, Year, Genre, Tracknumber and Comment (all of arbitrary length in every file format). Also, length and bitrate will be read from the file (more technical information like channels and sample rate may be added in future 1.x releases). Editing the tags can take place without any knowlegde of the file format on the disk, so having complete albums consisting of different formats is not a problem any more. Furthermore, using the Python bindings, file information can be easily read out or changed in scripts or interactive sessions. Creating, for example, m3u files becomes a cakewalk: --== sample code ==-- import tageditor import os m3ufile = file("files.m3u", "w") m3ufile.write("#EXTM3U\n") for f in os.listdir("."): if os.path.splitext(f)[1] not in tageditor.tagEditorExts(): continue tag = tageditor.createTagEditor(f) m3ufile.write( "#EXTINF:%i,%s - %s\n" % (tag.getLength(), tag["Artist"], tag["Title"])) m3ufile.write(tag.filename() + "\n") --== end of sample code ==-- .: Changes since 1.0b1: 2003-08-31 Torsten Marek * added FLAC support * changes/additions to the build system, now Ogg Vorbis and FLAC are disabled when not detected on the system * released as 1.0b2 2003-06-01 Torsten Marek * in id3Tag::getSongInfo(): replaced head |= tmp[0] by head |= (unsigned char)tmp[0] to avoid wrong length computation There aren't any changes in the Python bindings, they're just for completeness. .: Requirements: libtagedit: Ogg Vorbis libraries (optional) FLAC C and C++ libraries (optional) libtagedit-python: Python 2.2 or 2.3 with distutils sip 3.8 .: Where to get it: http://www.sourceforge.net/projects/libtagedit .: Where to send questions: Torsten Marek From Alexandre.Fayolle at logilab.fr Fri Sep 26 12:51:36 2003 From: Alexandre.Fayolle at logilab.fr (Alexandre Fayolle) Date: Fri, 26 Sep 2003 18:51:36 +0200 Subject: [ANN] pygantt-0.9.3 In-Reply-To: <20030926164343.GQ28349@calvin> References: <20030926164343.GQ28349@calvin> Message-ID: <20030926165136.GU28349@calvin> On Fri, Sep 26, 2003 at 06:43:43PM +0200, Alexandre Fayolle wrote: > This release fixes the way to find the PIL fonts. It also fixes a bug in > the resource filter (many thanks to Mitry Samersoff for providing a > patch) My sincerest apologies to Dmitry Samersoff for misspelling his name. -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From jdhunter at ace.bsd.uchicago.edu Thu Sep 11 21:19:24 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 11 Sep 2003 20:19:24 -0500 Subject: getting ttf font/family name; fontTools? In-Reply-To: <3F60F508.8030300@rogers.com> ("Mike C. Fletcher"'s message of "Thu, 11 Sep 2003 18:19:52 -0400") References: <3F60F508.8030300@rogers.com> Message-ID: >>>>> "Mike" == Mike C Fletcher writes: Mike> TTFQuery does all this stuff (using fontTools). Mike> Particularly the "describe" module in the package does the Mike> work of pulling apart the tables to get something useful: This looks useful -- thanks. There apparently is an error in family_query.py video:~/python/src/TTFQuery-0.2.4> python2.2 family_query.py Scanning for system fonts... Traceback (most recent call last): File "family_query.py", line 11, in ? from ttfquery._scriptregistry import registry File "/usr/lib/python2.2/site-packages/ttfquery/_scriptregistry.py", line 15, in ? registry = _getRegistry() File "/usr/lib/python2.2/site-packages/ttfquery/_scriptregistry.py", line 11, in _getRegistry new,failed = registry.scan( directories, printErrors = 1, force = 0) NameError: global name 'directories' is not defined John Hunter From M.Boeren at guidance.nl Thu Sep 18 09:27:50 2003 From: M.Boeren at guidance.nl (Marc Boeren) Date: Thu, 18 Sep 2003 15:27:50 +0200 Subject: convert ints in a range to strings Message-ID: <7BE0F4A5D7AED2119B7500A0C94C58AC3D6D66@DELLSERVER> > outputFile = file('ips.txt', 'w') > r = range(256) > for r in range(256): > f = '192.168.1.%s\n' % r #Change this line to macth your network. > outputFile.write(f) > outputFile.close() I came up with this: >>> f = ['192.168.1.%d' % r for r in range(256)] >>> outputFile = file('ips.txt', 'w') >>> outputFile.write("\n".join(f)) >>> outputFile.close() Any comments on which is more pythonic? Cheerio, Marc. From gh at ghaering.de Tue Sep 9 07:27:16 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 09 Sep 2003 13:27:16 +0200 Subject: Python / C: small runtime difference? In-Reply-To: References: Message-ID: <3F5DB914.1030507@ghaering.de> Martin Schneider wrote: > One step ahead: My test program sorted a two-dimensional array containing > pairs of a string and a long integer, and the strcpy routine seems pretty > slow. > > After reducing the problem to numerical sort only, I could improve the > relation to 1:50. > > Is this a normal ratio? Not for optimized C. But your algorithm is very naive I must say. If I were to implement such an algorithm in C, I'd avoid copying as much as possible. It's best to have an array of pointers to structs. Then in your bubble-sort algorithm, only exchange the pointers, don't copy the structs themselves. FWIW your Python code most likely doesn't copy either, it only moves references around, which is quite fast. So if you make your C code as smart as Python automatically is , your C code should be a hell of a lot faster than your Python code :-) HTH, -- Gerhard From messageboardfan1 at yahoo.com Wed Sep 24 09:40:18 2003 From: messageboardfan1 at yahoo.com (ataraxia2500) Date: Wed, 24 Sep 2003 15:40:18 +0200 Subject: newbie script References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> Message-ID: <3f719ed5$0$14824$79c14f64@nan-newsreader-03.noos.net> ok thanx I'm on linux, what I want basically is the script to launch xyz and then check if it's running using os.system('xyz'), and if it's not running I want the script to relaunch xyz. So could u tell me please also how to launch or relaunch a programme please :) > > If you're UNIX based: > > os.system('xyz') will return the exit status of your program xyz. > More importantly for you, it will return! > > So try an (ugly) loop like: > > import os > while 1: > os.system('xyz') > > > -Ed > > ataraxia2500 wrote: > >> I wanna do a script that launch a programm xyz and relaunch xyz if it >> crashes. what kind of module do I need for such a task? > From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 15:24:52 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 20:24:52 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: On Tue, 23 Sep 2003 12:08:04 -0700, Tim Hochberg wrote: >Stephen Horne wrote: >> On Tue, 23 Sep 2003 08:44:13 -0700, Tim Hochberg >> wrote: >> >> >>>FWIW, Psyco recognizes this structure and removes the overhead >>>associated with it. >> >> >> I went looking for Psyco yesterday, and all I could find was broken >> links. Was sourceforge just having bad day, or is there a new site >> that hasn't made it into Google yet? > > >Probably the former. I just checked at http://psyco.sourceforge.net/ and >everything seemed to be working. You're right - I can see it now. Thanks. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From syver at inout.no Thu Sep 4 04:14:00 2003 From: syver at inout.no (Syver Enstad) Date: 04 Sep 2003 10:14:00 +0200 Subject: Active Scripting in Python References: Message-ID: janeaustine50 at hotmail.com (Jane Austine) writes: > I donwloaded win32all for Python 2.3 and installed it. > > I manually run pyscript.py and it returned "successfully registered" > message. > > For a simple test(on client side), I created the following html: > > > > And opened it in IE6.0 on WinXP. Unfortunately, it doesn't show > anything. > > After googling, I tried "pyscript.py --debug" and the trace collector > shows: > > Object with win32trace dispatcher created (object=None) > in _InvokeEx_ with GetInterfaceSafetyOptions 0 1 > (IID('{BB1A2AE2-A4F9-11CF-8F20-00805F2CD064}'),) None None > in _InvokeEx_ with GetInterfaceSafetyOptions 0 1 > (IID('{BB1A2AE1-A4F9-11CF-8F20-00805F2CD064}'),) None None > > Am I doing something stupid? I think Mark Hammond has disabled the scripting extensions by default, go to Mark Hammonds site, there should be an explanation on how to enable it there... From jjl at pobox.com Mon Sep 15 13:04:56 2003 From: jjl at pobox.com (John J. Lee) Date: 15 Sep 2003 18:04:56 +0100 Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <17d520f6.0309130704.7944c876@posting.google.com> <87znh89ufv.fsf@pobox.com> Message-ID: <878yoqoudj.fsf@pobox.com> Steve Lamb writes: > On 2003-09-13, John J. Lee wrote: > > I've never seen anybody give a convincing reason why GTk is a good > > choice for *anything* except writing GNOME apps. > > I run several GTK apps that don't touch Gnome: > Sylpheed-Claws > Pan > XChat > > GTK != GNOME. [...] Yep: that's exactly what I don't understand! *Why* did you do that? John From gerhard.haering at opus-gmbh.net Wed Sep 3 10:46:41 2003 From: gerhard.haering at opus-gmbh.net (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 Sep 2003 16:46:41 +0200 Subject: Anybody else having problem *sending* mail to this list? Message-ID: <3F55FED1.7020406@opus-gmbh.net> On my mailserver (running a recent Postfix snapshot) I get this since a few hours: mylene:/var# mailq -Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient------- DA10713E37 1617 Wed Sep 3 11:32:46 gh at ghaering.de (lost connection with mail.python.org[12.155.117.29] while sending end of data -- message may be sent more than once) python-list at python.org However, using telnet to send mail to python-list on mail.python.org from the same host seems to work fine. Is there something strange going on? -- Gerhard From robin at jessikat.fsnet.co.uk Fri Sep 19 11:48:10 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 19 Sep 2003 16:48:10 +0100 Subject: pop3 email header classifier? Message-ID: Hi, I'm getting vast numbers of fake upgrade emails containing some kind of virus. My rather old client can be made to reject these based on some patterns in the subject line. They're nearly all based on the word 'New', 'Latest', 'Microsoft', 'Patch', 'Pack', ... etc etc. Is there a python tool that can be made to delete these from my POP3 mail box rather than let my client reject? Quite a few seem to have semi-valid return addresses so I get postmaster rejects from xxx at microsoft.com etc. I know about spam-bayes etc, but these things are over 120k each and it seems pretty pointless to download them (as well as taking about an hour). -- Robin Becker From __peter__ at web.de Tue Sep 23 13:24:36 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Sep 2003 19:24:36 +0200 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> <299f1138.0309230818.22bc9bf6@posting.google.com> Message-ID: jallan wrote: > I don't see any particular reason why Python "cannot handle case > mappings that increase string lengths". Now that's a long post. I think it essentially boils down to the above statement. Looking into stringobject.c (judging from a first impression, unicodeobject.c has essentially the same algorithm, but with a few indirections): static PyObject * string_upper(PyStringObject *self) { char *s = PyString_AS_STRING(self), *s_new; int i, n = PyString_GET_SIZE(self); PyObject *new; new = PyString_FromStringAndSize(NULL, n); if (new == NULL) return NULL; s_new = PyString_AsString(new); for (i = 0; i < n; i++) { int c = Py_CHARMASK(*s++); if (islower(c)) { *s_new = toupper(c); } else *s_new = c; s_new++; } return new; } The whole routine builds on the assumption that len(s) == len(s.upper()) and nothing short of a complete rewrite will fix that. But if you volunteer... Personally, I think it's a long way to go for a little s, sharp as it may be :-) Peter From tim.one at comcast.net Fri Sep 19 12:10:40 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 19 Sep 2003 12:10:40 -0400 Subject: file position *tell()* works different In-Reply-To: <13a533e8.0309190137.2df0cc60@posting.google.com> Message-ID: [Peter Abel] > I'm working under W2k with > Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on > win32 > > I have a file *test_data.txt* with the following content: > 0123456789 > 0123456789 > abcdefghi > ABCDEFGHIJKLMNOPQ > > and I work on it with the following python script: > > # Open NOT in binary mode > fp=file('test_data.txt','r') > a='xx' > while a: > print 'Filepointer: %3d' % fp.tell() > a=fp.readline() > fp.close() > > print > > # Open IN binary mode > fp=file('test_data.txt','r+b') > a='xx' > while a: > print 'Filepointer: %3d' % fp.tell() > a=fp.readline() > fp.close() > > Now, when test_data.txt is saved in PC-mode with 0xC, 0xA as newline >it works correct. What does "correct" mean? Or what does incorrect mean? > But when I save the file in UNIX-Mode with 0xA as newline, > my script gives me the following output, where that one with > the file not opened in binary mode is wrong: > Filepointer: 0 > Filepointer: 7 > Filepointer: 19 > Filepointer: 30 > Filepointer: 49 > Filepointer: 51 > > Filepointer: 0 > Filepointer: 11 > Filepointer: 22 > Filepointer: 32 > Filepointer: 50 > Filepointer: 51 What exactly about that do you think is wrong? For example, tell() results for files opened in text mode have no portably defined relationship to byte offsets from the beginning of file, so it's not wrong simply that the numbers displayed differ between the two blocks of output. Here from the C standard: The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read. When f is opened in text mode, about the only thing you can do with an f.tell() result portably is to use it as-is (without doing arithmetic on it first) as an argument to a later f.seek(). When the standard says it's unspecified beyond that, it means it. > When I try this under HP-UX it works fine in both cases. Unixish systems make no distinction between text mode and binary mode, but Windows does. That's why the results differ. > So I wonder if the function *tell()* is not correctly implemented > under win32. Python's file.tell() on Windows just calls a Microsoft C function. AFAIK, Microsoft's implementation conforms to the C standard, but the C standard doesn't promise as much as you appear to believe it does/should. From roy at panix.com Mon Sep 22 21:08:01 2003 From: roy at panix.com (Roy Smith) Date: Mon, 22 Sep 2003 21:08:01 -0400 Subject: What is a "method-wrapper" object? Message-ID: I had a class called rule and a subclass of rule, called bgpRule, in a file called bgp.py. I decided to move the rule class to its own file, called rule.py. The original file did "import rule". I forgot to change bgpRule's __init__() method from calling rule.__init__() to call rule.rule.__init__(). Amazingly, this caused no immediate error, but rule.__init__() never got called. When I found the problem, I was puzzled as to why I didn't just get AttributeError when I called rule.__init__(). A little investigation led to this: [rsmith at qwerky agent]$ py Python 2.2.2 (#1, Apr 5 2003, 13:59:12) [GCC 3.2.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import rule >>> dir (rule) ['__builtins__', '__doc__', '__file__', '__name__', 'rule', 'target', 'time'] >>> print rule.__init__ >>> print rule.__init__() None >>> So, what is this "method-wrapper" thingie that doesn't show up in the module's dir()? I don't see any mention of it in the on-line documentation. Have I stumbled upon one of those deep dark Python secrets that mere mortals aren't supposed to know about? From pyth at devel.trillke.net Fri Sep 19 12:48:51 2003 From: pyth at devel.trillke.net (Holger Krekel) Date: Fri, 19 Sep 2003 18:48:51 +0200 Subject: was: Re: looking for MOP documentation In-Reply-To: <3F6B2AB1.2D839EF5@engcorp.com>; from peter@engcorp.com on Fri, Sep 19, 2003 at 12:11:29PM -0400 References: <3F6319E9.4C7BAA0F@engcorp.com> <3F66F516.3D06D946@engcorp.com> <3F69AD0F.53D51719@engcorp.com> <3F69D215.5649AF66@hotmail.com> <3F69DFEB.5B05CED8@engcorp.com> <7h37k45j895.fsf@pc150.maths.bris.ac.uk> <3F6B2AB1.2D839EF5@engcorp.com> Message-ID: <20030919184851.D31102@prim.han.de> Hello Peter, Peter Hansen wrote: > Michael Hudson wrote: > > Of course, there's a sense in which Common Lisp just doesn't have much > > syntax, but Python's hardly overloaded with it, either. *The objects* > > or to be more precise the *types* of objects themselves are what > > determine really happens, and that's precisely the sort of thing > > metaclasses let you play with. > > I guess this might get down to the question of whether Python is more about > the syntax, grammar, keywords, and such, of the language or more about the > standard types of objects which are provided with it. In my mind, it's > very much the former and very little the latter, but maybe that's just me. > Dicts and lists and integers are interesting and all, but I'm not sure > it's their behaviour which makes Python Python. Although probably 2/3 of the implementation of Python deal with the type/object implementations, from a using-the-language point of view the syntax probably contributes more obviously to the observed "simplicity" of Python. But the term "meta object protocol" seems to point much more into the direction of types/objects as Michael suggests and here Python has a lot to offer. Is there some free material on MOP somewhere? FWIW, in the next pypy-sprint we'll probably try to deconstruct the python-syntax and its resulting compilation and execution into several aspects. Maybe we should term this effort meta language protocol :-) cheers, holger From nhodgson at bigpond.net.au Thu Sep 4 06:01:09 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 04 Sep 2003 10:01:09 GMT Subject: Tkinter Text widget getting too slow References: <87bru1fny7.fsf@pobox.com> Message-ID: John J. Lee: > How about something like Scintilla? The original poster had tried PyCrust which uses the wxWindows port of Scintilla wxStyledTextCtrl. The design centre for Scintilla is editing source code files and its assumptions are incorrect for very large documents or very wide documents. The performance of Scintilla is dependent on how it is used as much as its design and it can be sped up greatly by turning off styling and word wrap. Neil From daniel.a.joyce at worldnet.att.net Thu Sep 11 14:20:27 2003 From: daniel.a.joyce at worldnet.att.net (Daniel Joyce) Date: Thu, 11 Sep 2003 18:20:27 GMT Subject: Problems with Python/Pycrust on SUSE 8.2 Message-ID: When I try and run pycrust, I get... 'import site' failed; use -v for traceback Traceback (most recent call last): File "/usr/bin/pycrust", line 4, in ? from wxPython.lib.PyCrust.PyCrustApp import main File "/usr/lib/python2.2/site-packages/wxPython/lib/PyCrust/PyCrustApp.py", line 8, in ? from crust import CrustFrame File "/usr/lib/python2.2/site-packages/wxPython/lib/PyCrust/crust.py", line 8, in ? from filling import Filling File "/usr/lib/python2.2/site-packages/wxPython/lib/PyCrust/filling.py", line 9, in ? from wxPython import stc ImportError: cannot import name stc Segmentation fault idle gives: 'import site' failed; use -v for traceback But continues to run, though I don't know if any features are broke. WX is installed, there is a stc.h Is there a recompilation step I can do? DO I need the new WXPython release? I checked YAST2 for update patches, but SUSE has no published fix. -Daniel Joyce ---- The Meek shall inherit the Earth, for the Brave are among the Stars! From ryan10975073 at netscape.net Tue Sep 9 22:51:35 2003 From: ryan10975073 at netscape.net (ryan10975073 at netscape.net) Date: Tue, 09 Sep 2003 22:51:35 -0400 Subject: Internal states.. Message-ID: <124EEBE3.600A3EC8.A05AB946@netscape.net> Chad Netzer wrote: >On Tue, 2003-09-09 at 19:05, ryan10975073 at netscape.net wrote: >> Chad Netzer wrote: > >> ? Thank you. Sounds interesting. :~) well do you know any resource or something i can dwell into >> ?for "Mersenne Twister (part of Python2.3),and "cryptographic random number generation" ?? > >For Mersenne Twister, just search on Google. ?Same for cryptographic >random number generator (or cryptographic hash). ?Mind you, the latter >are HEFTY subjects, with lots of math. ?The crypto RNG topics require a >lot of knowledge about cryptography in general, to understand fully. > >> ?And what u are saying is that everytime the seed([x]) where x = long int, it would return the same value?? > >Yes. > >$ python2.3 >Python 2.3 (#1, Aug 12 2003, 13:06:21) >>>> import random >>>> help(random) > >>>> random.seed(0) >>>> random.random() >0.84442185152504812 >>>> random.random() >0.75795440294030247 >>>> random.random() >0.420571580830845 > >>>> random.seed(0) >>>> random.random() >0.84442185152504812 >>>> random.random() >0.75795440294030247 >>>> random.random() >0.420571580830845 > > >> ?if it does thats then whats the point ?? > >Setting the seed has several uses. ?You can store its value to repeat >sequences of events (sometime used in simulations). ?You can create >truely random seed values somehow, then use them to set the seed (the >system time values are typically a small subset of all possible seeds, >and similar starting seeds can produce simlar values on poorly made >RNGs) > >> ?Its better to use seed() which is based on the system's time then.. > >If you don't care about the specific seed, yes, just let the system make >one for you. ?For cryptographic applications (which the RNGs we are >talking about are NOT suited for, generally), it is very bad advice to >use the system time, alone, as a seed. > >> And i think we can't use Mersenne Twister RNG in Python if i am not wrong. > >Python2.3 comes with it. ?It is just an implementation detail (but it is >generally considered a better, faster RNG than the previous >implementation). ?It is what I used above. > >Is there any reason you didn't send your reply to the Python mailing >list? ?I'm CC'ing the list, since there is nothing personal in this >email, and it started on the list. > > >-- >Chad Netzer > > Yup!sorry. it was a mistake.. :~(.. Thank you anyway. I got your message clean & cut. Cheers, Ryan __________________________________________________________________ McAfee VirusScan Online from the Netscape Network. Comprehensive protection for your entire computer. Get your free trial today! http://channels.netscape.com/ns/computing/mcafee/index.jsp?promo=393397 Get AOL Instant Messenger 5.1 free of charge. Download Now! http://aim.aol.com/aimnew/Aim/register.adp?promo=380455 From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Sep 11 11:43:11 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 11 Sep 2003 16:43:11 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> Message-ID: <66t0mv410it5ftvjokfpkov0v029trv6lp@4ax.com> On Thu, 11 Sep 2003 13:10:42 GMT, "Steve Holden" wrote: >First of all, if you insist on using an invalid address, might I suggest >that "x at y.invalid" would be less visually annoying, with the additional >merit of actually meaning something. I used to have something like that, only my newreader won't allow a completely invalid addresss (it insists on seeing '.co.uk' and some other formatting stuff). It turned out that my obviously invalid domain was actually valid and owned by someone else. Actually, it was pointed out to me by someone who disagreed with a point I was making. Basically, even if a spamtrap domain is actually a real domain by pure fluke, it will still recieve my spam - as said the lecture. If dollar signs are valid in a domain name (which I assume they are as my newsreader allows them) then I can imagine a valid domain consisting of one, two, three or whatever of them - but not a huge run of them. That is the reason for my choice. By preference I would miss that line out of the header completely, but it's not an option. This first comment of yours raises the suspicion that, in disagreeing with my idea, you feel you have to attack everything you can about me and about the idea. Let's see how that suspicion pans out... >So, if I can summarise. You see a feature in C# that represents perhaps one >of the less-well-thought-out aspects of the language. You then ask how to >graft it into Python because "Python should be more like C#"? Oh dear. In C#, 'ref' parameters are not IMO a "less-well-thought-out" aspect of the language. They are, IMO, a very well thought out feature in the context of that language. Making the 'ref' explicit in the call is also a novel approach which I don't think I've seen in any other language, which is why I decided to raise the subject. On thinking it through, it simply isn't necessary in Python - but that doesn't mean you have to make it out to be a universally bad idea or go through the old 'stop trying to turn Python into X' garbage. Actually I'm sick to death of the old 'your just trying to turn Python into X' argument whenever I suggest that *maybe* Python might learn a trick from another language. I have been accused of trying to turn Python into C, C++, Java, Pascal, Ada and several others in the past. None of these accusations is true. They are tired and pathetic. They say more about the accuser than the accused. Believe it or not, languages other than Python have good features. Believe it or not, Python has become a better language by adopting features from other languages AS WELL AS by adopting ideas of its own. Sometimes a feature that works well in one language can work well in another. Python does not need a 'not invented here' mentality. >> : The rationale for this in C#, I assume, is mostly about clarity and >> : maintainability - the caller can't be surprised when value type >> : parameters are changed in a function as he had to explicitly allow it. >> >I agree the requirement for the "ref" keyword in the call lends some >clarity. Not sure I'd agree about maintainability, though. Maintainability is mostly helped by explicitness. The maintainer can see that the parameter might be rebound simply by looking at the call. I can't imagine any scenario where improved clarity doesn't lead to improved maintainability. > And it can only >be a matter of time before people start suggesting that the ref mechanism be >used because there's a two-hundred nanosecond time saving ... Garbage. Neither Python nor C# are meant to be execution speed record holders. I did address a performance issue, but only because (1) that performance issue was raised by the 'against' side in a previous discussion of pass-by-reference parameters and (2) there is already some sensitivity to the idea of Python becoming slower than it already is (IIRC some people still use Python 1.5 in part because it is a little faster than Python 2.x). It would be hard to predict the relative speeds of a this idea against the tuple-returning method. Each has its own overheads - in one case creating and unpacking the tuple, in the other case checking that the right parameters are marked as 'ref' or not. All I can say for sure is that the performance of conventional function calls would not change. But then my argument was never about performance. It appears to me that you invented that issue purely so you could counter it - but countering an argument that the other side never made is a very weak victory. >But given Python's ability to have a function return a tuple to an unpacking >assignment (which has the real advantage that the intention to modify the >value of the left-hand tuple elements is explicit) I really can't see why >you want to complicate things further. It is possible for a person to propose an idea for discussion without having though it through fully - that may even be the point of proposing it for discussion. If discussion could never lead to new ideas and changed opinions there'd really be no point. In the context of Python the idea turns out to serve no compelling purpose. I already admitted that in message ID cg5vlvgorsi88elsn9ur5ueavpg27d7ui3 at 4ax.com. I was even showing signs of heading that way when I said... : C# 'needs' ref parameters because it has no convenient way to return : multiple values from a function. Python does not. The question is : really whether this argument about expressing intentions and evading : errors is compelling or not. all the way back in message ID jnkulv8t6e1qc3mb4pmf0k706e98pgmss2 at 4ax.com You don't have to claim that the feature is "one of the less-well-thought-out aspects of" C# to do that - C# is not Python. You also don't need to accuse me of trying to "graft it into Python because "Python should be more like C#"". Basically, you don't have to turn this into a crusade just because I thought an idea from another language might be worth some thought and discussion. Python is not the one true faith - it is a programming language. Like all good programming languages it has sometimes adopted good ideas from other programming languages. This idea is not destined to be one of them, and that's fine - it was a bad idea, but that doesn't make it a heresy. Discovering whether an idea is bad is one of the advantages of discussion. >"Explicit is better than implicit". This has nothing to do with it - the 'ref' notation *is* explicit. >> > Currently, if you see a call to f(x) you know >> >that x cannot be rebound. >> >> And if in some future version of Python the suggestion I made was >> implemented, when you see f(x) you will still know that x cannot be >> rebound - but when you see f(ref x) you will know that x may well be >> rebound. >> >OK, remind me why this is better than > >x = Inc(x) > >or > >x, y = DoubleInc(x, y) The idea I had in mind is that sometimes it is a good thing to restrict what the caller can do in order to prevent errors. The return-value method may hypothetically, in some cases, allow excessive flexibility. If the intention of the function is to replace a value then literally doing that in the function itself - rather than leaving it the the caller to decide whether to replace it or whether to keep both - may be a good idea. At present Python allows this if the value is a component of a mutable object passed in as a paramater, but not if the value was passed in directly as the parameter itself. As it turns out, I can't think of a compelling example where this idea would be beneficial and that logic above almost certainly doesn't connect to the practicalities of real world programming - I've already said that - but it wasn't immediately obvious that it would work out like that when I started the thread. >> I wouldn't want this. To implement it, either a single compiled >> version of a function would need to figure out at run time whether the >> parameters where by reference or not, or several versions of each >> function would have to be compiled into the .pyc file. >> >> Also, I don't really see the benefit. If a function has by-reference >> parameters then rebinding those parameters is likely a big part of the >> purpose of the function. Supplying a parameter which cannot be rebound >> is likely an error caused by someone forgetting to type the 'ref', in >> which case they'd equally likely appreciate an error message as >> opposed to wierd, hard-to-trace logic errors. >> >So you introduce a "ref" keyword so that a dangerous and unneccessary >mechanism can be "safely" introduced? Not at all. The dangerous thing in JCMs example is the overloading, not the call-by-reference. Pass-by-reference parameters are not dangerous. Making the pass-by-reference explicit in the call is also not dangerous. I am a little suspicious of the C# system of using 'ref' and 'out' to resolve overloading, but Python doesn't do overloading at all. That doesn't mean overloading has to be a bad idea and neither does it mean that Python is a bad language. Like any language feature overloading has a good and a bad side to it, and like any good language Pythons features are selected to work well in the context of the language as a whole. Different languages simply have different strengths and weaknesses. But overloading is a separate issue to pass-by-reference - take a look at standard Pascal for instance, which has pass-by-reference but no overloading. Pass-by-reference is unnecessary in Python, yes. The theoretical argument does not connect to practical reality. But as I already said, it was not immediately obvious that it would work out that way. From aleax at aleax.it Mon Sep 8 07:28:49 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 08 Sep 2003 11:28:49 GMT Subject: basic rules of design (was Re: Comments on Python Redesign) References: Message-ID: Fernando Perez wrote: ... > A basic rule of design should always be: a default (www.python.org) value > should satisfy the _majority_ of usage cases (not those with the most > money/corporate power/whatever). Since the majority of visitors to the > site can arguably be thought to be developers, _that_ is the audience the As a general principle of design, this is wrong, because it does not take into account the _COST_ of occurrences of "not satisfying". Consider dictionary addressing: what DOES one want to occur when the key is not in the dict in an operation such as thedict[thekey]? It is arguable that in a majority of cases one wants to use a default value while the need to get an error is somewhat rarer. HOWEVER, this does not mean Python's design is wrong, because this simple count regarding "majority of use cases" is not considering the *COSTS*. If absent keys implicitly supplied a default value, then using the default when an error should be instead raised for key absence would produce weird and hard-to-debug error situations down the line; as is, using the default when in fact one wants to supply a default value immediately produces an exception that shows one must use .get (or whatever) instead. So, the current design may well be optimal even though it might appear to conflict with the "basic rule of design" as Fernando mistakenly states it. Of course, if one DOES consider costs appropriately, then the thesis that Fernando wants to promote doesn't necessarily follow any more. It may well be argued that developers are more web-savvy than managers and other corporate decision-makers, easily able to follow a link and/or set a bookmark as appropriate -- so that failing to serve developers by the default homepage has low cost, while failing to serve managers by it (even though it were true that *EVEN IN THE FUTURE* most visitors will be developers) may well have higher costs. This doesn't necessarily have to do with "money" or "corporate power", but rather with ability of the two sub-audiences to negotiate different levels of difficulty -- what's trivial to a developer may well not be to an executive. Analogy: say that due to space constraints (adapting to public use an existing Renaissance building, a frequent case around here) I have to choose EITHER a few steps or stairs OR a ramp as the building's main public access way. Maybe for 95% of the visitors the stairs are marginally more convenient than the ramp. If one were to apply Fernando's mistakenly-stated principle, one would choose stairs. But actually the inconvenience of ramps vs stairs to those 95% of users is minor, call it 0.01 in some arbitrary unit of utility -- while for the 5% of visitors who are wheelchair-bound, the stairs are *WAY* more problematic than the ramp, say by 10.0 in the same unit of measure. So if one were to follow Fernando's principle of serving the majority of use cases, overall loss of utility for 100 visitors would be 50.0 units (10.0 each for the 5 wheelchair-bound visitors); by following the RIGHT principle of maximizing overall utility (WEIGHING the frequency by the cost, a TRUE key principle of design!), the overall loss of utility would be 0.95 (0.01 each for the 95 non-wheelchair-bound visitors). Thus, the application of Fernando's mistaken principle would be a minor tragedy in term of design failure in this hypothetical case. It's not an issue of anybody being a "second class citizen", as Fernando emotionally puts it: it IS an issue of the ables and strongest, even if in a majority, making a (to them) minor sacrifice to help less-able and weaker ones, even if in a minority, avoid what (to them) might more likely be a serious problem. If designers will consider this issue more generally when making their key architectural decisions, then this whole weird thread may have repaid itself by this single observation;-). Alex From roy at panix.com Mon Sep 15 20:29:10 2003 From: roy at panix.com (Roy Smith) Date: Mon, 15 Sep 2003 20:29:10 -0400 Subject: object.attribute vs. object.getAttribute() Message-ID: For the past 6-8 months, I've spent most of my time writing C++ and a little bit of Java. Both of these languages support and encourage the use of private data and explicit accessor functions, i.e. instead of writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to writing Python, I find myself in a quandry. Historically, I've always avoided accessor functions and just reached directly into objects to get the value of their attributes. Since Python doesn't have private data, there really isn't much advantage to writing accessors, but somehow I'm now finding that it just feels wrong not to. I'm not sure if this feeling is just a C++/Java-ism that will cure itself with time, or if perhaps it really does make sense and I should change the way I code. On the plus side, accessors/mutators give me: 1) Implicit documentation of which attributes I intended to be part of an object's externally visible state (accessors). 2) Hooks to do data checking or invarient assertions (mutators). 3) Decoupling classes by hiding the details of data structures. 4) Vague feeling that I'm doing a good thing by being more in line with mainstream OO practices :-) On the minus side: 1) More typing (which implies more reading, which I think reduces the readability of the finished product). 2) Need to write (and test) all those silly little functions. 3) Performance hit due to function call overhead. 4) Only the appearance of private data (modulo some slots hackery). 5) Code is harder to change (adding functionality means going back and adding more slots). 6) Vague feeling that I'm dirtying myself by letting C++ and Java change my Python coding habits :-) Comments? From eric.brunel at pragmadev.com Wed Sep 10 03:47:58 2003 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 10 Sep 2003 09:47:58 +0200 Subject: I need to make Excel/Powerpoint-style charts. References: Message-ID: python at sarcastic-horse.com wrote: > Hi- > > > My office produces a lot of charts based on time-series data. We use MS > powerpoint and excel to make these charts. The data gets updated > regularly, but there doesn't seem to be an easy way to automate updating > the charts using these packages. So, we spend a non-trivial amount of > time manually updating lots of spreadsheets to redraw the charts we need. > > I hope to find some sort of python graphics library that can make charts > similar to Excel and Powerpoint, and then I can start automating these > tasks. > > Here is an example of the charts we make: > > http://www.sarcastic-horse.com/example.pdf #52k size file. > > Are there any packages that can do similar charts? I need to be able to > chart time-series data with occasional missing observations. I also need > to be able to shade some regions of the charts, and add text titles, > captions and notes. > > I'm (slowly) learning the reportlab package, and it looks good, but I > wanted to check if there was an even better solution out there. > > Thanks for the help. Maybe you'll be interested in gdchart/PyGDChart: http://www.fred.net/brv/chart I'm not really sure it can do everything you want, though... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jjl at pobox.com Wed Sep 3 19:32:16 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Sep 2003 00:32:16 +0100 Subject: Tkinter Text widget getting too slow References: Message-ID: <87bru1fny7.fsf@pobox.com> janeaustine50 at hotmail.com (Jane Austine) writes: > As you add more items, say text lines, in Text widget, it gets too > slow and almost impractical to use on. Take idle for example. If the > text gets bigger(e.g. print [...] > Is there any way to speed up Text widget, or should I look for another > GUI library? I'm surprised that you're having trouble with it, actually, but: How about something like Scintilla? I'm not sure about wx and Tk, but Scintilla is available for GTk and Qt, IIRC (the latter is a port, called QScintilla). There might well be something similar for wx or Tk. Or maybe the standard Qt or GTk text widgets are themselves more scalable than their wx or Tk counterparts -- no idea. If you specifically want a Python shell, I think eric3 uses QScintilla, so there should be code in there you can use. John From anand_soliton at yahoo.com Wed Sep 10 21:02:37 2003 From: anand_soliton at yahoo.com (Anand) Date: 10 Sep 2003 18:02:37 -0700 Subject: Python C extension: Value different if passed as list than if passed as number References: <3f5dc178.0309101343.256bb7f5@posting.google.com> Message-ID: <3f5dc178.0309101702.7294c356@posting.google.com> My bad. I wanted to a inplace memory write for an int. so i = 0; func(i); print i; ====== output = 1. The funny thing is python doesnt use 0 as 0. instead it points to a memory location whose value = 0. Since in my inplace replace, i changed that value from 0 to 1, test[0] actually became test[1] :)) so i had tons of strange behavior happening. I shouldnt have made an immutable object as mutable. From rzantow at ntelos.net Wed Sep 17 04:21:20 2003 From: rzantow at ntelos.net (rzed) Date: Wed, 17 Sep 2003 04:21:20 -0400 Subject: Computer Programming for Everybody, a Newbie Project References: Message-ID: Arthur wrote: > Ron asks - > >> Any other ideas would be appreciated. Meanwhile, I would be >> interested if anyone would offer thoughts on which of the 5 >> directions for future activity sound most interesting. > > Sorry Ron. > > Can you remind me what the connection to CP4E is, and why you are > headlining that slogan in connection with your work. > > You, as did I with my own project, with sustained effort over a three > year period - starting, let's say from scratch - produced something > of which each of us can hopefully be rightfully proud. > > Three years of sustained effort. > > But we seemed to have taken away different lessons. > > My expereince led me to look upon the CP4E slogan quite askance. > Yours, apparently, allowed you to embrace it. > > It seems to me "everybody" who's imagination is ignited by something > to the extent that it carries them through 3 years of sustained > effort can expect to be doing "computer programming" somewhere along > that line. > > Not very surprising, really. > > No slogans helped me along - that I do know. > > It was three years of sustained effort. > > For everybody? > > Are we *required* to embrace that notion? > > Yes everybody - let's say - has that potential. But that was true > before Python came along. > > For some - like myself - Python was a real factor in helping realize > that potential. I am a raving fan, in fact. > > But I do not discount my 3 years of sustained effort as anything less > than 3 years of sustained effort, and seem to think that that was a > bit of factor, as well. > > And would love to see the CP4E slogan go away now, peacefully and > happily. > This post is very confusing to me. I'm not sure what a three-year project in itself has to do with CP4E. Would you say that a slogan like "Literacy for Everyone" should go away because it took you three years to write a novel? I've worked on very few programs that required a three-year sustained effort. The large projects that did are not, I think, in any way related to the idea of CP4E. To my mind, the things that are related are three-minute projects (well, okay, a little longer than that): quick programs that are purpose-built to allow an actual job to be done. By "actual job" I mean the job of, say, teaching, or editing, or whatever it is that the non-programmers who create the handy little programs are paid to do. Some of those utilities are useful enough to work into more elaborate and general programs, but not everyone has the same needs, and not everyone has the dedication or capability to do the sustained work you seem to be talking about. I would certainly never discount a three-year project; the effort is laudable, and presenting the result to others can be daunting. Most of the programs 'everyone' writes do not, I believe, fall into that category. But they make the lives of their users a little better nonetheless, and that, it seems to me, is the point of CP4E. -- rzed From gh at ghaering.de Thu Sep 11 10:27:29 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 11 Sep 2003 16:27:29 +0200 Subject: 1.5 vs. 2x - build problem In-Reply-To: References: <7af2fd5c1a70e3c6ce4fe1f8eee39b9b@remailer.frell.eu.org> Message-ID: <3F608651.6080307@ghaering.de> Steve Holden wrote: > "Fritz Wuehler" wrote: >>I downloaded a tarball which doesn't compile. The error message says I >>need python 2x but all I have is 1.5. Can I fix the compatability >>problem and get it to work on 1.5? > > Yes, please do. On the other hand, you could invest the time and bring your software/system up-to-date with Python 2.3. You can just install it in /usr/local and leave your previously installed Python alone. FWIW I, for one, would reject any patches that'd add Python < 2.1 compatibilty to my software. -- Gerhard From andrew-pythonlist at puzzling.org Mon Sep 15 21:48:21 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Tue, 16 Sep 2003 11:48:21 +1000 Subject: Web server with Python In-Reply-To: References: <6o24mvcmksid33t4s9b8cbsrnctl5n2o6m@4ax.com> Message-ID: <20030916014821.GB4093@frobozz> On Mon, Sep 15, 2003 at 08:18:25PM +0200, Patrick Useldinger wrote: > On Sun, 14 Sep 2003 15:43:30 +1000, Andrew Bennetts > wrote: > > > >Eek! Does 1.0.7 (just released) work any better? Also, what platform are > >you using, and are you installing from the source .tar.gz or something else? > > I didn't try 1.0.7, didn't even know that it was out. > I am on a WinXP box and used the prebuild binaries. Ah, ok. The prebuild binaries for Windows only work on one version, and I think the Windows maintainer has chosen to only support 2.2. You're welcome to build your own from the source, or try to convince someone on IRC to build 2.3 binaries for you ;) Also, you don't need a compiler to use Twisted. The C extensions are entirely optional, and just provide some optimisations over some of the equivalent pure python modules, but most users would probably never notice the difference. > I have started digging into Medusa right now... and stay focused on > that one until I have a blocking problem or I get bored ;-) We'll be waiting ;) -Andrew. From robin at jessikat.fsnet.co.uk Fri Sep 12 07:39:53 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 12 Sep 2003 12:39:53 +0100 Subject: Reportlab Image object opens filehandles References: Message-ID: In article , Michael Schmitt writes >Hello. > >I am trying to build a pdf document using: >--- >from reportlab.platypus.flowables import Image >lst = [] >for filename in imageFiles: > I= Image(filename, width= 300, height= 300) > lst.append(I) >--- >Creating an Image object seems to open a filehandle, so if the size of >imageFiles increases, I get "IOError: [Errno 24] Too many open files" on a >Solaris machine, where the number of simultaneously opened filehandles >seems to be limited to roughly 255. > >Is there a way to produce a pdf document with a large number of images >without running into the problem of too many open filehandles? > >Thanks for any hints. >Michael > > I have implemented an attempt at a lazy platypus Image, but haven't time to test it right now. If you contact me I can send it you directly. -- Robin Becker From hanzspam at yahoo.com.au Mon Sep 15 04:33:06 2003 From: hanzspam at yahoo.com.au (=?ISO-8859-1?Q?Hannu_Kankaanp=E4=E4?=) Date: 15 Sep 2003 01:33:06 -0700 Subject: Finally found a use for lambda! References: Message-ID: <840592e1.0309150033.3622d1f9@posting.google.com> Roy Smith wrote in message news:... > My apologies for a somewhat silly posting, but after 6 years of hacking > Python, I finally found a use for lambda! I wanted to write a unit test > to prove that a given dictionary does not have a given key. Since > assertRaises requires its second argument to be something callable, > instead of writing: > > self.assertRaises (KeyError, foo['bar']) > > I had to write: > > self.assertRaises (KeyError, lambda: foo['bar']) > > Of course, now that I think about it, I could have also written: > > self.assertEqual (foo.has_key ('bar')), 0) > > so I guess I didn't really need the lambda after all :-) Lambda is pretty useless in Python, unfortunately. List comprehensions reduce their uses with filter and map, and any more complex closure has to be written as a named function anyway.. I wish lambda would allow statements in them also, so I could do func(lambda x: arr[x] = y) Little closures like that are sometimes handy. But having to do def fn(x): arr[x] = y func(fn) is not too much of a burden. Lambda would be just nicer. The current use I've had for lambda has been similar to yours. I wanted a separate thread to initialize something in a class on the background, so I did something like threading.Thread(target=lambda: self.doSomething(a, b, c)).start() I think I've used it elsewhere too but I don't have my sources here. From godoy at metalab.unc.edu Tue Sep 30 19:06:25 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 30 Sep 2003 20:06:25 -0300 Subject: Threading and Windows. References: <6ojo41-424.ln1@beastie.ix.netcom.com> <8hpo41-m84.ln1@beastie.ix.netcom.com> Message-ID: Dennis Lee Bieber writes: > Jorge Godoy fed this fish to the penguins on Tuesday 30 September 2003 > 09:01 am: > >> >> The most interesting thing is that I get an error in Windows but I >> don't get such an error in Linux. >> > spawnv() is probably a direct match with a unix/linux system call, so > the arguments are just being passed on -- and what linux does when it > gets the address of a string where it expected an integer constant is > unknown to me (probably sees the address /as/ the integer, and since > P_WAIT is 0, the runtime is treating any non-zero to be the equivalent > of P_NOWAIT) The behaviour of treating it as nonzero would be expected. What happens is the opposite of that as I described before: the program hangs as if it received P_WAIT. I think that they check explicitly for P_NOWAIT and treat anything different as zero (P_WAIT). The principle of least surprise was violated, IMVHO as a newbie on that area. :-) See you, -- Godoy. From jjl at pobox.com Mon Sep 22 18:42:57 2003 From: jjl at pobox.com (John J. Lee) Date: 22 Sep 2003 23:42:57 +0100 Subject: string.rstrip References: <731fc603.0309221414.78a92789@posting.google.com> <3F6F7709.5EA37011@alcyone.com> Message-ID: <87zngwxx5a.fsf@pobox.com> Erik Max Francis writes: [...] > You're using .rstrip incorrectly. The second argument to string.rstrip > is a list of characters, any one of which will be stripped if they are [...] Erik means 'a sequence of characters', of course, not a list. John From tim.hochberg at ieee.org Mon Sep 29 19:55:21 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Mon, 29 Sep 2003 16:55:21 -0700 Subject: Prime number module In-Reply-To: References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> Message-ID: Lulu of the Lotus-Eaters wrote: > Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote previously: > |I just wrote a fairly simple sieve, which gave primes up to 1,000,000 > |in a few seconds (1.8GHz P4, Python code). There were 78498 primes in > |that range...at least in theory there should be less than 100 times as > |many primes in the range up to 10^8. > > Quite a few less, actually. Under Gauss' Prime Number Theorem, an > approximation for the number of primes less than N is N/ln(N). I know > there have been some slight refinements in this estimate since 1792, but > in the ranges we're talking about, it's plenty good enough. > > So I only expect around 5,428,681 primes less than 10^8 to occur. Well, > that's not SO much less than 7.8M. > > |So here's the thought - a binary file containing a complete list of > |primes up to 10^8 would require roughly 30MB (using 32 bit integers, > |which should comfortably handle your requirement). > > I wonder if such a data structure is really necessary. Certainly it > produces a class of answers quite quickly. I.e. search for a prime, and > its offset immediately gives you the number of primes less than it. > Heck, searching for any number, even a composite occurring between > primes, works pretty much the same way. Of course, the above > approximation gives you a close answer even quicker. > > But if you are worried about disk storage, one easy shortcut is to store > a collection of 16-bit differences between successive primes. That's > half the size, and still lets you answer the desired question *pretty* > quickly (extra addition is required)... or at least generate a local > copy of Horne's data structure in one pass. > > Moving farther, even this gap structure is quite compressible. Most > gaps are quite a bit smaller than 65536, so the highbits are zeros. In > fact, I am pretty sure that almost all the gaps are less than 256. So > an immediate compression strategy (saving disk space, costing time to > recreate the transparent structure) is to store gaps as 8-bit values, > with a x00 byte escaping into a larger value (I guess in the next two > bytes). > > Maybe I'll try it, and see how small I can make the data... unless I do > my real work :-). I believe you could implement a hybrid scheme that would be quite fast and still maintain nearly the same level of compression that you describe above. In addition to the above compressed data, also store, uncompressed, every Nth prime. A binary search will get you within N primes of your answer, to find the exact value, recreate those N-primes. For a N of, for instance, 64 the level of compression would be minimally affected but should make finding the number of primes less than a given number number much faster than the basic compressed scheme. In fact I wouldn't be suprised if this was faster than the uncompressed scheme since you're less likely to thrash your memory. -tim > Yours, Lulu... > > -- > Keeping medicines from the bloodstreams of the sick; food from the bellies > of the hungry; books from the hands of the uneducated; technology from the > underdeveloped; and putting advocates of freedom in prisons. Intellectual > property is to the 21st century what the slave trade was to the 16th. > > From FBatista at uniFON.com.ar Mon Sep 22 17:28:48 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 22 Sep 2003 18:28:48 -0300 Subject: Calling functions before that are def'ed Message-ID: #- Is there a way to define functions after the main part of a Python #- script? You don't need this. I wanted the same thing when started with Python (came from C), but this implies a poorly modular design. Better: #!/usr/bin/env python def mymain(...): ... def func1(...): ... def func2(...): ... def func3(...): ... def func4(...): ... # This is the main part #Very few basic controls about argv, etc... ... ... mymain(...) And consider that you're not programming OO. . Facundo From max at ucmg.com.ua Wed Sep 3 03:51:20 2003 From: max at ucmg.com.ua (Max Ischenko) Date: Wed, 03 Sep 2003 10:51:20 +0300 Subject: Interoperability between VB and Python under ASP Message-ID: Hi, I've started to develop under Microsoft ASP framework, which allows different lang. used in a ActiveX page. I wonder about possible strategies to use Python modules from VBScript <%%> includes. Right now I'm thinking about this approaches: - create a COM server in Python to be able to call it from VB. Drawbacks: cumbersome and (probably) slow. - pure data exchange. Python code sets some data in global env. that is afterwards read by VB. Drawbacks: very limited in nature. - convert all VB pieces that need access to Python modules into Python. Have I missed something or could anyone comment on this? Discussion is wellcomed. -- Regards, Max. From ask at me.com Thu Sep 11 14:54:46 2003 From: ask at me.com (Greg Krohn) Date: Thu, 11 Sep 2003 18:54:46 GMT Subject: OT: Americans love their guns References: <000d01c37870$181e6020$0c02a8c0@Arts> Message-ID: "Geoff Gerrietts" wrote in message news:mailman.1063297012.18608.python-list at python.org... > I think that /your freedom/ ends where /my freedom/ begins. Until you > can guarantee that your weapon will not be used against me by your > family members or the conqueror thereof, your freedoms to shoot what > you want as a hobbyist and to exercise catastrophically lethal force > in home defense are not compelling arguments. What freedom of yours does me owning a gun infringe on? Your right not to worry? (I've rewritten that 100 times and it still sounds funny gramatically. I appologise.) greg From wilkSPAM at OUTflibuste.net Thu Sep 18 03:28:06 2003 From: wilkSPAM at OUTflibuste.net (Wilk) Date: Thu, 18 Sep 2003 09:28:06 +0200 Subject: Simple python cgi question References: <87llsnmrw4.fsf@flibuste.net> <87znh3411g.fsf@flibuste.net> <3sScnYrZ8I14cvWiXTWc-w@speakeasy.net> Message-ID: <871xuea73t.fsf@flibuste.net> Stephen Boulet writes: > I don't want report lab since I'll be using lilypond to generate the > pdfs (I mentioned that I'd be calling the pdf generating program from > python). > > What I needed to know was how to upload a file, really. I thought it > might be trivial, but maybe not so ... Yes it's trivial, you'll retreive the file with cgi.FieldStorage(), you'll pass it to your local app with popen (a pipe) and retreive the pdf with the pipe or open (a file), control the size of the buffer and send the result with print. Before, you'll print the right header content-type: application/pdf bye -- William Dode - http://flibuste.net From jroznfgre at jngpugbjreQBGbet.cy Mon Sep 15 06:49:19 2003 From: jroznfgre at jngpugbjreQBGbet.cy (JZ) Date: Mon, 15 Sep 2003 12:49:19 +0200 Subject: caching the sql queries Message-ID: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> Is there any equivalent of caching sql queries for Python like ADOdb for PHP? (For those who did not hear about ADODb and its feature : http://phplens.com/adodb/caching.of.recordsets.html) -- JZ From sancho-fx1 at gmx.de Wed Sep 10 04:54:51 2003 From: sancho-fx1 at gmx.de (marcus b.) Date: Wed, 10 Sep 2003 10:54:51 +0200 Subject: java pythpn extension (JPE) download fails Message-ID: Hi, I'm trying to get a current version of the java python extensin (JPE), but the the link on http://jpe.sourceforge.net/ (http://sourceforge.net/project/shownotes.php?release_id=60438) is not working. I searched the web to get some other source of download, but everyone seems referring to this site. Has anyone sucessfully downloaded this JPE recently? Any hint how to get JPE would be very nice..! Greetings Marcus From cygwin-help at cygwin.com Fri Sep 5 12:44:07 2003 From: cygwin-help at cygwin.com (cygwin-help at cygwin.com) Date: 5 Sep 2003 16:44:07 -0000 Subject: ezmlm response Message-ID: <1062780247.22135.ezmlm@cygwin.com> Hi! This is the ezmlm program. I'm managing the cygwin at cygwin.com mailing list. Acknowledgment: The address python-list at python.org was not on the cygwin mailing list when I received your request and is not a subscriber of this list. If you think you've unsubscribed, but continue to receive mail, please check the following URL for help: http://sources.redhat.com/lists.html#unsubscribe-full-addr-unknown This URL will lead you to information which will enable you to unsubscribe. --- Administrative commands for the cygwin list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: To remove your address from the list, send a message to: Send mail to the following for info and FAQ for this list: Similar addresses exist for the digest list: To get messages 123 through 145 (a maximum of 100 per request), mail: To get an index with subject and author for messages 123-456 , mail: They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: To stop subscription for this address, mail: In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at cygwin-owner at cygwin.com. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: Received: (qmail 22120 invoked from network); 5 Sep 2003 16:44:04 -0000 Received: from unknown (HELO manatee.mojam.com) (199.249.165.175) by sources.redhat.com with SMTP; 5 Sep 2003 16:44:04 -0000 Received: from montanaro.dyndns.org (titan.itcs.northwestern.edu [129.105.214.230]) by manatee.mojam.com (8.11.6/8.11.6) with ESMTP id h85GhwM14100 for ; Fri, 5 Sep 2003 11:43:58 -0500 Received: from montanaro.dyndns.org (localhost [127.0.0.1]) by montanaro.dyndns.org (8.12.9/8.12.2) with ESMTP id h85Gi2Gp029963 for ; Fri, 5 Sep 2003 11:44:02 -0500 (CDT) Received: by montanaro.dyndns.org (8.12.9/8.12.2/Submit) id h85Gi25F029960; Fri, 5 Sep 2003 11:44:02 -0500 (CDT) From: Skip Montanaro MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <16216.48466.365698.9787 at montanaro.dyndns.org> Date: Fri, 5 Sep 2003 11:44:02 -0500 To: cygwin-uc.1062700471.nellflaigclagldbcadg-python-list=python.org at cygwin.com Subject: Re: confirm unsubscribe from cygwin at cygwin.com In-Reply-To: <1062700471.12028.ezmlm at cygwin.com> References: <1062700471.12028.ezmlm at cygwin.com> X-Mailer: VM 7.14 under 21.5 (beta9) "brussels sprouts" XEmacs Lucid Reply-To: skip at pobox.com From lupan at zamek.gda.pl Tue Sep 16 14:15:30 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Tue, 16 Sep 2003 20:15:30 +0200 Subject: tuples vs lists References: Message-ID: <8765jsppkt.fsf@psi.lupan.zamek.gda.pl> "Ivan Voras" writes: > Are there any performance/size differences between using tuples and using > lists? > I made the timings of creation/unpacking/indexing for short tuples/lists and loops for longer tuples/lists. In Python 2.1, 2.2 and 2.3 creation and unpacking of short tuples is 2x/3x faster which is what you may expact knowing they are fixed size, but indexing is slightly slower for tuples which I didn't expect. Whether you loop over tuple or list does matter only for 2.2 (tuples are 30% slower). Where there is 2x difference or 30% difference it is reproducable in subsequent runs of of the script given below. lupan at psi:[~/dyplom/src]$ sh tuple-vs-list.sh 2.1 creation tuple 1000000 loops, best of 3: 0.442 usec per loop list 1000000 loops, best of 3: 1.1 usec per loop unpacking tuple 1000000 loops, best of 3: 0.58 usec per loop list 1000000 loops, best of 3: 1.23 usec per loop indexing tuple 1000000 loops, best of 3: 0.369 usec per loop list 1000000 loops, best of 3: 0.339 usec per loop looping tuple 10000 loops, best of 3: 170 usec per loop list 10000 loops, best of 3: 173 usec per loop 2.2 creation tuple 1000000 loops, best of 3: 0.341 usec per loop list 1000000 loops, best of 3: 0.96 usec per loop unpacking tuple 1000000 loops, best of 3: 0.457 usec per loop list 1000000 loops, best of 3: 1.09 usec per loop indexing tuple 1000000 loops, best of 3: 0.286 usec per loop list 1000000 loops, best of 3: 0.264 usec per loop looping tuple 10000 loops, best of 3: 149 usec per loop list 10000 loops, best of 3: 114 usec per loop 2.3 creation tuple 1000000 loops, best of 3: 0.286 usec per loop list 1000000 loops, best of 3: 0.672 usec per loop unpacking tuple 1000000 loops, best of 3: 0.387 usec per loop list 1000000 loops, best of 3: 0.761 usec per loop indexing tuple 1000000 loops, best of 3: 0.204 usec per loop list 1000000 loops, best of 3: 0.19 usec per loop looping tuple 10000 loops, best of 3: 74.6 usec per loop list 10000 loops, best of 3: 76.3 usec per loop # tuple-vs-list.py TIMEIT=/usr/lib/python2.3/timeit.py # they are big as I have fast machine N=1000000 N2=10000 for ver in 2.1 2.2 2.3; do echo $ver echo -ne 'creation\ntuple ' python$ver -O $TIMEIT -n $N '(1,2,3)' echo -n 'list ' python$ver -O $TIMEIT -n $N '[1,2,3]' echo -ne 'unpacking\ntuple ' python$ver -O $TIMEIT -n $N 'a,b,c = (1,2,3)' echo -n 'list ' python$ver -O $TIMEIT -n $N 'a,b,c = [1,2,3]' echo -ne 'indexing\ntuple ' python$ver -O $TIMEIT -n $N -s 'x = (1,2,3)' 'x[1]' echo -n 'list ' python$ver -O $TIMEIT -n $N -s 'x = [1,2,3]' 'x[1]' echo -ne 'looping\ntuple ' python$ver -O $TIMEIT -n $N2 -s 'r = tuple(range(1000))' 'for x in r: pass' echo -n 'list ' python$ver -O $TIMEIT -n $N2 -s 'r = range(1000)' 'for x in r: pass' done -- =*= Lukasz Pankowski =*= From bokr at oz.net Sat Sep 27 13:20:44 2003 From: bokr at oz.net (Bengt Richter) Date: 27 Sep 2003 17:20:44 GMT Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: On Sat, 27 Sep 2003 09:47:47 +0100, Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: >On Fri, 26 Sep 2003 14:44:30 +0200, Ronald Oussoren > wrote: > >>The fun you can have on windows, I've >>managed to create files that cannot be removed :-) > >I've had that one simply by saving a web page in IE. Seriously >annoying. > Do you mean windows exploder will not even delete it with right-click, delete? Or doesn't it show up at all? (how do you know it exists? dos dir?) Regards, Bengt Richter From ads at chead.org Wed Sep 17 05:42:44 2003 From: ads at chead.org (ads) Date: Wed, 17 Sep 2003 16:42:44 +0700 Subject: GTK help Message-ID: <215410979.20030917164244@chead.org> I use PYGTK 2.0.0 for python 2.3 and GTK Runtime 2.2.4 under windows98 --------------- Replied message -------------- The Bat! mailer ver 1.53d ---------------------------------------------- Date : Wednesday, September 17, 2003 >From : David M. Cook To : python-list at python.org Subject : GTK help ---------------------------------------------- In article , ads wrote: > I need some help, whe trying to run some gtk examples, show below > messages: [...] > store = gtk.ListStore(StockItemInfo) > TypeError: could not get typecode from object > It show up when I run pygtk\examples\pygtk-demo\demos\stock_browser.py Which versions of pygtk and gtk are you using? Dave Cook -- http://mail.python.org/mailman/listinfo/python-list ---------------------------------------------- From gandreas at no.reply Mon Sep 29 15:16:12 2003 From: gandreas at no.reply (Glenn Andreas) Date: Mon, 29 Sep 2003 14:16:12 -0500 Subject: A startup puzzle References: Message-ID: In article , "Edward K. Ream" wrote: > I've just about convinced myself there is no good, clean solution to the > following puzzle. I wonder if you agree. [snip] > For example, doing the following at the top of leoGlobals doesn't work: > > import leoApp > app = leoApp.leoApp() # construct the app instance. > > Indeed, the leoApp module will be imported before the assignment of app. > Moreover, the leoApp module does other imports, and all the app variables in > those modules will be uninitialized. > > It would be horrible style to place detailed constraints on the order in > which modules get imported, and I'm not sure even that would work. > > Any ideas for a clean solution? Thanks. Maybe I'm missing something, but it seems like you want some sort of lazy initialization thing here. Perhaps using a proxy object sort of like this might work: realApp = None class LeoProxy: def __getattr__(self,attr): if not realApp: import leoApp realApp = leoApp.leoApp() return getattr(realApp, attr) app = LeoProxy() Then you can import that module as often as you want, but the first time you do something with leoApp.app (i.e., "leoApp.app.doSomething()"), it will only then call the "real" function to create it (and then proxy it over as needed) From edreamleo at charter.net Wed Sep 3 09:09:35 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 3 Sep 2003 08:09:35 -0500 Subject: Writing solid code book References: Message-ID: > there is another famous book 'Writing solid code' but does it apply to > Python ? Or it's usable only by Microsoft C programmers ? The author > seems to be an ex-Microsoft guy ! Interesting question. This book probably makes a good indirect case for using Python rather than C. I found it useful back when I was I C programmer. Python makes many of the points in the book moot, and the last chapter on attitude applies universally. For example, assertions are much less useful in Python because the interpreter essentially asserts many properties of each statement. In Python one wants assertions only for conditions that the interpreter can't possibly deduce. BTW, back when I was a C programmer the book "Code Complete" would have been a complete answer to the question, "what do you do?" It's still relevant, I would guess. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From zanesdad at bellsouth.net Thu Sep 11 10:42:56 2003 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 11 Sep 2003 10:42:56 -0400 Subject: GET and POST In-Reply-To: ; from opo@opo.com on Thu, Sep 11, 2003 at 03:58:52PM +0200 References: Message-ID: <20030911104256.B32566@cerberus.liberty> * franck (opo at opo.com) wrote: > HI, > > this is my code > params = {} > > params['fuseaction'] = '*****'; > params['user'] = '***'; > params['password'] = '**********'; > params['num_card'] = '******'; > params['date_of_birth'] = '****'; > > params = urllib.urlencode(params) > f = urllib.urlopen("http://bidule.com",params) According to the urllib documentation (I've never used urllib, only httplib), all you have to do is change: f = urllib.urlopen("http://bidule.com",params) to f = urllib.urlopen("http://bidule.com?%s" % params) Here is the example from the documentation for a GET (found at http://www.python.org/doc/current/lib/node415.html): >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params) >>> print f.read() I haven't whether this works or not, so I take no responsibility for any damage caused by this code ;-) Jeremy Jones From mike at nospam.com Thu Sep 4 13:44:23 2003 From: mike at nospam.com (Mike Rovner) Date: Thu, 4 Sep 2003 10:44:23 -0700 Subject: Where to post useful code References: <2e1f6497.0309040646.3dcce9fb@posting.google.com> Message-ID: RichB wrote: > I've written a few scripts that might be very useful to small groups > of people (i.e. extracting time stamps from pictures taken with Sony > digital cameras). > I don't want to start sourceforge projects or anything big like that. > I just want to make some stuff available. Where can I post/upload my > stuff? You have several options: - Python Cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python) which is a searcheble storage place with small discussion attached - PythonInfo Wiki (http://www.python.org/cgi-bin/moinmoin/HiddenJewels) which lets other people to extend your code and/or discuss it - Vaults of Parnassus (http://www.vex.net/parnassus/) which is most comprehensive but messy collection of python stuff referencies - Python Package Index (http://www.python.org/pypi) in case you promote your code to community useful package HTH, Mike From tzot at sil-tec.gr Mon Sep 29 21:19:31 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 04:19:31 +0300 Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: On Sat, 27 Sep 2003 17:22:41 GMT, rumours say that "Andrew Dalke" might have written: >BTW, the similarity-but-not-the-same between DOS and unix >caused me problems when I started using unix. See, under DOS >there's this great utility called "unerase" which can be used to >recover files accidentally deleted. Only I would deliberately >delete a file in order to probe the system; eg, is this file really >used? Safe wisdom: mv (move, ren for old DOS) would be better, right? >And I wanted to see if the script really used the C compiler.... > >Had to reinstall IRIX to fix that one. If 'inst same' wasn't enough, then that should have been a really old version of Irix... :( -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From jerome.vacher at gehis.fr Tue Sep 30 07:55:50 2003 From: jerome.vacher at gehis.fr (Jerrykhan) Date: 30 Sep 2003 04:55:50 -0700 Subject: Best Bug Tracker on Zope platform ? Message-ID: <62f2814b.0309300355.6091dd84@posting.google.com> Hello, who know the best Bug tracker system on a Python/Zope server ? BugZilla is Perl oriented (beuh !!) What about others ? Is A python oriented BugZilla like exists ? or need I write it ? On a zope one or behind an apache one. Any ideas ? Thanks .. JerryKhan the foolish dracomorpheus. From aahz at pythoncraft.com Mon Sep 15 16:53:48 2003 From: aahz at pythoncraft.com (Aahz) Date: 15 Sep 2003 16:53:48 -0400 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> Message-ID: In article , Harri Pesonen wrote: > >The point I was trying to make (not in this message but in general) is >that it would be simple (trivial but tedious) to create a version of >Python that is thread-safe, and the only reason it is not done is >because it would break old code. You're wrong. You have refused to do your research, and you have been ignoring information people provide to you. >Only one global variable left (in fact there is Py_None as well). You're wrong. There are only two global *C* variables -- but all Python objects are global. Most people want to share information between threads; as soon as that becomes a requirement, you run into *BIG* problems with refcounting and garbage collection when you do free threading. That doesn't even count the problem I mentioned earlier about interfacing with thread-unsafe libraries. Now, would you care to learn how Python actually works before making further pronouncements? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From jjl at pobox.com Sun Sep 7 18:23:24 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Sep 2003 23:23:24 +0100 Subject: Comments on Python Redesign References: <87vfs4mxgg.fsf@voodoo.fake> Message-ID: <873cf8jl0j.fsf@pobox.com> John Hall writes: > On Sun, 07 Sep 2003 17:26:23 +0200, Lawrence Oluyede > wrote: > > >Zeldman's post about the new version: > >http://zeldman.com/daily/0803a.shtml#validator > > > When I view _this_ site in IE6, it has low-contrast text in a small > size, which "view|text size" cannot change. Presumably they view that as an IE bug. John From max at alcyone.com Sat Sep 6 18:00:37 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 06 Sep 2003 15:00:37 -0700 Subject: Need help on UNICODE conversion References: <5lbklvgtlm6l4e1n51tnbin151drrh4410@4ax.com> Message-ID: <3F5A5905.9E8571E3@alcyone.com> Bernd Preusing wrote: > I have a JPG file which contains some comment as unicode. > > After reading in the string with s=file.read(70) from file offest 4 > I get a string which is shown as > 'UNICODE\\0x00\\ox00K\\0x00o' and so forth in the debugger > (using Komodo). As others have pointed out, this seems to be an unfaithful cut and paste; to really tell what it is we'd have to see the actual contents of the string. If it is really Unicode, however, it looks like it might be a UTF-16 encoding. Try 'utf-16' for the encoding name. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You're wasting time / Asking what if / You linger on too long \__/ Chante Moore From bgailer at alum.rpi.edu Thu Sep 25 21:42:37 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 25 Sep 2003 19:42:37 -0600 Subject: When did Windows start accepting forward slash as a path separator? In-Reply-To: References: Message-ID: <6.0.0.22.0.20030925194134.0279ad00@66.28.54.253> At 05:50 PM 9/25/2003, Stephen Ferg wrote: >I have a question that is not directly Python-related. But I thought >I'd ask the most erudite group that I know... :-) > >When did Windows start accepting the forward slash as a path separator >character? Good question. Certainly later than: Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. C:\>cd /samis The syntax of the command is incorrect. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From FBatista at uniFON.com.ar Tue Sep 23 11:40:38 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 23 Sep 2003 12:40:38 -0300 Subject: Try/except vs. if/else Message-ID: #- In my understanding, using try/except rather than if/else is more #- pythonic. However, sometimes it is difficult to use the later. It's more pythonic to use always the right tool for the problem. #- For example, I want to search for a sub string in a list composed of #- strings. It is considered "possitive" if there is a match, #- no matter how #- many. #- #- my_test = ['something', 'others', 'still others'] #- #- case 1: try/except #- #- hit = 0 #- for i in my_test: #- try: #- i.index('some') #- hit = 1 #- except ValueError: #- pass #- #- #- #- case 2: if/else #- #- hit = 0 #- for i in my_test: #- if 'some' in i: #- hit = 1 #- IMHO, better the case 2. One detail, stop the iteration when you have an ok (code untested): for i in my_test: if 'some in i: hit = 1 break else: hit = 0 . Facundo From jarrodhroberson at yahoo.com Sun Sep 7 22:17:24 2003 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 7 Sep 2003 19:17:24 -0700 Subject: python module for MS SQL Server 7 or 2000? References: Message-ID: Gerhard H?ring wrote in message news:... > Y2KYZFR1 wrote: > > I have searched and only found references to using ODBC or some > > ancient posts about some ancient sybase library under linux, neither > > of which meets my critiera. [...] > > Tried Google? Doesn't look like so: > > http://www.google.com/search?q=python%20ms%20sql%20server > > -- Gerhard yes and nothing meets my criteria. I need something that is stable and cross platform without any dependancies on any other libraries or depenacny on linux From mertz at gnosis.cx Wed Sep 3 13:17:59 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 03 Sep 2003 13:17:59 -0400 Subject: what's wrong with REBOL? (fwd) Message-ID: Jeff Epler wrote previously: |There are legal reasons: Perhaps the software will be found to violate |a patent, or infringe copyright. Perhaps it will be judged to violate a |DMCA-type law. Perhaps a new "software defects" law will be impossible |for free software to conform to (for instance, due to a requirement that |the software developer post a bond against damages caused by defects in |the software). Yeah... and perhaps the word 'disingenuous' will be removed from future editions of popular dictionaries; and then we will lack a concise way to describe "special pleading" of this sort. I think it's unlikely though. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From __peter__ at web.de Tue Sep 23 17:35:01 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Sep 2003 23:35:01 +0200 Subject: Newbie question, problem with functions References: <31bd93f0.0309231304.329c9589@posting.google.com> Message-ID: Rickard Karlsson wrote: > I have wrote this little program, that is supposed to execute eg. the > Linux ls command when you press a button. Te problem is that all the > commands are run automaticly and they won't run when I press the > associated button. Wath am I do wrong? [...] > b1 = Button(frame, text = "ls", command = self.execute('ls')) > b2 = Button(frame, text = "ls -alh", command = self.execute('ls > -alh')) > b3 = Button(frame, text = "pwd", command = self.execute('pwd')) [...] You are in fact passing the result of self.execute(...), i. e. None, instead of the method. Do b3 = Button(frame, text="pwd", command=lambda: self.execute('pwd')) instead or define wrapper methods like so: def executeLs(self): self.execute("ls") and assign them to the buttons without a trailing (), e. g.: b1 = Button(frame, text="ls", command=self.executeLs) Peter From mpeuser at web.de Thu Sep 11 10:10:09 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 11 Sep 2003 16:10:09 +0200 Subject: Tkinter Canvas/Grid question References: Message-ID: "Jeff Epler" Thank you for the comprehensive explanations you gave I was to lazy to do ;-) In addition I should like to point out a chapter from Nancy Walsh's book "Learning Perl/Tk" where one can find a lot of information about the different geometry managers (no prejudices against Perl I hope?) http://www.oreilly.com/catalog/lperltk/chapter/ch02.html > The other problem you may run into (I haven't run your code, but with > many levels of widget present, this may be a problem) is that each > level of the widget tree between this one containing the canvas, and the > Toplevel() or Tk() above it, must also be configured so that they will > expand to consume any extra available space This had been one of the problems, so I suggested to use an appropriate paramtrized pack on the higher level for simplicity. Kindly Michael P From peter at engcorp.com Wed Sep 24 17:32:07 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 24 Sep 2003 17:32:07 -0400 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: <3F71B857.2D1E3268@engcorp.com> <3F720759.34D7BD3E@engcorp.com> Message-ID: <3F720D57.485718EC@engcorp.com> Tim Hochberg wrote: > > Peter Hansen wrote: > > Chris Liechti wrote: > > > >>Peter Hansen wrote re: > >> > >>>PyThreadState_SetAsyncEnc > > > > > >>>Presumably somebody will come up with a little extension module or > >>>other technique for calling this which will let anyone use it at will, > >>>so I'm unclear on why it should be made inaccessible from Python. > >> > >>why bother with c, just use ctypes to call the function ;-) > > > > How would one do that? It would make for an easy way to experiment > > with it, in the 0.001% of cases where a non-newbie one might want to > > do such a thing. ;-) > > > > Is this function available in a DLL somewhere? I can't find even > > a single reference to that name anywhere in the Python23 directory > > tree on Win32 after a fresh install. > > It's here: > > http://starship.python.net/crew/theller/ctypes/ Sorry, Tim, I meant the PyThreadState_SetAsyncEnc function, not ctypes itself. :-) See my other posting, where I report I found it... -Peter From luc at nospam.invalid Fri Sep 19 15:37:06 2003 From: luc at nospam.invalid (luc wastiaux) Date: Fri, 19 Sep 2003 21:37:06 +0200 Subject: How do I learn operator overriding? References: Message-ID: On Fri, 19 Sep 2003 14:25:23 -0400, pytho wrote: > Hi- > > > I need to make a class for quartlerly dates. I need to be able to compare > two quarterly dates and get the number of quarters between them. For > example: > >>>> 2001q1 = qDate(year=2001, quarter=1) >>>> 2001q4 = qDate(year=2001, quarter=4) >>>> 2001q4 - 2001q1 > 3 > > The only problem is that I have no idea how to override operators in > python. Can anyone give me a few trivial examples of how it is done? in your class: def __sub__(self, mydate): # perform self - mydate # and return a new qdate object I can't reach www.python.org but there should be some documentation on operator overloading. Also, I recommend the book "learning Python" from O'reilly ( http://www.oreilly.com/catalog/lpython/ ) which covers most of the things you need to know about python. -- luc wastiaux email: luc-at-4002-dot-org jabber: luc at jabber.4002.org From rjc at tampabay.rr.com Tue Sep 30 17:28:21 2003 From: rjc at tampabay.rr.com (Robert Clayton) Date: Tue, 30 Sep 2003 21:28:21 GMT Subject: import _XXXXXX References: Message-ID: O.K. But in PyKyra most ever Python file begins with _pyKyra. "Skip Montanaro" wrote in message news:mailman.1064947483.21334.python-list at python.org... > > Robert> When a Python program declares import _XXXX. What form is XXXX > Robert> when the underbar is included (_XXX)? > > There's no special form. The leading underscore is there to alert people > they should not normally import that module directly. For example, people > should import bsddb, not _bsddb. Same goes for (the third part modules) > MySQLdb and _mysql. In both cases, the former builds on the latter. > > Skip > > > From aahz at pythoncraft.com Sun Sep 7 16:25:14 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2003 16:25:14 -0400 Subject: Comments on Python Redesign References: <3F5B8C51.6462BC38@alcyone.com> Message-ID: In article <3F5B8C51.6462BC38 at alcyone.com>, Erik Max Francis wrote: > >Could someone remind me what need there is for a redesign in the first >place? Of all the Python-related efforts that one could put time into, >this seems like one of the least useful. AMK's comment is a bit overdone, so here's something more understated: The current website has a number of navigation, structural, and content flaws resulting from the fact that it has grown organically for roughly a decade. It is also harder to maintain than we'd prefer. Finally, it looks a bit dated. While we are making some progress at removing cruft, most of us involved in the work agree that a full-scale redesign would be a Good Idea. Part of the impetus for doing the work is to streamline the site to make it easier for Python newcomers (and people investigating Python for themselves or their organizations) to find the information they want or need. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From jcribbs at twmi.rr.com Thu Sep 4 13:13:22 2003 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Thu, 04 Sep 2003 17:13:22 GMT Subject: ANNOUNCE: MojoView 1.0 Message-ID: MojoView 1.0 is now available at: http://www.netpromi.com/files/MojoView-1.0.zip What is MojoView? MojoView is a Python package that assists you in building simple gui database applications using PyGTK2. It consists of a set of classes that you can subclass in your application. Each class is either a dialog or a widget that should be placed inside a dialog, along with supporting code that handles a lot of the mundane details inherant in most gui database apps. I think that this package will mostly help those new to or unfamiliar with developing PyGTK2 applications. Experienced PyGTK programmers will have probably already developed their own libraries providing similar or better functionality. To find out more about MojoView, go to: http://www.netpromi.com/mojoview.html From skip at pobox.com Tue Sep 2 15:55:52 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 2 Sep 2003 14:55:52 -0500 Subject: Docs on speeding up Python code? In-Reply-To: References: Message-ID: <16212.62920.413196.374346@montanaro.dyndns.org> Andreas> Thanks for the answers. Really a very useful document. Like most other static pages, my fast python page: http://manatee.mojam.com/~skip/python/fastpython.html can quickly get out-of-date, and I don't have a lot of spare time to work on it. I'd be more than happy to set up a Wiki so the community can help maintain it. If you think you'd contribute something (however minor) if it was Wiki-fied, let me know. Skip From Dick.Zantow at lexisnexis.com Wed Sep 10 17:25:05 2003 From: Dick.Zantow at lexisnexis.com (rzed) Date: Wed, 10 Sep 2003 17:25:05 -0400 Subject: Heisenberg strikes again! References: Message-ID: neeson wrote: > Alright, I'm fairly new to Python, and this one has got me stumped. > I've just started to write a cli program that'll use readline, and > I've attached the relevant bits. > > Here's the mystery: If I so much as /look/ at the list 'matches', > readline stops working. Run the program, hit tab at the prompt, > you'll get 'one', which is incorrect, as there are in fact four > possible completions. Now comment out the line that I've marked > (which, incidentally, does nothing). /Now/ it works. > > Is there some very strange side effect to accessing a list element > that I'm unaware of? I've tried it in two different versions of > Python. > > Any elightenment would be appreciated... > > Heath > > ps In terms of being useful, this program doesn't make any sense. > I'm not trying to get it to work, I'm looking to understand why the > commented line affects the rest of the code. > > > #!/usr/bin/python > > import readline > import sys > > commands = ["one", "two", "three", "four"] > matches = [] > > def comp(text, state): > if state == 0: > matches = [] > n = len(text) > for cmd in commands: > if cmd[:n] == text: > matches.append(cmd) > throwaway = matches[0] # <--- Comment out this line What is supposed to happen when state != 0? 'matches' will not exist at that point. > return commands[state] > > readline.set_completer(comp) > readline.parse_and_bind("tab: complete") > > while 1: > try: > line = raw_input("> ") > except EOFError: > print "\n", > sys.exit() > print ": %s" % line From dkuhlman at rexx.com Mon Sep 1 17:09:12 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 01 Sep 2003 14:09:12 -0700 Subject: Structured writing to console, such as a table References: Message-ID: Raaijmakers, Vincent (IndSys, GE Interlogix) wrote: > Ok, perhaps a question on a newbie level. > > I try to create a simple 'write to a console application' where > all the items in a string do have a variable size: > items = ["a", "bbbbbbbbb", "cc"] > Well, actually, I need to print a table as simple text, nice lined > up in a console. So: > > > Item: Value: Another Value: > ----------+----------+------------------ > a | 1 | 2 > bbbbbbbbb | 2 | 17 > cc | 3 | 5 > > My hope was that somewhere in python land an existing module was > waiting for me. A module that also prints lines, headers.... > > Unfortunately, I can't find it. Books, Google... > Before I reinvent this wheel... please give me some tips, > references, examples... This is not a solution to your problem, but is something that you may want to know. Docutils and the reStructuredText that it processes support the kind of ASCII tables that you describe. You may want to check the Docutils/reStructuredText specification. If you follow that specification you will be able to send your tables through a Docutil tool to produces HTML, LaTeX, etc. Docutils, by the way, is implemented in Python. See: http://docutils.sourceforge.net/docs/rst/quickref.html#tables http://docutils.sourceforge.net/ https://sourceforge.net/projects/docutils/ Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From eppstein at ics.uci.edu Tue Sep 16 18:31:28 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 16 Sep 2003 15:31:28 -0700 Subject: scoping with lambda in loops References: <7f9e1817.0309161338.20fbdcbc@posting.google.com> Message-ID: In article <7f9e1817.0309161338.20fbdcbc at posting.google.com>, imcmeans at telus.net (Ian McMeans) wrote: > First, I made multiple lambda functions inside a loop, each of which > depended on the current loop variable. > > >>> a = [] > >>> for index in range(5): > a.append(lambda: index) > > > Now, see if you can guess what the output was for each of the > functions in the list a: > >>> a[0](), a[1](), a[2](), a[3](), a[4]() > I had expected it to be (0, 1, 2, 3, 4), but actually, it's: > > (4, 4, 4, 4, 4) > > This really surprised me. I guess what is happening is that each > lambda knows what the context of execution is where it was defined, > and doesn't actually evaluate until the function is called, and when > it does evaluate, it uses the current value of the variable. Is this > related to static scoping? It's related to closures. If you're using lambda, you're probably a lisp programmer, and should know all about closures. Creating a function object with def or lambda, within an outer function scope, creates a closure for that outer function call. The inner function's accesses to variables from the outer function will return the most-recently-updated binding from the closure. If you call the outer function again, you will get a different unrelated closure. If you the inner function to have its own local variable that stores some expression value as it existed at the creation time of the inner function, rather than re-evaluating the expression whenever the inner function is called, the standard way is to use a defaulted keyword parameter: a = [] for index in range(5): a.append(lambda index=index: index) or maybe more concisely a = [lambda index=index: index for index in range(5)] -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From tjreedy at udel.edu Mon Sep 1 12:36:52 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 1 Sep 2003 12:36:52 -0400 Subject: method (a, b = '', *c, **d): gets a syntax error? References: <3F4F644D.2060003@uni-bonn.de> <3dqcndZe5u2g4NKiXTWJiA@comcast.com> <-6-dnRcax4ZCW9KiXTWJkA@comcast.com> Message-ID: >(Gerrit Holl) Python 2.3 does the same. > > Python 2.3 (#1, Aug 5 2003, 14:13:25) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > 0 >>> zip(**(),) > File "", line 1 > zip(**(),) > ^ > SyntaxError: invalid syntax > 1 >>> def foo(**a,): pass > File "", line 1 > def foo(**a,): pass > ^ > SyntaxError: invalid syntax Thank you for the verification. I have submitted doc bug report SF 798652 >(Michael Hudson): Because that's what the grammar says After the grammer in 5.3.4 follows :"A trailing comma may be present after an argument list but does not affect the semantics. " I suggested instead "If an argument list does *not* end with *expr or **expr, a trailing comma may be added without affecting the semantics." I also suggested a change in 7.5 Function definitions to the production for parameter_list. >(Piet von Oostrum) [Explanation of why '**dic,)' should be error] I agree, which is why I filed as doc bug. Note >>> def fl(*lis,): pass File "", line 1 def fl(*lis,): pass ^ # points at ')' SyntaxError: invalid syntax The error is detected as ')' instead of ',' because **dic could have followed, but didn't. Terry J. Reedy From Harri.Pesonen at wicom.com Tue Sep 2 08:23:11 2003 From: Harri.Pesonen at wicom.com (Harri Pesonen) Date: 2 Sep 2003 05:23:11 -0700 Subject: Simple question: How to pass a C++ class reference to a callback? Message-ID: <17fbc98a.0309020423.11ac7b8d@posting.google.com> How do I pass the calling C++ class reference (or anything) to a callback? My code is: static PyObject* emb_Set(PyObject *self, PyObject *args) { char *key, *value; if(!PyArg_ParseTuple(args, "ss", &key, &value)) return NULL; // do something with the C++ class here // how the get the class instance pointer? Py_INCREF(Py_None); return Py_None; } static PyMethodDef EmbMethods[] = { {"Set", emb_Set, METH_VARARGS, "Sets the given variable."}, {NULL, NULL, 0, NULL} }; in C++ class: Py_Initialize(); Py_InitModule("test", EmbMethods); PyRun_SimpleString(script); Py_Finalize(); Harri From jjl at pobox.com Tue Sep 16 15:04:25 2003 From: jjl at pobox.com (John J. Lee) Date: 16 Sep 2003 20:04:25 +0100 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> Message-ID: <873cewy2py.fsf@pobox.com> hildegarde_roth at yahoo.de (Hilde Roth) writes: > This may have been asked before but I can't find it. If I have > a rectangular list of lists, say, l = [[1,10],[2,20],[3,30]], is > there a handy syntax for retrieving the ith item of every sublist? > I know about [i[0] for i in l] but I was hoping for something more > like l[;0]. If you need that kind of thing a lot, look at Numeric (or its replacement, numarray), or perhaps the standard library's array module. John From "mmoum[no-spam-please]" at woh.rr.com Sun Sep 21 22:06:14 2003 From: "mmoum[no-spam-please]" at woh.rr.com (mmoum[no-spam-please]) Date: Mon, 22 Sep 2003 02:06:14 GMT Subject: Where does sys.path get initialized Message-ID: Hi, Can anyone tell me where sys.path gets initialized? I know that I can import sys and then execute sys.path.append(pathname), but I'd prefer not to have to do that everytime I use PythonWin or Idle. I'm using Python on both Linux and Windows XP, and I suspect the process is different for each. Thanks in advance, Mike From duncan at NOSPAMrcp.co.uk Mon Sep 22 11:35:12 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 22 Sep 2003 15:35:12 +0000 (UTC) Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale related?)) References: Message-ID: Peter Otten <__peter__ at web.de> wrote in news:bkn12v$tns$06$1 at news.t-online.com: > My first idea was to add a .dsu(mapping) where the tuples in the > decoration phase would be generated as (mapping(item), item). Note that if anyone proposes this seriously, it should generate a 3-tuple (mapping(item), index, item) rather than the 2-tuple you suggest. This is because the mapping function could reasonably be used to impose an ordering on objects that have no natural order, so you need to be sure that the comparison never falls through the the original object even where the mapping compares equal. It also has the side effect of making the sort stable (although if stability is a goal you might want another option to reverse the sort which would use '-index' as the second element and call .reverse() on the result). FWIW, I think something like this belongs in the standard library rather than as a method on lists or a new builtin. -- 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 mwilson at the-wire.com Mon Sep 22 11:30:44 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 22 Sep 2003 11:30:44 -0400 Subject: Display message while running... References: Message-ID: In article , c42 wrote: >I'm writing a script that needs a message not to touch the screen while >it runs. (Windows NT/2K/XP) >I tried win32api.messagebox, but this stops the program until someone >clicks on OK. (A response (ie. "OK") is not required.) >Any suggestions? I guess the usual messagebox runs modally, meaning the program that runs it stops while the message is displayed. I don't know if there's a non-modal equivalent, If not, cobble up a Dialog and display it using Show for as long as you need. (Can't be more specific, as I only know wxWindows.) Regards. Mel. From schwerdy at web.de Thu Sep 11 04:08:05 2003 From: schwerdy at web.de (schwerdy) Date: 11 Sep 2003 01:08:05 -0700 Subject: file.close() freezes my script References: Message-ID: Thank you for your answer Bob Halley wrote in message > This sounds like a classic pipe deadlock. I didn't have the time so far to do a workaround, but I'll report if I fixing succeeds. Thanks again! Schwerdy From martin at v.loewis.de Thu Sep 11 16:43:19 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 11 Sep 2003 22:43:19 +0200 Subject: tkinter, sockets and threads together References: <79ad5955.0309111133.5f6bf26f@posting.google.com> Message-ID: juliagoolia301 at hotmail.com (Julia Goolia) writes: > i read that it is bad to use threads with tkinter. so my question is > how does one create a gui program with sockets? at one point you have > to call mainloop() which does not return. then you are not free to do > stuff with the sockets. > > what's up with that? On Unix, you can use Tk file handlers for sockets, i.e. have Tcl select(2) not only on the connection to the X11 server (which is a socket itself), but also select on your sockets. This is readily supported in _tkinter. On Windows, you have no choice but to use threads. If the socket processing threads have no relationship to the Tk thread, everything is fine. However, in many cases, interaction of some kind is needed. In this case, it is ok to call Tk methods from other threads, as long as they translate to "fast" commands, i.e. commands that only modify state, but don't block - you should not run the mainloop in multiple threads. Regards, Martin From eric.brunel at pragmadev.com Fri Sep 12 03:53:08 2003 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 12 Sep 2003 09:53:08 +0200 Subject: gdmodule clipping References: Message-ID: John Hunter wrote: > Does gd lib or gdmodule support clipping? I would like to set a clip > rectangle and when I issue drawing commands (like im.polygon) have > only the part of the polygon inside the clip rectangle displayed. AFAIK, gd doesn't support it natively. But since your clipping region seems to be a rectangle, I suppose you could do this by creating a new image having the size of your clipping region, draw in this image, then put it back in your main image via image.copyTo(...) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jcsisko at openlinksw.co.uk Tue Sep 23 13:00:53 2003 From: jcsisko at openlinksw.co.uk (Jan Csisko) Date: 23 Sep 2003 10:00:53 -0700 Subject: DB2 driver for windows References: <3f6cc89b$0$1122$6c56d894@feed0.news.be.easynet.net> <3f6f6c4c$0$1115$6c56d894@feed0.news.be.easynet.net> Message-ID: <998aac6a.0309230900.26942d6b@posting.google.com> Hi Philip, please note that the Drivers available at http://www.openlinksw.com will provide you with JDBC as well as ODBC access to DB2 from almost any OS. Hth, Regards, Jan Philip wrote in message news:<3f6f6c4c$0$1115$6c56d894 at feed0.news.be.easynet.net>... > Dave Benjamin wrote: > > > In article <3f6cc89b$0$1122$6c56d894 at feed0.news.be.easynet.net>, Philip > > wrote: > >> i'am looking for a db2 driver for windows > >> the DB2 servers runs on as400 if that makes any difference. > > > > I don't know if you're looking for a native driver, but if you can work > > with ODBC, I was able to get DB2's ODBC driver (the one that comes with > > the DB2 client installation) to talk to the mx.ODBC module. > > > > http://www.egenix.com/files/python/mxODBC.html > > > > Currently i'am using jython for database administration (because didn't find > an native driver) > > I like the java jdbc driver because you don't need to install anything > especialy interesting when sharing code) > > But the downside is that you have the java tiresome api. the obvious reason > way i have choicen python/jython. > > Well, prefer a native one but if it's easy to install the odbc driver > that would be fine too. > > Thanks, > Philip From adechert at earthlink.net Tue Sep 16 18:58:32 2003 From: adechert at earthlink.net (Alan Dechert) Date: Tue, 16 Sep 2003 22:58:32 GMT Subject: MORE volunteers for voting project needed Message-ID: A couple of months ago, I posted a call for volunteers on C.L.PY for our demo voting system development project (open source Python on SourceForge). I am very pleased with the result so far. We have some excellent developers to go along with some top notch experts in voting technology we have on board. David Mertz has taken the Development Lead position. We still have a need for a few people to take charge of some sub-projects. We had originally targeted the demo completion around mid-Oct. It looks like that will slip some but I hope to keep it from slipping too much. The need for better voting technology is fairly urgent! If you are interested, please have a look at what we are doing. Mostly we need Python developers but we also need someone skilled at project management and that can do a PERT chart (or Gantt chart) -- this person does not need to be a Python programmer. Here are our pages on SourceForge: http://evm2003.sourceforge.net The Architecture document may be of particular interest. You can take the link on this page or go directly to http://evm2003.sourceforge.net/architecture.html Most of our interaction is taking place on our email list. The archives are here: http://gnosis.python-hosting.com/voting-project/ Here's our other SF page http://sourceforge.net/projects/evm2003 More background information can be found here: http://home.earthlink.net/~adechert/ Our crew is international! Besides USA, we have programmers from India, Italy, and Sweden. Please get in touch with me if you are interested in helping with this project. -- Alan Dechert 916-791-0456 adechert at earthlink.net From peter at engcorp.com Tue Sep 16 07:33:42 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Sep 2003 07:33:42 -0400 Subject: was: Re: looking for MOP documentation References: <3F62123C.F671D058@engcorp.com> <3F6319E9.4C7BAA0F@engcorp.com> Message-ID: <3F66F516.3D06D946@engcorp.com> Ng Pheng Siong wrote: > > According to Peter Hansen : > > kasper graversen wrote: > > > On Fri, 12 Sep 2003 14:36:44 -0400, Peter Hansen wrote: > > > >> Erm, what's "MOP" mean? > > > what has all this talk to do with documentation of the MOP??? > > Er, if you'll look back, you'll see that Anthony asked what MOP > > meant > > Meta Object Protocol. Thanks, but one might say that this is what it spells, not what it _means_. At this point, I'm sure google would help, if I felt a driving need to go and learn what it really means. -Peter From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 24 13:17:49 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 24 Sep 2003 18:17:49 +0100 Subject: Thoughts on PEP315 References: <6qad8u1oiv.fsf@salmakis.intevation.de> Message-ID: On Wed, 24 Sep 2003 12:14:48 +0200, Bernhard Herzog wrote: >I think someone once suggested "and while" instead of a plain while: > >do: > ... >and while condition: > ... > >This reads quite nicely IMO. Hmmm. It certainly has all the advantages I claimed for 'break if'. At the moment my mental parser is choking on it - but I can't give a good reason why. Probably it's just odd seeing 'and' at the start of a line, I suspect. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From pbhowmick at sbcglobal.net Tue Sep 16 15:13:57 2003 From: pbhowmick at sbcglobal.net (Partho Bhowmick) Date: Tue, 16 Sep 2003 19:13:57 GMT Subject: Missing python23_d.lib in Windows Python 2.3 Message-ID: I am building extension modules for Python 2.3 under Windows using MS Visual Studio .Net 2003. In the debug build, there is a pragma statement in that causes a link to the lib python23_d.lib This library does not exist. Am I missing something or is the installation missing something? From bogus at invalid.tld Fri Sep 19 13:36:35 2003 From: bogus at invalid.tld (Jules Dubois) Date: Fri, 19 Sep 2003 11:36:35 -0600 Subject: \r for newline in readlines function References: Message-ID: <1j8xu75qycwmf$.1e7h5ve1avjxu$.dlg@40tude.net> On Fri, 19 Sep 2003 12:37:42 -0400, in article , Leeds, Mark wrote: > I did more investigation into my previous problem > and what happens is that my text file has \r for representing > a new line instead > of a \n. If you open a file in text mode, you're probably getting text as the implementation library or operating system view it. Under MS-DOS and derivative system (e.g., Windows), text files are stored with CRLF as the line delimiter but are returned to the program without the CR. Under MacOS text files use CR as the delimiter, and under Unix, LF. > is there a way to tell the readlines > function that the symbol for a newline is \r rather > than \n ? I think this is proper behavior, and the problem lies in the combination of file format and the operating system under which you're executing. A simple but inefficient solution is the write your own input function to read the file one character at a time and handle characters like CR and LF in a manner suitable to your requirements. From jonah13579 at hotmail.com Mon Sep 15 12:08:02 2003 From: jonah13579 at hotmail.com (Jonah) Date: 15 Sep 2003 09:08:02 -0700 Subject: Is there a web templating system like ruby's amrita ? References: <6ee58e07.0309120421.622cb55@posting.google.com> Message-ID: <9a5f3d1c.0309150808.62753710@posting.google.com> llothar at web.de (Lothar Scholz) wrote in message news:<6ee58e07.0309120421.622cb55 at posting.google.com>... > I there anything that completely avoid the use of python code inside > a template. I like the Amrita system because it allows me to design > the templates with WYSIWYG editors and blind text. I too, would appreciate any insight to this question. I come from a perl background, and now split my work about 50/50 between python and perl. The one area which I continue to use perl is for templating purposes. I think Template Toolkit is the best one out there (especially for MVC purposes), and would love to use something equivalent in python. There had been talk of porting that module to python (and even parrot), but AFAIK its still perl only. Jonah From rob at cs.brown.edu Mon Sep 29 01:49:59 2003 From: rob at cs.brown.edu (Rob Hunter) Date: Mon, 29 Sep 2003 01:49:59 -0400 Subject: isNumber? check In-Reply-To: Message-ID: How do I check if a value is a number in Python? One way is (x == type(1)) and (x == type(1.2)) and (x == type(2387482734274)) and ... but this seems kludgy. Any better way? Thanks, Rob From dokaspar at student.ethz.ch Tue Sep 30 14:57:17 2003 From: dokaspar at student.ethz.ch (Dominik Kaspar) Date: 30 Sep 2003 11:57:17 -0700 Subject: where are the "class variables"? Message-ID: <62e9c66e.0309301057.65f24a3b@posting.google.com> i'm used to java and its strict way of defining variables. so how is it possible to reach something like a class variable in python? with the following code i didn't have much succes... class Server(threading.Thread): running = 0 (??) def run(self): running = 1 while running: print "do something here..." def exit(self): running = 0 thanks -- dominik From msajec at ieee.org Thu Sep 25 19:34:33 2003 From: msajec at ieee.org (Mike S.) Date: 25 Sep 2003 16:34:33 -0700 Subject: Compiling informxidb-1.3 on python2.2? References: Message-ID: Well I managed to get the configure script to run: ./configure loading cache ./config.cache checking whether make sets ${MAKE}... (cached) yes checking for python... (cached) /usr/bin/python checking for --with-informix... /opt/informix checking for esql... (cached) /opt/informix/bin/esql checking for --enable-thread... no checking for --enable-shared... yes creating ./config.status creating Makefile creating ext/srcdir creating ext/Setup creating ext/Makefile But got a ton of errors when trying step 5 in Robin's list: >>esql _informixdb.c _informixdb.ec:48:20: Python.h: No such file or directory _informixdb.ec:49:24: longobject.h: No such file or directory In file included from _informixdb.ec:50: dbi.h:13: parse error before '*' token dbi.h:14: parse error before '*' token dbi.h:15: parse error before '*' token dbi.h:18: parse error before '*' token dbi.h:18: parse error before '*' token dbi.h:18: warning: data definition has no type or storage class dbi.h:19: parse error before '*' token dbi.h:19: parse error before '*' token dbi.h:19: warning: data definition has no type or storage class dbi.h:20: parse error before '*' token dbi.h:20: parse error before '*' token dbi.h:20: warning: data definition has no type or storage class dbi.h:21: parse error before '*' token dbi.h:21: parse error before '*' token dbi.h:21: warning: data definition has no type or storage class dbi.h:35: parse error before '*' token dbi.h:35: warning: data definition has no type or storage class Make sense to anyone?? msajec at ieee.org (Mike S.) wrote in message news:... > > 2. Untar, run configure > Unfortunately, the trouble starts here at step 2. By any chance do > you have both python1.5 and python2.2 installed? > > root at pe informixdb-1.3]# ./configure > loading cache ./config.cache > checking whether make sets ${MAKE}... (cached) yes > checking for python... (cached) /usr/bin/python > checking for --with-informix... /opt/informix > checking for esql... (cached) /opt/informix/bin/esql > checking for --enable-thread... no > checking for --enable-shared... yes > creating ./config.status > creating Makefile > creating ext/srcdir > creating ext/Setup > cp: cannot stat `/usr/lib/python1.5/config/Makefile.pre.in': No such > file or directory > creating ext/Makefile > make: ./Makefile.pre.in: No such file or directory > make: *** No rule to make target `./Makefile.pre.in'. Stop. > [root at pe informixdb-1.3]# > : > > Robin Munn wrote in message news:... > > Mike S. wrote: > > > Hello, > > > > > > Has anyone had success compiling the informixdb-1.3 module under > > > python 2.2? It seems the absense of makefile.pre.in in python 2.2 > > > causes the break under py2.2. Is there an easy way around this. I've > > > heard rumors of a manual method, but have been unable to track down > > > details. Any help is very much appreciated. > > > > > > Thanks in advance, > > > Mike > > > > Here's the step-by-step notes I wrote for myself when I had to do > > exactly that back in May: > > > > Steps in installing the informixdb module: > > > > 1. Download informixdb source from > > http://starship.python.net/crew/sturner/informixdb.html > > 2. Untar, run configure > > 3. Edit ext/Makefile: change CFLAGS (line 100) to include > > -I${INFORMIXDIR}/incl/esql > > 4. Cd into ext directory > > 5. Run "esql _informix.ec" to generate _informix.c file > > 6. Cd back into parent directory > > 7. Run make > > 8. Copy informixdb.py and ext/_informixdb.so into > > /usr/lib/python2.2/site-packages/ > > > > I hope this helps. I did this install on a Red Hat machine that had the > > Informix SDK installed, so I had the esql command available. If you > > don't have esql available, then I'm not sure what you'll need to do. > > > > Good luck! From NO-MAIL at hotmail.com Mon Sep 22 21:49:36 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 23 Sep 2003 01:49:36 GMT Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> Message-ID: "Julian Tibble" wrote in message news:slrnbmv319.9d2.chasm at galileo.rift... > In article , M-a-S wrote: > > No difference on my computer (see my note at the end): > > > > > s *= 1 <--------------------------------- maybe this is your difference! > > oh dear :( > damn typos That's why I had in my code this: assert f_rec == f_iter == f_xter == f_nter == f_rdc for all the factorial values :) And I like the Python's way of expressing multiple relations! M-a-S From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 10 20:03:10 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 11 Sep 2003 01:03:10 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <3F5F83B1.48763F85@alcyone.com> Message-ID: I get to the reason I'm rapidly changing my mind on this idea at the end of this post, so you may want to read the last few paragraphs first, but... On Wed, 10 Sep 2003 13:04:01 -0700, Erik Max Francis wrote: >Stephen Horne wrote: > >> Its not an issue of whether the same effect can be achieved in Python. >> It's more an issue of whether the method used expresses the >> programmers intentions properly. > >I agree. And with your suggestion, now every single function call can >potentially change meaning. Given Python's dynamicism, you may not even >know if this particular function call exhibits the behavior. Now >Python's nice, predictable behavior is up for grabs. I don't agree with this. If the caller has to specify the behaviour in the syntax they use for the call AS WELL AS the definition (in both cases using the 'ref' modifiers) then the call mechanism is 100% explicit and predictable. If, given Pythons dynamism, you have an function object of the wrong type (and therefore one which does not support the call mechanism you are trying to use) then it will fail - just as attempting to do a conventional function call on a non-function will fail. That is, suppose I define a function... def Call_This (p_Function) : x = 1 p_Function (ref x) This function doesn't know what type of object it will be called with - it *should* be a function with a reference argument but it might be a conventional function, it might be a function with the wrong number of arguments, or it might not be a function at all. But it doesn't really matter because I have explicitly specified how I want to call that object - if the object doesn't support that call mechanism it simply fails. So if i write... def Example_Fn_1 (p) : None Call_This (Example_Fn_1) then an exception will be raised because I provided the wrong type of function as a parameter. But this is not really any different to what we should already expect if I write... Call_This ("oops, this isn't a function") >If you want to rebinding outside the function, a far better way of >"expressing the programmer's intentions properly," in my opinion, is to >make the behavior as explicit as possible: > > class Container: > def __init__(self, x=None): self.x = x > def get(self): return self.x > def set(self, x): self.x = x > def increment(self): self.x += 1 # for example > > def Inc(c): > container.increment() > > container = Container(1) > Inc(container) > print container.get() Of course this handles the increment example and it handles most cases quite well, but there are many cases where this is inappropriate. Putting an object into a mutable wrapper *purely* as a way to allow a function to rebind the object it needs to rebind is a bad idea - it means creating extra housekeeping code that (1) obscures the real application logic, and (2) creates extra opportunities for bugs. But of course my putting it that way is bogus - in reality, most data would be in mutable objects (class instances) anyway in real world programs, and the use of return values (including returning a tuple) can handle returning any number of output values. In other words, the following *is* bad... variable = Wrapper (variable) Call_Function (variable) variable = Wrapper.Unwrap () But realistically, that wouldn't happen. Rather, you'd have... variable = Call_Function (variable) And so we get back to Peter Ottens point - Python doesn't need call-by-reference (or rather call-by-reference-to-reference) because it has another way of providing output values - and significantly, one which allows multiple values to be conveniently returned. As a fan of many functional techniques and as someone who instinctively distrusts side-effects, I actually like this. But a little voice keeps whispering to me "yes, but not always". Part of it is of course that I still feel it is a wart that, when passing a mutable object as a parameter, I can rebind any internal component of that object and it will be visible to the caller - but if I rebind the object as a whole the change doesn't affect the caller. Of course we've been through this before, though, and I doubt you want to revisit the arguments any more than I do. The most compelling example I have is essentially the side-effect thing from my reply to Peter Ottens post. As an attempt to express it more clearly, there are times when you set up an object purely so that you can store it into a container... obj = Obj_Type () obj.Do_Setup_Stuff_1 () obj.Do_Setup_Stuff_2 () obj.Do_Setup_Stuff_3 () container.Add (obj) In many cases, the Add function will not take a copy because it seems pointless. The caller set up the object purely to store it in the container, and in most cases is going to discard its reference to the object immediately afterwards. But then there's always the possibility that the caller might carry on using that object. For instance... obj = Obj_Type () obj.Do_Setup_Stuff_1 () obj.Do_Setup_Stuff_2 () obj.Do_Setup_Stuff_3 () container.Add (obj) obj.Do_Setup_Stuff_3_Slightly_Differently () container.Add (obj) This probably wouldn't do what was expected - the 'slightly differently' call changed an object that is also being referenced from inside the container - an accidental side-effect. If a 'ref' parameter is used and the 'Add' function rebinds it to 'None', however, we get... obj = Obj_Type () obj.Do_Setup_Stuff_1 () obj.Do_Setup_Stuff_2 () obj.Do_Setup_Stuff_3 () container.Add (ref obj) obj.Do_Setup_Stuff_3_Slightly_Differently () # exception here tells that something has gone wrong container.Add (ref obj) Which quickly gets bugfixed to... obj = Obj_Type () obj.Do_Setup_Stuff_1 () obj.Do_Setup_Stuff_2 () obj.Do_Setup_Stuff_3 () container.Add_Copy (obj) obj.Do_Setup_Stuff_3_Slightly_Differently () # no exception as Add_Copy doesn't rebind the parameter container.Add (ref obj) Then again, even in this case there are other ways. For instance... builder = Builder () builder.Do_Setup_Stuff_1 () builder.Do_Setup_Stuff_2 () builder.Do_Setup_Stuff_3 () container.Add (builder.Build ()) builder.Do_Setup_Stuff_3_Slightly_Differently () container.Add (builder.Build ()) In this case, the builder class can set a 'used' flag after the 'Build' call which tells it that it needs to make a copy before applying further changes. In that way, both unnecessary copies and accidental side-effects are avoided while keeping the intention clear (especially as this is basically one of the classic design patterns from Gamma et al - though I may be confusing Builder with Factory Method) and with no changes to Python. So my 'most compelling example' isn't compelling at all. Damn. I've been thinking on this for some hours now and still not come up with a more compelling example (or at least not one which can't be better handled a different way) so I guess the idea is a dud. Bet you never expected me to admit that so easy ;-) From vze4rx4y at verizon.net Wed Sep 3 16:07:11 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 03 Sep 2003 20:07:11 GMT Subject: Difference of hash and __hash__() References: Message-ID: > > Looks like a bug to me too. Stefan, please raise a bug report on Sourceforge (or it will get lost). Preferably add a patch and test suite ;) > > Thanks, will do this evening. No need for a patch or test suite. Just assign the bug to me. I'm already working on the solution. Raymond Hettinger From danielk at aracnet.com Mon Sep 15 10:28:31 2003 From: danielk at aracnet.com (Daniel Klein) Date: Mon, 15 Sep 2003 07:28:31 -0700 Subject: Loading modules at startup in IDLE Message-ID: Does anyone know a way to automatically load modules in IDLE at startup? I can set %PYTHONSTARTUP% but this only works for the interactive prompt, not in IDLE. I tried doing the same thing with %IDLESTARTUP% but received no joy. What am I missing? Or has this capability been removed on 2.3? Thanks, Daniel Klein From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 24 01:13:47 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 24 Sep 2003 06:13:47 +0100 Subject: Thoughts on PEP315 References: <6f52nvsobkkf2n3p6stum3ipd5cp96i3pv@4ax.com> Message-ID: On Wed, 24 Sep 2003 06:07:21 +0100, Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: >The whole point of the syntax in the PEP is to have the loop condition >tested in the middle of the loop - something which in C (and current >Python) is handled badly by the unstructured 'break'. Ooops - that 'badly' was meant to be in quotes as I don't really think it's that bad. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From spam at magnetic-ink.dk Tue Sep 30 01:47:13 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Tue, 30 Sep 2003 05:47:13 +0000 (UTC) Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> Message-ID: <3f7918e1-cebe25d5-ba02-4762-ae3e-ad3bb70874cb@news.szn.dk> Lulu of the Lotus-Eaters wrote: > So I only expect around 5,428,681 primes less than 10^8 to occur. > Well, that's not SO much less than 7.8M. I found 5,761,455 primes < 1E8. // Klaus -- ><> unselfish actions pay back better From hwlgw at hotmail.com Tue Sep 2 17:52:05 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 2 Sep 2003 14:52:05 -0700 Subject: Python REST framework? References: Message-ID: > [Jeremy Jones] > Does anyone know if there exists a Python REST (web services) framework? > I've googled and come up short. I don't think it should be that hard to > do ... I'm interested. But I have been looking at the discussion on the rest mailing list at http://groups.yahoo.com/group/rest-discuss/ and it seems they haven't found a solution for the user:password thing yet. Using SSL is a must, but then what? Create some unguessable URI? That is not safe enough for banking applications etc. And using lowlevel http stuff is also being frowned upon. Consider creating a multiuser web-based game in a RESTful way, where players can use a password to get access to their avatar. I haven't figured out yet how to do such a thing according to REST, using Python Standard Library modules. -- Real programmers can write assembly code in any language. -- Larry Wall From mwh at python.net Tue Sep 2 07:34:11 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 2 Sep 2003 11:34:11 GMT Subject: printer friendly python tutorial References: <5.2.1.1.0.20030901234513.02e92120@66.28.54.253> <1062496037.923678@dmz2.imec.be> Message-ID: <7h3znhnh1g8.fsf@pc150.maths.bris.ac.uk> "K.C. Shashidhar" writes: > Fredrik Lundh wrote: > > http://www.python.org => Documentation => Download > > Current Documentation (first link on page) => > > http://www.python.org/doc/current/download.html > > where the table on the top of the page contains download > > links for HTML, PDF, Postscript, GNU info, iSilo, and LaTeX > > versions of the docs, in ZIP, GZip, and BZip2 archives. > > I wonder why someone wanting to print only the tutorial has to > download the whole archive and unzip. Wouldn't it be helpful to keep > them separately available, like the HTML versions are? Finite time and resources. Doesn't look like the zipped HTML is available separately, FWIW. You could suggest this to docs at python.org if you feel strongly, I guess. Cheers, mwh -- This is the fixed point problem again; since all some implementors do is implement the compiler and libraries for compiler writing, the language becomes good at writing compilers and not much else! -- Brian Rogoff, comp.lang.functional From lonnies at tgf.tc.faa.gov Mon Sep 22 13:39:36 2003 From: lonnies at tgf.tc.faa.gov (Lonnie, SRC employee) Date: Mon, 22 Sep 2003 13:39:36 -0400 Subject: Message-ID: <3f6f32b9@post.newsfeed.com> *** post for FREE via your newsreader at post.newsfeed.com *** I can figure out how to set the standalone attribute in the tag eg closest I have got to what I need is: using minidom in this code(snippet): xmldoc = Document() pi = xmldoc.createProcessingInstruction("standalone","yes") xmldoc.appendChild(pi) xmlroot = xmldoc.createElement("xpg") xmlroot.setAttribute("version","1.0") xmlroot.setAttribute("creator","crusher") xmldoc.appendChild(xmlroot) thx Lonnie Souder -----= 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 rasmus.klump at myorange.dk Mon Sep 29 08:51:59 2003 From: rasmus.klump at myorange.dk (Klaus Alexander Seistrup) Date: Mon, 29 Sep 2003 12:51:59 +0000 (UTC) Subject: PEP-0263 and default encoding Message-ID: <3f782aef-bdbbd6f1-a72a-4a6c-8b23-c4915b89a61f@news.szn.dk> Hi, After upgrading my Python interpreter to 2.3.1 I constantly get warnings like this: DeprecationWarning: Non-ASCII character '\xe6' in file mumble.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details And while I understand the problem, I cannot fathom why Python doesn't simply rely on the encoding I have specified in site.py, which then calls sys.setdefaultencoding(). Would anyone care to explain why the community has chosen to inconvenience the user for each python script with non-ASCII characters, rather than using the default encoding given in the site.py configuration file? Cheers, // Klaus -- ><> o mordo tua nuora, o aro un autodromo From godoy at metalab.unc.edu Tue Sep 9 11:26:46 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 09 Sep 2003 12:26:46 -0300 Subject: Request for comments on modular application design and security. Message-ID: Hello. I'm somewhat new to Python and I'm working on a modular application that needs to access a database. Let me describe what I've done so far and what I'm thinking about before asking something. We have a login program that authenticates the user against passwords available in the database and it opens a connection with priviledges only to read the user's table. If the access is granted than we os.execv() a second module that contains a menu list of modules of the system that are available for them. This will be used as the 'main menu'. If a button is clicked, the final program is called with all of its options. The problem is how to pass the information that the user was successfully authenticated and that connections should be opened with its username and password on the database. How can I pass this information from one proccess to another without compromising security and in a way that's available in both Linux and Windows? (They have half of the machines running each OS and are migrating to Linux.) Also, I'd appreciate comments on my approach. The program is going to be huge in size and with several screens. I've adopted separate modules to allow me to have it installed one piece a time and have it working nicely on old machines (mainly P-233 or a maximum of P-300 with 64/128 MB of RAM). TIA, -- Godoy. From __peter__ at web.de Thu Sep 18 13:52:36 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2003 19:52:36 +0200 Subject: Forcing getopt to process a specific option first?? References: Message-ID: Dan Rawson wrote: > Is there any way to force getopt to process one option first?? I'd like > to be able to pass in the name of a configuration file for my application, > then have the remaining command-line parameters over-ride the > configuration file if they are present. The easiest solution would be to make the config file the mandatory first argument of the command line and then call getopt.getopt(sys.argv[2:], options) Below is another approach, that might fit your needs: import getopt #sample args args = ["-c", "config.txt", "-r", "-i", "specialin.txt"] options, args = getopt.getopt(args, "c:ri:o:") useroptions = dict(options) if "-c" in useroptions: #set defaults defaultoptions = {"-i": "defaultin.txt", "-o": "defaultout.txt"} del useroptions["-c"] #override defaults defaultoptions.update(useroptions) options = defaultoptions.items() print options Peter From claird at lairds.com Fri Sep 5 05:03:32 2003 From: claird at lairds.com (Cameron Laird) Date: Fri, 05 Sep 2003 09:03:32 -0000 Subject: Embedded Perl or Python (XPost) References: Message-ID: In article , Chris wrote: . . . >I am developing a software project where a major portion of it is to >enable script access to c++ classes > >The idea is to extend the basic functionality of the program by allowing >third parties to write add ons that are called by my c++ classes as >virtual functions. . . . >Given the above which interpreter is most likely to fit my bill with the >smallest footprint ? . . . Let's be clear on what we're discussing. When you write, "smallest footprint", do you seriously mean, "creates the smallest differential in the size of the resulting exe- cutable image"? Frankly, that would surprise me; your project sounded interesting and useful up until those last two words. I don't mean to be harsh; unless there's something you're not telling us, though, the size of executables-as-file-images is quite unlikely to be even the tenth most important aspect of your target. I'll anticipate a bit more, and observe that Python is likely to be the better choice, because it remains easier for a newcomer to extend-or-embed (it's not clear that you've decided between these alternatives), at least until Perl 6 meets all its goals. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From link0937 at hotmail.com Tue Sep 23 05:32:07 2003 From: link0937 at hotmail.com (Link) Date: Tue, 23 Sep 2003 17:32:07 +0800 Subject: Anyone who good at PYTHON in Taiwan? Message-ID: Any instruments in Taiwan to help me for my questions answer? Of course, should pay for you if necessary. Please contract me by mail in the Taiwan daytime. Looking forward to your reply. Link From newsgroups at jhrothjr.com Tue Sep 16 15:44:20 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 16 Sep 2003 15:44:20 -0400 Subject: why pass statement? References: Message-ID: "M-a-S" wrote in message news:iRI9b.12996$x21.4462 at twister.southeast.rr.com... > Why is there the pass statement? I think, the expression statement would be enough: > > class C: > None > > while True: > None You don't actally need Pass. A docstring is sufficient: class C: "this is a class" while True: "loop de loop de loop" John Roth > > > > > > From R.Brodie at rl.ac.uk Fri Sep 26 09:10:01 2003 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 26 Sep 2003 14:10:01 +0100 Subject: why the inconsistency? References: <4bh3nv0esljf8pkegog0lc4lmg87siv1oc@4ax.com> Message-ID: "Alex Martelli" wrote in message news:CxWcb.172171$R32.5498673 at news2.tin.it... > I'm not sure how you'd compute log on integer numbers. Anyway, > if you're in a hurry to know the number of digits in 2**64 -- I > see math.log(x,10) taking about 4 usec per loop, len(str(x)) about > 6.3, in each case with x=2*64 and measuring with timeit.py > (elapsed time, as I'm measuring on Linux). And if you're really in a hurry 64 * log10(2) is good too ;) From ta-meyer at ihug.co.nz Tue Sep 30 06:04:11 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 30 Sep 2003 22:04:11 +1200 Subject: isNumber? check In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F1303744F86@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F13026F2977@its-xchg4.massey.ac.nz> [me] > > """ > > def isInt(s): > > try: > > i = int(s) > > except ValueError: > > i = None > > return i > > def isFloat(s): > > try: > > i = float(s) > > except ValueError: > > i = None > > return i > > def isNumber(s): > > return isInt(s) or isFloat(s) > > """ [Peter Otten] > Made-up use-case: > > s = "123" > value = isNumber(s) > if value is not None: > value *= 2 > else: > raise ValueError, "%s is not a number" % s I would think that: """ s = "123" value = isNumber(s) if value is None: # do something that shows it's not a number. # (obviously not raise a ValueError, because # then there's no point using the function at # all) # continue program, with value in value, if needed. """ Would be a more logical way to do it. > To me this looks like a deliberate attempt to obfuscate. It's not. It was an example case showing that there isn't any need to bother with regexs and the like if you don't want to - Python will do the work for you. Assuming you trust the Python developers, you can trust that it will correctly check that the value is convertible into a number, and don't need to worry that you missed something in the regex (or whatever). > Nobody would guess that you have to test the result of > isNumber() against None A real function would have a docstring...this is only c.l.p... > and cannot reliably treat it as a boolean value. If returning a boolean value was a criteria, then you just replace "return i" with "return True" or "return False". > You should at least change the function name > to something like stringToNumber(). The OP asked for a function called isNumber. I posted an example of one. > The program flow is redundant: > - convert to number > - "convert" exception into special return value > - check for special return value > - throw exception The program snippet doesn't throw an exception at the end; your example usage did. If the code was going to raise a ValueError if it couldn't be converted, then it would be written differently; the OP didn't say that that was the case. The program flow is really: - convert to number and return - if an exception was raised then return None, signifying that no number can be created Lots of the stuff written about Python talks about using exceptions for code control, as this does. This isn't C++. > I can think of very few situations where None could actually > be *used* instead of a numerical value. Why would you want to *use* None? It's simply the function signifying that it couldn't convert the number. > > Note that "0" will come back as 0.0, though, because it > > evaluates as False. It would be easy enough to special case that, if necessary. > > This is a bug that demonstrates that your isInt()/isFloat() > implementation is not even well suited to implement isNumber(). Rubbish. This is me not taking care of every little detail in example code, for the sake of brevity, but warning that that is the case. In any case, it still correctly determines if the object can be converted to a number, and still correctly returns the number it is converted to. The only thing that is possibly incorrect is that it's a float instead of an int. As I said, easily fixed. You seem to have missed the whole point of the code snippet. The idea is that you can use the conversion built into Python to check if a number can be converted, without having to write code that checks yourself. Perhaps you would like this more? """ def isNumber(s): for f in [int, float,]: try: return f(s) except ValueError: pass raise ValueError("Cannot convert to a number") """ To me this doesn't seem as clear in explaining the concept, although it's more like code I would actually use. This does return "0" as 0, and raises a ValueError is no conversion is possible. The point is that the concept, which is what I was trying to convey, is the same. If you really don't want the value returned, then you could just use: """ def isNumber(s): for f in [int, float,]: try: f(s) except ValueError: continue return True return False """ Probably not the fastest way to do it, but certainly simple. (Although not as simple as the hasattr(__int__) solution, which is very nice :) =Tony Meyer From aleax at aleax.it Fri Sep 26 08:53:22 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 12:53:22 GMT Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: <3F71B857.2D1E3268@engcorp.com> Message-ID: <6FWcb.125171$hE5.4261048@news1.tin.it> Peter Hansen wrote: > Anthony Baxter wrote: >> >> On behalf of the Python development team and the Python community, I'm >> happy to announce the release of Python 2.3.1 (final). > > The highlights mention the existence of a new API > PyThreadState_SetAsyncEnc, which is "deliberately accessible only from C", > that can interrupt a thread by sending it an exception. > > I can't find an online discussion of this, so I'm asking here. Why was > this > made accessible only from C? Is it dangerous? Experimental? Someone > feels it will be used inappropriately if too readily available at the > Python level? As covered in previous discussion, basically the latest reason. > Presumably somebody will come up with a little extension module or other > technique for calling this which will let anyone use it at will, so I'm > unclear on why it should be made inaccessible from Python. Having to use a third-party extension module, or other kludge, will make people more aware than this functionality is most likely NOT intended nor appropriate for the use they have in mind (that's going to be the case well over 90% of the time, IMNSHO based on teaching, consulting and debugging lots and LOTS of horrid, inappropriate threading architectures over the years). I just wish that most of the threading-synchronization constructs currently available in Python, and module thread first and foremost, were just as "arm's length away", leaving module threading and module Queue as "the only obvious way to do it" for 90%+ of people's actual threading needs... a sufficiently selfish and short-sighted consultant might think that would reduce their volume of business, but IMHO -- by removing most of the threading-related issues of most Python programs -- it would just make everybody's life a little bit better;-). Alex From hutsonken at ev1.net Mon Sep 22 21:51:40 2003 From: hutsonken at ev1.net (Kenneth Hutson) Date: Mon, 22 Sep 2003 20:51:40 -0500 Subject: How do you sort a name list and list in random order? References: Message-ID: What about shuffle()? "Tobias Pfeiffer" wrote in message news:bknkiq$3o6va$1 at ID-162581.news.uni-berlin.de... > Hi! > > Frank & Janny Plaza wrote in > news:mailman.1061730708.21315.python-list at python.org: > > > I am trying to write a program in which the users will each enter > > their names and when all names have been entered, I want to randomly > > sort > > "randomly sort"??????? I mean, for me "randomly" means somewhat of the > opposite of "sorted"... > > Bye > Tobias From duncan at NOSPAMrcp.co.uk Tue Sep 30 03:45:34 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 30 Sep 2003 07:45:34 +0000 (UTC) Subject: PEP-0263 and default encoding References: <3f782aef-bdbbd6f1-a72a-4a6c-8b23-c4915b89a61f@news.szn.dk> <3f79171c-d4c587aa-d4ac-44b9-97da-5e0024d4d268@news.szn.dk> Message-ID: Klaus Alexander Seistrup wrote in news:3f79171c- d4c587aa-d4ac-44b9-97da-5e0024d4d268 at news.szn.dk: > > Still beats me why it doesn't use the sys.getdefaultencoding() instead > of inconveniencing me. > I think the reasoning was that you might give your scripts to someone else who has a different default encoding and it would then fail obscurely. A script should be portable, and that means it can't depend on things like the default encoding. i.e. Its an attempt to satisfy both of these: Explicit is better than implicit. Errors should never pass silently. -- 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 hungjunglu at yahoo.com Sat Sep 27 04:25:10 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 27 Sep 2003 01:25:10 -0700 Subject: Try/except vs. if/else References: <3F70598E.8020500@bu.edu> Message-ID: <8ef9bea6.0309270025.3c4d79ed@posting.google.com> Tim Rowe wrote in message news:... > On Tue, 23 Sep 2003 11:10:49 -0400, Shu-Hsien Sheu > wrote: > > >In my understanding, using try/except rather than if/else is more > >pythonic. > > Rule of thumb: when the block of code is still doing what it's > supposed to do, use if/else. If it's failing to do what it's supposed > to do, use try/except. "except" should be an /exception/! ..... > So try/except /only/ when something has gone wrong and you need to go > into some sort of recovery or termination, /not/ for routine tests. You have a valid point of view, which nonetheless is not shared by everyone. This is a recurring subject in the newsgroup. Python exceptions have been used for other purposes, as can be seen from Python FAQ (e.g. "4.22 Why is there no goto?" in http://www.python.org/doc/faq/general.html) The "for" loop in Python is also implemented internally with exceptions. E.g.: http://groups.google.com/groups?selm=mailman.1010884758.23378.python-list%40python.org&oe=UTF-8&output=gplain, where it mentioned: "... In some other languages, 'non failure' mode exceptions may be unusual, but it's the normal idiom in Python." regards, Hung Jung From skip at pobox.com Fri Sep 26 11:22:10 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Sep 2003 10:22:10 -0500 Subject: PEPs link gone from the Python homepage? In-Reply-To: References: Message-ID: <16244.22946.446379.622160@montanaro.dyndns.org> David> Since a significant part of Python is only documented in PEPs, I David> am disappointed to see that they can't be easily found. Where David> are they? Dave, Try the left margin of the /dev/ page. If you find stuff in PEPs you believe belongs in the standard documentation set, please file a documentation bug report. While PEPs do contain a lot of valuable information, I don't think that using them for end-user documentation was a goal. Skip From BoteDesSchattens at web.de Tue Sep 16 10:40:47 2003 From: BoteDesSchattens at web.de (Tobias Pfeiffer) Date: 16 Sep 2003 14:40:47 GMT Subject: Print always puts newline (or adds a space) References: <3d9e1e6e689e3a662f59990c4b401713@news.teranews.com> <3F64DEF7.F98CFAB8@alcyone.com> Message-ID: Hi! Erik Max Francis wrote in news:3F64DEF7.F98CFAB8 @alcyone.com: >> Is there a "lower level" way to output >> chars other than 'print'? > > Yep, call sys.stdout.write directly. Is it then also possible to "jump back" a few chars to, e.g., have a progress... (damn, I forgot that word) however, that shows the percentage of progress? Like print "25%" and then jump back three chars and write "26%"? And then, on my Linux machine, such things just don't happen at all. E.g. in a loop like... for i in range(1000): j = pow(2,i) if j%100: print "#", ...I will get nothing for a long time and then ten "#" chars at one time. Is there a solution for that? Bye Tobias From gh at ghaering.de Mon Sep 8 02:40:17 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 08 Sep 2003 08:40:17 +0200 Subject: python module for MS SQL Server 7 or 2000? In-Reply-To: References: Message-ID: <3F5C2451.4080308@ghaering.de> Y2KYZFR1 wrote: > Gerhard H?ring wrote in message news:... > >>Y2KYZFR1 wrote: >> >>>I have searched and only found references to using ODBC or some >>>ancient posts about some ancient sybase library under linux, neither >>>of which meets my critiera. [...] >> >>Tried Google? Doesn't look like so: >> >>http://www.google.com/search?q=python%20ms%20sql%20server > > yes and nothing meets my criteria. I need something that is stable and > cross platform without any dependancies on any other libraries or > depenacny on linux Huh? The first hit can be built against the FreeTDS library, and you can have commercial support for it. Your point "no dependency on any other libraries" is just not practical for a database adapter, because then the database adapter would have to implement the database's wire protocol in pure Python. Well, it's possible, but it's not been done yet , at least for MS SQL. Oh, and this other DB-API module that communicates to MS SQL server using its XML protocol, that would meet *this* requirement. Dunno how stable it is, though. -- Gerhard From nospam at here.com Wed Sep 10 14:25:29 2003 From: nospam at here.com (Richard Townsend) Date: Wed, 10 Sep 2003 19:25:29 +0100 Subject: Image on disabled button References: <1062436629.69505.0@dyke.uk.clara.net> <1063135933.53254.0@doris.uk.clara.net> <7e337cbf.0309092318.3019e1cb@posting.google.com> Message-ID: <1063218108.5220.0@doris.uk.clara.net> > > I have now checked again on HP-UX and have found that you must also set: > > self.root.option_add('*disabledForeground', '') > > to stop the bug appearing... It also works on Windows 2000. From gafStopSpamData at ziplink.stopallspam.net Tue Sep 30 16:23:59 2003 From: gafStopSpamData at ziplink.stopallspam.net (G.A.) Date: Tue, 30 Sep 2003 20:23:59 GMT Subject: General Password questions References: <3F6F86A2.DC29472A@engcorp.com> <3F704A91.FA7D31F7@engcorp.com> Message-ID: On Tue, 23 Sep 2003 18:02:37 +0200, Riccardo Attilio Galli wrote: >english). An user should never enter the password again. I know how hashes >work, and they're useful when I can compare an entered password with an >hash value, but here I need that the user don't enter a password anymore >(after the first time). Better late than never: The only way to do this securely is to rely on the operating system's security, and even that isn't always possible. I think the NT/W2K model allows for encryption based on keys that only the specific user can use (i.e. you have to actually be logged in as that user; I'm not sure if the adminstrator can fake it). This won't work on 9X. On UNIX, a close approximation is to just store the password in a file to which only the user has read access, but obviously root will still have access. Note that if the application supports multiple mail accounts for a single user (as many do), then it becomes useful to have a single password for the application, used to encrypt the various passwords for the different mail accounts. Gary From newsgroups at jhrothjr.com Mon Sep 8 13:23:44 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 8 Sep 2003 13:23:44 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <3f5a2260$0$166$a1866201@newsreader.visi.com> Message-ID: "Harri Pesonen" wrote in message news:TRr6b.4056$ZB4.1410 at reader1.news.jippii.net... > Grant Edwards wrote: > > > In article , Harri Pesonen wrote: > > > >>I agree, it's not logical. I'm learning Python at the moment, and like > >>it very much. This "self" thing seems to be the only odd feature, > > > > It seemed quite natural to me, but perhaps that's because I'd > > used other languages that worked the same way. Coming from > > Modula-3 and Smalltalk, the way classes worked in Python seemed > > quite intuitive. > > > > OTOH, C++ seems like a real non-intuitive mess to me. > > > >>it feels like the whole class feature was added later. > > > > Why? > > Because everything else in Python seems to be very compact, there are no > variable type declarations, or variable declarations, or anything else > unnecessary that can be omitted. I would like to have self omitted, it > would make the class syntax more beautiful and compact. On the other > hand, I would like to have real private methods. > > Also I think that the class members should be explicitly declared. In > general, it would be nice to have an option (like Option Explicit in > Visual Basic) so that you can't assign to variables that have not been > declared. It would probably make Python less error prone. I believe that is what __slots__ is for. That's run time rather than compile time, but at least it gives you the error on the statement that attempts to do an invalid assignment. > Also if > variable declarations could have the type, again some errors could be > detected at compile time. It's quite possible to add run time type checking to Python, at a significant cost in performance. See the descriptors material. There's been quite a bit of work on a compile time type checking system over the years, but it has never resulted in a proposal that could be agreed on. My own personal opinion is that I like the type check system in the ML family of languages: it stays out of your way unless you need it. How that would fit in Python is another question, though. At this time, it looks like an issue for Python 3.0, which seems to keep receeding into the distance. John Roth > I have not written any real Python applications yet, so I'm not expert, > these are just my thoughts at this point. > > Harri > From dkuhlman at rexx.com Wed Sep 3 13:00:12 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 03 Sep 2003 10:00:12 -0700 Subject: what is the easiest way to parse a file References: Message-ID: tagarwal wrote: > Is there a library in python which could be used for parsing file > based upon various sections Do you have a grammar for the input files? Is so, look at the parser generators for Python, for example Plex, PLY, and others. You might find some help in "Python 201 -- (Slightly) Advanced Python Topics", Section 5, "Parsing", which is at: http://www.rexx.com/~dkuhlman/python_201/python_201.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From pf_moore at yahoo.co.uk Tue Sep 16 15:26:01 2003 From: pf_moore at yahoo.co.uk (Paul Moore) Date: Tue, 16 Sep 2003 20:26:01 +0100 Subject: Datetime utility functions References: <182bcf76.0309150707.3a8c0482@posting.google.com> Message-ID: Christos "TZOTZIOY" Georgiou writes: > I sent my own version without having seen your own --and mine might seem > obfuscated, compared to yours. Only a minor suggestion: don't use > dt.replace, use dt.__class__ instead, since you wouldn't want your > function to have side-effects (that is, don't destroy the actual object > that dt is bound to.) dt.replace doesn't have side effects - it creates a new object. Also, by using replace(), my version works with date, datetime, or subclasses. Yours does too, but it sets the time component of a datetime to zero. It's a matter of preference which behaviour is "better", I guess. Paul. -- This signature intentionally left blank From newsgroups at jhrothjr.com Tue Sep 30 10:59:37 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Sep 2003 10:59:37 -0400 Subject: intercepting smtp email References: Message-ID: ".r!kard" wrote in message news:blc1kt$ooe$1 at green.tninet.se... > I'm no star at this but maybe you can check the code in > http://www.gnu.org/software/mailman > > .r!kard I think he's asking for a mini-firewall. In other words, is something he doesn't know about sending messages on port 25? John Roth > > "Scott Hathaway" wrote in message > news:c6354815.0309300518.4acb87b2 at posting.google.com... > > I want to write an NT service that will intercept any outgoing smtp > > traffic, like Norton Antivirus does. Can anyone tell me how I can do > > something like this in Python? I do not know how to intercept the > > outgoing traffic, specifically. > > > > Any help is greatly appreciated. > > > > Thanks, > > Scott > > From NO-MAIL at hotmail.com Tue Sep 16 15:46:09 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 19:46:09 GMT Subject: None, False, True References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> <3f675ecd$0$97184$edfadb0f@dread12.news.tele.dk> Message-ID: <5MJ9b.13244$x21.9088@twister.southeast.rr.com> "Max M" wrote in message news:3f675ecd$0$97184$edfadb0f at dread12.news.tele.dk... > > Yes. You assign new values to the objects None, False and True. You then > print out those values in a tuple. > > What's not to understand? > > But for others reading your programme you might be better of to keep > them their normal values. Which are ...? I mean what are None, False and True? Are they just identifiers? Are they variables defined in __builtins__? Are they literals? Are they language "bricks" like "for" and "1"? From mpeuser at web.de Fri Sep 5 04:07:10 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 10:07:10 +0200 Subject: safari References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <51809ae4.0309040634.7999e400@posting.google.com> Message-ID: > Alex Martelli wrote in message news:... > > Even ignoring safari's many other advantages > > Safari is definitely a useful service (I am a subscriber) but > 1. its range of titles is quite limited (only best-sellers) It is *very* limited; though I think all or O'Reilly's books are in it (and MicrosoftPress and SAMS) there is little more; they advertise Addison Wesley, but there is only a fraction of their books. > 2. the time lag between release as hardcopy vs. on Safari can be really long 3. It *is* expensive in the long run, except you have a *very* broad interest in multiple aspects of computer science. Kindly Michael P (also a subscriber) From cmkleffner at gmx.de Mon Sep 15 02:44:56 2003 From: cmkleffner at gmx.de (cmkl) Date: 14 Sep 2003 23:44:56 -0700 Subject: better use of os.system() References: <181d118be52ffabbbeaa120340c3f759@news.teranews.com> Message-ID: <3b091a1c.0309142244.6232a8ac@posting.google.com> Fooman wrote in message news:<181d118be52ffabbbeaa120340c3f759 at news.teranews.com>... > > lower: not found > > > > I want it to run "lower" just like it would if I typed "lower" at the > > bash prompt. How can I do that? > > The problem is that the 'lower' script is not in the path that > the python interpreter knows about. You can do: > > os.system("/my/nonstandard/pathto/lower") > > or, if you are using Linux, or similar, you can try > making sure that your $PATH variable is getting set to > include the path to your script in the environment that > the python interpreter gets launched in. > > So, what platform are you running under, and what is the > path to your 'lower' script, and what are the contents > of your $PATH variable? > > Tobiah You can use the standard windows Python distribution with a little trick. First of all make sure you can start 'lower' from a dos console. To do that, you need a little helper cygwin shell script: - start cygwin - cd /bin - create a cmd2bash script with the following content: #! /bin/bash $* - chmod +x cmd2bash (make it executable) Then start a console and try out following command: C:\>c:\cygwin\bin\bash c:\cygwin\bin\cmd2bash "ls -la" Do you see the content of drive C:\ in posix style? You may need to adjust the path to cygwin. If you have name with spaces (barf) you may need single quotes: C:\Programme>c:\cygwin\bin\bash c:\cygwin\bin\cmd2bash "ls 'Outlook Express'" Then try to start your lower script with: os.system('''c:\cygwin\bin\bash c:\cygwin\bin\cmd2bash "lower"''') btw: this trick works for msys too Regards Carl From http Thu Sep 4 14:54:21 2003 From: http (Paul Rubin) Date: 04 Sep 2003 11:54:21 -0700 Subject: OT: best book in years References: Message-ID: <7xn0dkxu3m.fsf@ruckus.brouhaha.com> Patrick Useldinger writes: > I am going to stay in hospital for a week or so (nothing serious), and > am trying to find a book or two to read there. As I have not come > across anything spectacular recently (except Python in a Nutshell), I > would like to know what *you* consider to be the best book you have > read in the last few years, about Python or IT in general. Security Engineering, by Ross Anderson From anton at vredegoor.doge.nl Fri Sep 5 20:21:15 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 06 Sep 2003 02:21:15 +0200 Subject: Coding Style: Defining Functions within Methods? References: <70df36e9.0309050837.1660cdf4@posting.google.com> Message-ID: harry.pehkonen at hotpop.com (Harry Pehkonen) wrote: >I have been defining new class methods when I'm trying to simplify >some code. But I'm thinking I should just define functions within >that method because they aren't useful from the outside anyway. It's also possible to generate classes by using a factory function. For an example of it getting a bit out of control see the code below. Anton --- from __future__ import division from Tkinter import * def template(x=None): class T(tuple): def __new__(cls, *args): return tuple.__new__(cls, args) def geta(self): return self[0] def getb(self): return self[1] a,b = map(property,[geta,getb]) return T Point = template() Rect = template(Point) Cube = template(Rect) class Transformer(Cube): def __init__(self, *args): a,b = self.a,self.b fx = (b.b.a-b.a.a)/(a.b.a-a.a.a) fy = (b.b.b-b.a.b)/(a.b.b-a.a.b) f = min(fx,fy) wxc = (a.a.a+a.b.a)/2 wyc = (a.a.b+a.b.b)/2 vxc = (b.a.a+b.b.a)/2 vyc = (b.a.b+b.b.b)/2 xc = vxc-f*wxc yc = vyc-f*wyc self.f,self.xc,self.yc = f,xc,yc def transform(self, R): f,xc,yc = self.f,self.xc,self.yc p1 = Point(f*R.a.a+xc, f*R.a.b+yc) p2 = Point(f*R.b.a+xc, f*R.b.b+yc) return Rect(p1,p2) class Cartesian: def __init__(self, master): self.canvas = Canvas(master,width=500,height=500) self.canvas.pack(fill= BOTH, expand=YES) master.bind("", lambda event='ignored', m=master: m.destroy()) master.bind("", self.configure) def configure(self, event): self.draw() def draw(self): c = self.canvas c.delete('all') T = Transformer(self.b,self.a) colors ='Red Green Blue Magenta Cyan Yellow'.split() for i in range(50,0,-1): R = Rect(Point(-i,-i),Point(i,i)) c.create_rectangle(T.transform(R), fill=colors[(i-1)%len(colors)]) def geta(self): c = self.canvas p1 = Point(0,0) p2 = Point(c.winfo_width(), c.winfo_height()) return Rect(p1,p2) def getb(self): a = 50 p1 = Point(-a,-a) p2 = Point(a,a) return Rect(p1,p2) a,b = map(property,[geta,getb]) def main(): root = Tk() ca = Cartesian(root) root.mainloop() if __name__=='__main__': main() From invalid at hazen.net Tue Sep 23 21:33:31 2003 From: invalid at hazen.net (John Hazen) Date: Tue, 23 Sep 2003 18:33:31 -0700 Subject: why the inconsistency? In-Reply-To: ; from mensanator on Tue, Sep 23, 2003 at 06:04:33PM -0700 References: Message-ID: <20030923183331.A16659@gate.hazen.net> On Tue, Sep 23, 2003 at 06:04:33PM -0700, mensanator wrote: > I just installed Python 2.3 (upgrading from 2.1). > > Version 2.3 is noticably faster and the automatic > conversion to long integers is very handy: > > >>> print 2**64 > 18446744073709551616 > > > But if I want to know how many digits 2**64 has, I can't > just do > > >>> print len(2**64) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: len() of unsized object > > So instead, I did this > > >>> print len(`2**64`) > 21 > > But the correct answer is 20, not 21. The reason the > answer is wrong > > >>> print `2**64` > 18446744073709551616L > > Why is the "L" there? I thought "L" isn't used anymore? I believe the L is there because the backticks invoke __repr__ intsead of __str__. I think backticks are somewhat deprecated now. (At least Guido called them "a failed feature which never got retired".) I think what you want is 'str'. >>> a = 2**64 >>> repr(a) '18446744073709551616L' >>> str(a) '18446744073709551616' >>> len(str(a)) 20 >>> -John -- @ From lupan at zamek.gda.pl Mon Sep 15 10:58:00 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Mon, 15 Sep 2003 16:58:00 +0200 Subject: list of lists References: Message-ID: <87vfru85fr.fsf@psi.lupan.zamek.gda.pl> Do you mean this: >>> T=[[1, 2, 3], [4, 5], [6]] >>> print T[0][1] 2 -- =*= Lukasz Pankowski =*= From peter at engcorp.com Fri Sep 19 20:07:32 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Sep 2003 20:07:32 -0400 Subject: whitespace References: Message-ID: <3F6B9A44.BD3D35F1@engcorp.com> RR wrote: > > Is there an easy way in python to remove whitespace from a string? >>> ' string with whitespace '.strip() 'string with whitespace' -Peter From achrist at easystreet.com Wed Sep 10 17:20:57 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Wed, 10 Sep 2003 14:20:57 -0700 Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> <3F5F8742.C1C66903@engcorp.com> Message-ID: <3F5F95B9.A8CB5786@easystreet.com> Peter Hansen wrote: > > > Queue.Queue.get() ... > That looks good. But that needs a thread to block, right? A generator manages to run without being a thread (at least overtly). If we have the suck() statement, we also need something that's the opposite of a generator (a Sucker?) and something that's the opposite of an iterator (a Suckee?). I'm starting to get an idea why this is completely not all there. The main question this raises is "How lightweight are threads?" Can I program with dozens or hundreds of python threads in a program (for example under Windows) and not notice that this is an inefficient or inept coding style? Al From mcherm at mcherm.com Tue Sep 9 12:38:28 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 9 Sep 2003 09:38:28 -0700 Subject: Jython class names Message-ID: <1063125508.3f5e0204dee4f@mcherm.com> Peter Otten writes: > That's definitely not what I expected. So == is the way to go. > Still, I'm curious: would the code below return 100 in Jython? > > >>> class C: pass > ... > >>> many = [C() for i in range(100)] > >>> d = {} > >>> for c in many: > ... d[id(c.__class__.__name__)] = None > ... > >>> len(d.keys()) > 1 Well, I fired up my Jython and tried it: Jython 2.1 on java1.3.1_03 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> class C: pass ... >>> many = [C() for i in range(100)] >>> d = {} >>> for c in many: ... d[id(c.__class__.__name__)] = None ... >>> len(d.keys()) 100 >>> Apparently the answer is "No". Really, in cPython or Jython or Pippi or PythonDotNet, or PyPy, or any other python implementation that I may not have thought of, the rule is that two equivalent strings _WILL_ return 1 (or True) if you compare them using "==". But if you compare using "is", or compare their "id()"'s, then they _might_ match or they might not... it's up to the implementation and depends on what kinds of optimization are done. The same is true for other built-in immutable types, like int and float. For example, in cPython 2.3, we get the following: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 9 is 10 - 1 True >>> 99 is 100 - 1 True >>> 999 is 1000 - 1 False This is due to special optimization being provided for small ints. There's a similar optimization for small strings: >>> 'a' is 'a' * 1 True >>> 'aa' is 'a' * 2 False But if I try both of these in Jython: Jython 2.1 on java1.3.1_03 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> 9 is 10-1 1 >>> 99 is 100 - 1 1 >>> 999 is 1000 - 1 0 >>> 'a' is 'a' * 1 0 >>> 'aa' is 'a' * 2 0 Apparently that version of Jython includes the same small int optimization but lacks the small string optimization. Really, if you want the answer to be reliable, use "==" instead of "is" for immutables. -- Michael Chermside From kpaz at samorzad.pw.edu.pl Fri Sep 26 16:36:56 2003 From: kpaz at samorzad.pw.edu.pl (Krzysztof Pa¼) Date: Fri, 26 Sep 2003 22:36:56 +0200 Subject: UPDATED: Python SSL Socket Client to Java SSL Server. HELP me PLEASE. References: Message-ID: On the Java server side I'm using ObjectInput/OutputStream classes to provide efficient communication. After accepting incoming connection, SSL handshake is done properly - I think. Next, while server is creating streams for reading and writing data with client I've got such exception in Java Server Code - during call of code: JavaCode: datain = new ObjectInputStream(client.getInputStream ()); - where client is client socket, JavaException: java.io.StreamCorruptedException: invalid stream header at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:737) at java.io.ObjectInputStream.(ObjectInputStream.java:253) ... So, what is the problem ? If there is any possibility to read/write data with SSLsockets from Python to Java ObjectInput/Output Streams or not ? Any ideas ? Kris. PS. Main part of my test python client code: === def verify_cb(conn, cert, errnum, depth, ok): print 'Got certificate: %s' % cert.get_subject() return ok s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ctx = SSL.Context(SSL.SSLv3_METHOD) ctx.set_verify(SSL.VERIFY_NONE, verify_cb) ss = SSL.Connection(ctx,s) print 'Python socket client. Connecting to: ', `HOST`, `PORT`, '.' ss.connect((HOST, PORT)) print 'Writing query to server...' ss.send("GET_VER") print 'Reading response from server...' data = ss.recv(2048) s.close() print 'Received', `data` === this code make such output: === Python socket client. Connecting to: [my server...]. Writing query to server... Got certificate: <...[cert data - ok]...> Reading response from server... Traceback (most recent call last): File "D:\Install\Python\conn.py", line 24, in ? data = ss.recv(2048) SSL.ZeroReturnError === From newsgroups at jhrothjr.com Mon Sep 15 22:15:49 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 15 Sep 2003 22:15:49 -0400 Subject: object.attribute vs. object.getAttribute() References: Message-ID: "Roy Smith" wrote in message news:roy-81B3E5.20291015092003 at reader2.panix.com... > For the past 6-8 months, I've spent most of my time writing C++ and a > little bit of Java. Both of these languages support and encourage the > use of private data and explicit accessor functions, i.e. instead of > writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to > writing Python, I find myself in a quandry. > > Historically, I've always avoided accessor functions and just reached > directly into objects to get the value of their attributes. Since > Python doesn't have private data, there really isn't much advantage to > writing accessors, but somehow I'm now finding that it just feels wrong > not to. I'm not sure if this feeling is just a C++/Java-ism that will > cure itself with time, or if perhaps it really does make sense and I > should change the way I code. I'm with Jeff on this one. If it looks like a value, then access it directly. If you need to slide a mutator in under it, it's simple enough to make it a property later without affecting any of the code that uses it. > On the plus side, accessors/mutators give me: > > 1) Implicit documentation of which attributes I intended to be part of > an object's externally visible state (accessors). Use the underscore convention. > 2) Hooks to do data checking or invarient assertions (mutators). > 3) Decoupling classes by hiding the details of data structures. > 4) Vague feeling that I'm doing a good thing by being more in line with > mainstream OO practices :-) 4 is actually the same thing as 3, except not stated as cleanly. > On the minus side: > > 1) More typing (which implies more reading, which I think reduces the > readability of the finished product). > 2) Need to write (and test) all those silly little functions. > 3) Performance hit due to function call overhead. > 4) Only the appearance of private data (modulo some slots hackery). > 5) Code is harder to change (adding functionality means going back and > adding more slots). > 6) Vague feeling that I'm dirtying myself by letting C++ and Java change > my Python coding habits :-) Items 1 through 3 don't matter if you use properties. You use them when you need them, otherwise you simply access the attribute directly. If you're using Python, you don't worry about private data. Use the underscore convention, and don't worry otherwise. Don't use slots. I never worry about where a good idea comes from. John Roth > > Comments? From dario at fga-software.com Fri Sep 5 10:36:25 2003 From: dario at fga-software.com (ProgDario) Date: 5 Sep 2003 07:36:25 -0700 Subject: Executing a Jython function from Java References: <67a857cc.0309050122.644ea7ee@posting.google.com> Message-ID: <67a857cc.0309050636.4ab33983@posting.google.com> dario at fga-software.com (ProgDario) wrote in message news:<67a857cc.0309050122.644ea7ee at posting.google.com>... > Hello, > > in the site I found a lot of complicated examples, but I can't find > the simple one I'm looking for. > > The problem is: > > I have 1 jython file (script1.py) with a function named 'calculate', > and a java file (run.java). > > I'd like to call the jython function from the java class recursively. > <<====<< > > I think it can be possible to get a PyFunction object that rapresents > the function, and then call the function from the already evaluated > object, so I don't need to re-evaluate it every loop. > > My code is something like this: > > PythonInterpreter interp = new PythonInterpreter(); > interp.execfile('script1.py'); > for (int i = 0; i < 1000; i++) { > interp.eval("calculate(8)"); > } > > Thanks in advance, > > Dario I searched the web for a long time, and finally Jeff Emanuel emailed me and solved the problem. That's the code, any advice is apreciated: import java.io.*; import java.util.*; import java.text.*; import org.python.util.PythonInterpreter; import org.python.core.*; public class Calculate { public static void main(String[] args){ PythonInterpreter interp = new PythonInterpreter(); interp.execfile("script1.py"); PyFunction func = (PyFunction)interp.get("calculate",PyFunction.class); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh.mm.ss"); System.out.println("======[" + sdf.format(new Date()) + "]==========="); for (int i=1 ; i<10000 ; ++i) { // Assuming calculate takes a float argument. func.__call__(new PyFloat(i)); //interp.eval("calculate(" + i + ")"); } System.out.println("======[" + sdf.format(new Date()) + "]==========="); } } From nospam at nospam.com Mon Sep 29 16:12:03 2003 From: nospam at nospam.com (AK) Date: Mon, 29 Sep 2003 20:12:03 GMT Subject: shelve keeping old (unused) data around? Message-ID: Hello, I'm using shelve module in python 2.3 and I found that it does a very odd thing, at least very unexpected to me. It seems that the data of a replaced or deleted key stays in filename.dat file. Example: >>> d = [1]*1000 >>> from shelve import * >>> s = open('test') >>> s['test'] = d >>> s.close() test.dat is 4100 bytes >>> d = 1 >>> s = open('test') >>> s['test'] = d >>> s.close() test.dat is still 4100 bytes If I do del s['test'], it stays the same. From toby at rcsreg.com Sun Sep 14 17:50:15 2003 From: toby at rcsreg.com (Tobiah) Date: Sun, 14 Sep 2003 21:50:15 GMT Subject: No "side effect" assignment! Message-ID: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> Ok, I miss the idiom that my other languages use, something like: while( foo = getmore()){ process(foo); } I can't seem to do this in python without gagging: foo = getmore() while foo: process(foo) foo = getmore() Is that what ppl do? The manual sez that this is so that newbs won't do: if foo = bar: process() thinking that they are checking for equality. I feel that in a few ways python suffers by catering to the uninitiated. Usually however, there are great workarounds (or even plain better ways to do the job), which I am hopeful will be yielded by the list, as has been it's record thus far to do. Thanks, Tobiah From altis at semi-retired.com Wed Sep 17 00:03:30 2003 From: altis at semi-retired.com (Kevin Altis) Date: Tue, 16 Sep 2003 21:03:30 -0700 Subject: ANN: PythonCard 0.7.2 Message-ID: PythonCard is a GUI construction kit for building cross-platform desktop applications on Windows, Mac OS X, and Linux. Release 0.7.2 includes over 40 sample applications and tools to help users build applications in Python, including codeEditor, findfiles, and resourceEditor (layout editor). A list of changes since release 0.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 most of the samples that have been built with PythonCard and screenshots of them in action go to: http://pythoncard.sourceforge.net/samples/samples.html 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.2.1 or later and wxPython 2.4.1.2 or later. wxPython can be downloaded at http://www.wxpython.org/ Additional Notes: Remember to backup or just delete your old PythonCardPrototype directory before installing a new version, so that the old files aren't still in the package directory. If you installed a previous version of PythonCard on Windows using the binary installer, then you should be able to remove the old package via the Add/Remove Programs Control Panel. The distutils installer will put the framework, components, docs, samples, and tools in Lib\site-packages or your Python directory (typically C:\Python22 or C:\Python23). Of course, on Linux and Mac OS X that path will be slightly different and have forward slashes. Windows users should get a PythonCard menu in the Start->Programs menu with links to the documentation, samples, codeEditor, findfiles, and resourceEditor. The tools and most of the samples will now keep their config and data file info in the "pythoncard_config" directory created by the framework. On Unix, the directory will be ~/pythoncard_config. On Windows, the directory varies as described in the following post: http://aspn.activestate.com/ASPN/Mail/Message/PythonCard/1496793 So, if you run a PythonCard app with any of the runtime tools and select "Save Configuration" from the "Debug" menu, the window positions and sizes of your runtime windows (Shell, Message Watcher, etc.) will be saved in "pythoncard_config/pythoncard_config.txt" not the PythonCardPrototype directory. Likewise, when you change the text style used by the codeEditor via the "Styles..." menu item under the "Format" menu, the modification will be saved in "pythoncard_config/stc-styles.rc.cfg" ka --- Kevin Altis altis at semi-retired.com http://altis.pycs.net/ --- changelog since release 0.7 Release 0.7.2 2003-09-08 ranamed MultiColumnList 'border' attribute to 'rules' enabled MultiColumnList and Tree in the resourceEditor added minimalList and minimalTree samples as tests of the MultiColumList and Tree components added multicolumnexample by William Volkman replaced older MultiColumnList component with version by William Volkman added workaround for wxMSW GetFont() bug in MultiColumnList switched to Raise() in fixComponentOrder to deal with wxPython 2.4.x change with Hide/Show added shell.autoCompleteWxMethods = False to pycrustrc.py to hide CamelCase wxPython methods of components and other wxPython classes by default added source.encode('iso-8859-1') to textToHtml to avoid print/print preview exceptions in codeEditor; this will probably require a more sophisticated solution added workaround for wxWindows AppendText bug in jabberChat sample. This might need to be added to TextArea appendText if wxWindows isn't fixed soon fixed popItems handling of RadioGroup and other components with an 'items' attribute in resourcEditor propertyEditor.py updated classes in menu.py to be direct wxPython subclasses added source file support to templates in resourceEditor updated File->New... process to save new files added moreapplications.html page to highlight other apps built with PythonCard added wx.wxDEFAULT_DIALOG_STYLE to singleChoiceDialog to workaround wxPython 2.4.1.2 bug fixed samples launcher selection and added double-click support added int(round()) conversions to fix Python 2.3 deprecation warnings added '' back to sys.path in pycrustrc.py for shell work changed default font size for findfiles tool on Mac and GTK added autoSetEOL to codeEditor to automatically use the line endings already in a document replaced \xa0 characters in source files with spaces added macbuild.py to the minimalStandalone sample to show how to build standalones on Mac OS X fixed double loading of pycrustrc.py files in loadShell fixed config directory creation fixed image rotation in slideshow sample for files in zips updated fixed getStyleConfigPath in colorizer fixed PILtoBitmap typo in graphic.py PythonCard now requires a minimum Python 2.2.1 or higher and wxPython 2.4.x or higher Release 0.7.1 2003-07-16 dbBrowser now supports PostgreSQL using the psycopg interface An alternative dbBrowser using a wxGrid to display query results has been added. Its called dbBrowser2 and it re-uses much of the code from the original changed wx.wxc.__version__ check to wx.__version__ added Save Configuration menu item to Scriptlet menu in the codeEditor fixed config.py for standalone usage added Thomas Heller's main_is_frozen function to util.py added GetPixel method to BitmapCanvas added userdata attribute to Widget so all components added support for userdata in the resourceEditor changed resourceEditor to use a drag rect so dragging works the same on all platforms and no longer requires the use of CaptureMouse on Linux added WMAvailable check for Mac OS X so the top frame appears in front when app starts fixed pycrustrc.py loading on Linux/GTK added Grid component and simpleGrid sample fixed script launching in samples.py, findfiles, codeEditor, and resourceEditor added spinUp and spinDown events to Spinner component added dirname() function to util module to use instead of os.path.dirname() updated model.py to use the new function changed true/false to True/False in STCStyleEditor.py to avoid wxPython 2.4.0.4 deprecation warning changed 'items' attribute in resourceEditor to use TextArea instead of TextField for editing fixed 'icon' handling in resourceOutput.py Phil Edwards' started making Linux RPMs for PythonCard added Phil Edwards Linux installation instructions added Mac OS X (Jaguar) installation instructions fixed font attribute in BitmapCanvas added David McNab's walkthrough Increasing Usefulness with Timers and Threads fixed order of wx imports so wx always comes first added jabberChat options for conferencing and Show/Raise slideshow sample changes added Goto Slide dialog changed F8 key to act as a Pause/Continue toggle added zip file support fixed relative directory reference in webserver sample From FBatista at uniFON.com.ar Tue Sep 16 13:09:20 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 16 Sep 2003 14:09:20 -0300 Subject: tuples vs lists Message-ID: Don't know about sizes, but the tuples are faster than the lists. . Facundo #- -----Mensaje original----- #- De: Ivan Voras [mailto:ivoras at fer.hr] #- Enviado el: Martes 16 de Septiembre de 2003 1:52 PM #- Para: python-list at python.org #- Asunto: tuples vs lists #- #- #- Are there any performance/size differences between using #- tuples and using #- lists? #- #- #- -- #- -- #- Every sufficiently advanced magic is indistinguishable from #- technology #- - Arthur C Anticlarke #- #- #- -- #- http://mail.python.org/mailman/listinfo/python-list #- From sismex01 at hebmex.com Wed Sep 3 11:22:46 2003 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 3 Sep 2003 10:22:46 -0500 Subject: Invisible function attributes Message-ID: [lefevrol at yahoo.com] > > Python 2.3 > >>> def foo(): > ... foo.a = 1 > ... > >>> vars(foo) > {} > >>> foo() > >>> vars(foo) > {'a': 1} > >>> > > So it would appear that function attributes are not really > there until the first call to the function. If that is the > intended behaviour, it is really weird. I couldn't find any > explicit discussion of this topic in the LRM. > > Thanks if anyone can shed some light on this, > not so, function attributes are just like normal object attributes: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> def foo2(): return 9.86960440366 >>> foo2.a = "x" >>> foo2.a 'x' >>> So... the only reason that your 'foo' got it's attribute until you ran it, was because *inside* foo was the definition of said attribute; you could always have defined the attribute outside of foo anytime. -gustavo Advertencia:La informacion contenida en este mensaje es confidencial y restringida, por lo tanto esta destinada unicamente para el uso de la persona arriba indicada, se le notifica que esta prohibida la difusion de este mensaje. Si ha recibido este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Gracias. From mertz at gnosis.cx Tue Sep 23 13:39:39 2003 From: mertz at gnosis.cx (David Mertz) Date: Tue, 23 Sep 2003 13:39:39 -0400 Subject: scp in python References: Message-ID: "Michael" wrote previously: |Is there a scp (ssh) written in Python ? If it's worth anything, in my latest installment on Twisted, for IBM developerWorks: http://www-106.ibm.com/developerworks/linux/library/l-twist4.html I write a trivial 'scp' client as an example. Twisted is almost certainly overkill if you just need scp, and my example does about a tenth of what a real client should. But you could easily develop a real one using the same ideas. Yours, David... -- 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 tdelaney at avaya.com Tue Sep 9 19:44:33 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 10 Sep 2003 09:44:33 +1000 Subject: Eureka! Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEAD4F3B@au3010avexu1.global.avaya.com> > From: Skip Montanaro [mailto:skip at pobox.com] > > Much greater? > > http://tinyurl.com/161 > http://manatee.mojam.com/~skip/ > > If someone is out to deceive you, having them post two URLs > isn't going to deter them. ;-) True - but it gives more information. Perhaps foolishly, I trust you Skip. But not enough to click those links ;) Tim Delaney From stefan.fleiter at web.de Wed Sep 3 05:39:09 2003 From: stefan.fleiter at web.de (Stefan Fleiter) Date: Wed, 03 Sep 2003 11:39:09 +0200 Subject: Difference of hash and __hash__() In-Reply-To: References: Message-ID: Hi, > Looks like a bug to me too. Stefan, please raise a bug report on Sourceforge (or it will get lost). Preferably add a patch and test suite ;) Thanks, will do this evening. Greets, Stefan From tjreedy at udel.edu Fri Sep 19 12:27:10 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Sep 2003 12:27:10 -0400 Subject: Binding frustration References: Message-ID: "Ulrich Petri" wrote in message news:bkesft$105nn$1 at ID-67890.news.uni-berlin.de... > Whenever you use the assignment syntax (foo = bar) you create a "new" > binding unless you have declared the name global. Name assignment (name = expr) always creates a new binding (and deletes any previous binding of the same name). The 'global' declaration only affects which namespace the binding is made in. I believe that any sense in which foo=bar would not make a 'new' binding would be equally applicable to local as well as global binding. Terry J. Reedy From jetman516 at hotmail.com Fri Sep 26 21:12:44 2003 From: jetman516 at hotmail.com (The Jetman) Date: 26 Sep 2003 18:12:44 -0700 Subject: [2.2.1]How To Gracefully Shutdown an XML-RPC Server Message-ID: I'm reading source code, but I haven't found any examples of how to simply shutdown my XML-RPC server. I've done some nice things w/ it so far. I can upload and dload arbitrary files, remotely execute sys commands, etc. But I now want to use this code in a production project and essentially control a FreeBSD box from a MSOFT Access DB application. But the only Python fn I haven't been able to coerce into submission is sys.exit() ! Here's my server method: def sys_Shutdown( self ): # don't work as is.... sys.exit( 0 ) return 0 And here's what happens: Traceback (most recent call last): File "", line 1, in ? File "D:\PYTHON22\lib\xmlrpclib.py", line 821, in __call__ return self.__send(self.__name, args) File "D:\PYTHON22\lib\xmlrpclib.py", line 975, in __request verbose=self.__verbose File "D:\PYTHON22\lib\xmlrpclib.py", line 853, in request return self.parse_response(h.getfile()) File "D:\PYTHON22\lib\xmlrpclib.py", line 896, in parse_response return u.close() File "D:\PYTHON22\lib\xmlrpclib.py", line 571, in close raise apply(Fault, (), self._stack[0]) Fault: This is really bugging me, since I built everything else on my own. Any ideas ? Jet From newsgroups at jhrothjr.com Tue Sep 30 16:01:46 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Sep 2003 16:01:46 -0400 Subject: where are the "class variables"? References: <62e9c66e.0309301057.65f24a3b@posting.google.com> Message-ID: "Dominik Kaspar" wrote in message news:62e9c66e.0309301057.65f24a3b at posting.google.com... > i'm used to java and its strict way of defining variables. so how is > it possible to reach something like a class variable in python? > with the following code i didn't have much succes... > > class Server(threading.Thread): > running = 0 (??) This is correct - it binds 0 to the identifier running in the class. > > def run(self): > running = 1 use Server.running > while running: use while Server.running: > print "do something here..." > > def exit(self): > running = 0 use Server.running > > thanks > -- dominik If you want to put an identifier in the class, reference the class directly, or inherit from object and use a class method. John Roth From jjl at pobox.com Sat Sep 6 08:03:10 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Sep 2003 13:03:10 +0100 Subject: Why python??? References: <87fzjalogu.fsf@pobox.com> Message-ID: <87vfs6unsx.fsf@pobox.com> "Michael Peuser" writes: > "John J. Lee" [...] > > > There are two aspects: > > > (1) More power for same price - this works in favour of 'complex > software' > > > (2) Same power for less money - this works in favor of 'cheap software' > > > > And? What is your point? In both cases, the more bangs per buck, the > > greater the economic advantage that accrues to Python when compared > > with, say, C++. > > There is no linear scaling in these issues. It is of no importance whether a > word processor takes 0.1 sec instead of 0.01 for some operations. It is when > it takes 5 sec instead of 0.5. The issues with hard real time programs are > obvious. Most code is not written for home applications or some esoteric > operating systems as windows but for telecomunication, industry > microcontrollers, car applications,.... Windows is an esoteric OS? Still, you make an interesting point here: is it the case that more code is written for hard real-time systems than not? That would certainly surprise me. Where do you get your data? > May be they will be programmed in Python in 20 years, though I do not see > it. You need a certified compiler, a fail proof and predictable garbage > collector, and a little bit more. Yes. And? We seem not to be communicating here... > This is the matter of 'cheap' software. Sorry, I don't quite follow that. How does that relate to the rest of the paragraph? > Same argument holds for supercomputing as well. I may be wrong but I doubt > that the ASCIs will ever see much Python in their production lifetime. ASICs, you mean? Well, no, but so what? I don't think anybody has ever *claimed* that Python is suitable for that kind of application. [...] > > Python is an order of magnitude easier to learn than C++, but it > > brings really significant programmer-efficiency benefits. As a > > result, the argument about training simply doesn't stand up: the costs > > are lower than the benefits even on a short timescale. > > I know this argument well and have repeated it myself in the days of Pascal > and Algol68. Few have listened..... Well, they'd be right not to listen if you argued it about Pascal. There's a real difference in productivity between Pascal and Python. Pascal doesn't even have built-in garbage collection, for heaven's sake, which places it much closer to C than to Python in this respect. > Programmers are generally not trained in their compyna, thea are hired > including their special language skills. You're begging the question: arguably, that is the mistake of those hiring. Training (for Python, anyway) will frequently be cheaper than sticking to, say, C++. Other skills are more important than pre-existing ability to use a language like Python (though that's certainly not irrelevant!). > > > The fact that a better world is possible does not mean you get it. > > > True (with the definite exception of 'state any new thing you like'!), > > but I get the impression most places don't even try. Obviously, OOP > > *has* swept the industry, and presumably most commercial development > > makes use of version control. > > There is a great, great difference between what really happens and what > management thinks is happening.... Point taken. > [..] > > > Total costs are exactly the issue -- the contention is that use of > > languages like Python really does have a significant impact on that. > > This argument had been used by the most ambitious software tool project of > the last century, which was DoD's Ada. Very few people will ever believe > something like that again ;-) > > > > I should as well like to discuss your aspect of programmer's > productivity. > > > This is an important factor. However all investigations show that > > > programmer's productivity is an unmeasurable quantity. > > > > How would an empirical investigation show such a thing? > > Alex gave a hint to a German study. I think he was refering to: > http://www.ipd.uka.de/~prechelt/Biblio/jccpprtTR.pdf [...] (That was probably the one I was thinking of in another paragraph in my reply) I don't see how such a study could show that "programmer's productivity is an unmeasurable quantity". It's obvious that variations between individuals make differences due to languages hard to measure, but that doesn't make it impossible. John From peter at engcorp.com Wed Sep 3 09:29:54 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Sep 2003 09:29:54 -0400 Subject: Trouble with script fetching site References: <3Zadnamljsa-dMiiXTWc-w@speakeasy.net> Message-ID: <3F55ECD2.48F0BB0B@engcorp.com> Stephen Boulet wrote: > > I'm trying to parse a url to set my hardware & system clock (linux). I can't help with the problem at hand, but I also don't see the reason to do it. Why not just access an NTP server and grab the time the "proper" way? Using a web page is a roundabout way of doing it. There's a nice setclock.py script which Google can point you to which does the job much more easily. -Peter From p.useldinger at myrealbox.com Mon Sep 15 16:30:35 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Mon, 15 Sep 2003 22:30:35 +0200 Subject: unreferenced (???) variable; prob. simple References: Message-ID: <988cmvcgvk1n00gpepp1iimtgfidfihkro@4ax.com> On Mon, 15 Sep 2003 21:31:07 +0200, "Halfdan Holger Knudsen" wrote: >goodday all - here's a snippet of code that just doesn't seem to work...at >all! But I haven't got the faintest idea why I keep getting an unref. >local var. error. Take a look - I know I can get good help here. And PS: >Thanks beforehand. > >begind = 0 >endind = 0 > These variables are not know inside the function. The best solution is to declare them as local variables in the function, as they really are only of use in there, i.e.: def stripfunc() begind=0 endind=0 [... here goes the rest ...] -PU From my at mail.ru Fri Sep 12 05:15:18 2003 From: my at mail.ru (Kerim) Date: Fri, 12 Sep 2003 13:15:18 +0400 Subject: Embeddor Woes... References: Message-ID: <3f618ea9$1@shknews01> PyRun_SimpleFile doesn't work for me too. As a workaround I suggest to replace it with: PyRun_SimpleString("execfile('test.py')"); Kerim "Roel Vanhout" wrote in message news:mailman.1063286417.20657.python-list at python.org... > Have you tried to use embedding.cpp from the boost.python examples? It > will show if your configuration is working OK; if it is, the problem is > obviously in your program. At first sight I'd say that your test.py > can't be found - did you set the right working directories? > > cheers, > > roel > > > Preston H wrote: > > > Hello, someone may have tackled this problem before but I have > > searched the google newsgroups up and down and I can't find anything > > on this. I am trying to write an embedded python program in C++ that > > will go out and execute python language in a script. > > > > I am using Visual C++ .NET, and I do have Multithreaded DLL(/MD) > > turned on for the Runtime Library, I have the Python 2.2 installed and > > their include and libs directories are set. Also, I have Visual C++ > > .NET set to release version, mainly because I cannot find > > python22_d.dll anywhere. > > > > This is the error that I get when I successfully compile this program > > and try to run it at a dos prompt... > > > > The instruction at "0x77f85c41" referenced memory at "0x00000010". > > The memory could not be "written". > > > > This is the source code that I am trying to test... > > > > #include "python.h" > > #include > > > > int main(int argc, char* argv[]) > > { > > char *filename = "test.py"; > > > > FILE *OurFile = fopen(filename, "r+"); > > > > Py_Initialize(); > > > > PyRun_SimpleFile(OurFile, "test.py"); > > > > Py_Finalize(); > > > > return 0; > > } > > > > Like I said earlier, the program compiles without any hitches. Any > > help on this is appreciated very much! > > > -- > > -- > Roel Vanhout - Programmer/Systems Administrator > RIKS BV > Papenstraat 8 - 6211 LG Maastricht > Tel +31 (0)43 388 3708 - Fax +31 (0)43 325 3155 > > From duncan at NOSPAMrcp.co.uk Fri Sep 12 11:09:00 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 12 Sep 2003 15:09:00 +0000 (UTC) Subject: Internal Debugger Question References: <6ee58e07.0309120604.3a1f4985@posting.google.com> Message-ID: llothar at web.de (Lothar Scholz) wrote in news:6ee58e07.0309120604.3a1f4985 at posting.google.com: > i'm currently writing a debugger for python and found that some > modules store an absolute file path in "co_filename" of there > methods/functions and some store a relative file path. Because the > relative file path can never be expanded to an absolute file path > later (the sys.path may have changed) it is impossible to find the > source code location. > > Is there anything i have missed or is this simply a bug. I would > highly recommend to fix this bug ! Are you running Python 2.3, if not you should upgrade as the behaviour has changed? The only relative paths I can see are for the script itself. Other modules, even when loaded through a relative path store the absolute value of the name. Before trying to use the stored filename, remember that as of Python 2.3 you can have custom loaders, so the 'filename' might not refer to a path at all (although the loader might have a get_source method to help you). Even if it does refer to a path, the path might not be valid when you come to use it, if for example it was a path to a network drive which is no longer accessible. I think the best you can do in this situation is to try to use the path information you are given, and if you can't find a suitable source file either prompt the user or just give up. -- 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 rajarshi at presidency.com Sun Sep 14 18:00:48 2003 From: rajarshi at presidency.com (Rajarshi Guha) Date: Sun, 14 Sep 2003 18:00:48 -0400 Subject: singleton or Borg? Message-ID: Hi, I'm having a little problem with understanding the working of a singleton and borg class. Basically I nedd an class whose state will be shared across several modules. I found the stuff on the ASPN cookbook but it does'nt seem to be working for me. I've included some code: Borg.py: -------- class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state self.val = {} class Singleton(object): def __new__(type): if not '_the_instance' in type.__dict__: type._the_instance = object.__new__(type) return type._the_instance class Tester(Singleton): def __init__(self): self.val = {} t.py: ----- import Borg,v x = Borg.Tester() x.val['a'] = 1 print x.val v.func() print x.val v.py: ----- import Borg def func(): y = Borg.Tester() print y.val, '...from t.py' y.val['a'] = 2 return I had expected to see: {'a':1} {'a':1} ...from t.py {'a':2} However I get {'a':1} {} ...from t.py {'a':2} Should'nt the instantiation of val in v.func() just use the val that was already created when it was instatntiated in t.py? I just cant seem to wrap my head around this oen, so any suggestions would be appreciated. Thanks From bokr at oz.net Thu Sep 11 19:23:37 2003 From: bokr at oz.net (Bengt Richter) Date: 11 Sep 2003 23:23:37 GMT Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> <66t0mv410it5ftvjokfpkov0v029trv6lp@4ax.com> Message-ID: On Thu, 11 Sep 2003 16:44:28 -0400, "Terry Reedy" wrote: > >"Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote >in message news:66t0mv410it5ftvjokfpkov0v029trv6lp at 4ax.com... > >> Actually I'm sick to death of the old 'your just trying to turn >Python >> into X' argument whenever I suggest that *maybe* Python might learn >a >> trick from another language. [etc] > >This seems to be a predictible c.l.py response to proposals. I got >similar accusations several years ago, which made me similarly sick, >when I proposed the addition of list.pop() (which Guido did, in more >generalized form, about a year later). > >My main objection was/is that expressed by Michael Chermside today: >this would complexify a simplicity that I consider a good feature of >Python. Reading Bengt Richter's lastest response, also today, I >realize that 'ref x' would have to have much the same effect of Lisp's >FEXPR defun keyword -- of automatically quoting rather than evaluating >args -- although on just one rather than all. Perhaps you should be >accused of 'trying to Lispify Python' -- or perhaps not ;-). > If we had a wrapper for rebinding targets, then maybe such a wrapper could be passed to functions and used in a uniform way. E.g., faking it with real python: >>> class GAW(object): # Generalized Access Wrapper ... def __init__(self, thing, key): ... self.thing=thing ... self.key=key ... def _getv(self): ... try: return self.thing[self.key] ... except: pass ... try: return getattr(self.thing, self.key) ... except: pass ... raise KeyError,'%r is not key or attribute of %r'%(self.thing, self.key) ... def _setv(self, v): ... try: self.thing[self.key]=v ... except: ... try: setattr(self.thing, self.key, v) ... except: raise KeyError,'%r is not key or attribute of %r'%(self.thing, self.ke ... value = property(_getv,_setv) ... >>> a= ['foo', [23]] Oops, I should have called this Inc ;-) >>> def foo(aw): ... aw.value = aw.value + 1 ... >>> aaw = GAW(a[1], 0) >>> aaw.value 23 >>> foo(aaw) >>> a ['foo', [24]] >>> aaw.value 24 >>> z=100 >>> foo(GAW(globals(),'z')) >>> z 101 Maybe something could be done in C and with compiler support to implement safe access via deferral of the final access tail term of a target expression, using an object with an apparent value property that works more or less as above -- but so you could spell it e.g., awrap(z) or awrap(obj.x) or awrap(a[1][0]) by some magic ;-) The compiler would have to know about awrap, so it could separate the final access mechanism in the expression and create the code to create the appropriate access object... (a lot of hand waving, but maybe not impossible?) Regards, Bengt Richter From tzot at sil-tec.gr Thu Sep 25 14:35:00 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 25 Sep 2003 21:35:00 +0300 Subject: 64-bit EPIC and some modules References: <7h3smmm2m0w.fsf@pc150.maths.bris.ac.uk> <0ck3nvoicm45kb0oon2etsucttatc3aob7@4ax.com> <7h3ad8t2k6q.fsf@pc150.maths.bris.ac.uk> Message-ID: <89d6nv85qdrvegiehk25rpkpirogvqspgi@4ax.com> On Thu, 25 Sep 2003 11:20:27 GMT, rumours say that Michael Hudson might have written: >PS: hp-ux/itanium appears to be utterly horked... Thank God this is not a HP/UX then... presumably. See PS. PS: What is horked??? -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From BjornPettersen at fairisaac.com Tue Sep 16 14:49:21 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Tue, 16 Sep 2003 13:49:21 -0500 Subject: None, False, True Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624A5F@stpmsg00.corp.fairisaac.com> > From: M-a-S [mailto:NO-MAIL at hotmail.com] > > Can anybody explain this: sure. > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. You're running Python 2.3 on a windows os. > >>> > >>> None = 3 you're assigning the value 3 to the name 'None' > :1: SyntaxWarning: assignment to None the compiler warns you that 'None' is a special name that you probably don't want to rebind. > >>> False = 4 you assign the value 4 to the name 'False' > >>> True = 5 you assign the value 5 to the name 'True' > >>> None, False, True > (3, 4, 5) The interpreter prints the value of the tuple you entered. Which part of this didn't you understand? (my mind-reading skills are too rusty to determine if you think this shouldn't happen for some reason...) -- bjorn From h.b.furuseth at usit.uio.no Fri Sep 19 07:15:50 2003 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth (nospam nospam)) Date: 19 Sep 2003 13:15:50 +0200 Subject: convert Unicode to lower/uppercase? Message-ID: Has someone got a Python routine or module which converts Unicode strings to lowercase (or uppercase)? What I actually need to do is to compare a number of strings in a case-insensitive manner, so I assume it's simplest to convert to lower/upper first. Possibly all strings will be from the latin-1 character set, so I could convert to 8-bit latin-1, map to lowercase, and convert back, but that seems rather cumbersome. -- Hallvard From jb.richet at areas.asso.fr Fri Sep 12 07:01:20 2003 From: jb.richet at areas.asso.fr (Jean-Baptiste Richet) Date: Fri, 12 Sep 2003 12:01:20 +0100 Subject: using weave with Windows Message-ID: <3F61A780.2030208@areas.asso.fr> Hello, weave could be highly usefull to me, but I can't have it work correctly on my PC, and I can't understand the error message. Could you help me ? I installed the latest zip package by "python setup.py install", on a python 2.3 installation (OS = Windows ME), and here is a result when trying it : ========================= IDLE 1.0 >>> import weave >>> a = 123 >>> weave.inline('printf("%d\\n",a);',['a']) Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in Traceback (most recent call last): File "", line 1, in -toplevel- weave.inline('printf("%d\\n",a);',['a']) File "C:\DEVELOPPEMENT\PYTHON23\Lib\site-packages\weave\inline_tools.py", line 327, in inline auto_downcast = auto_downcast, File "C:\DEVELOPPEMENT\PYTHON23\Lib\site-packages\weave\inline_tools.py", line 426, in compile_function verbose=verbose, **kw) File "C:\DEVELOPPEMENT\PYTHON23\Lib\site-packages\weave\ext_tools.py", line 349, in compile verbose = verbose, **kw) File "C:\DEVELOPPEMENT\PYTHON23\Lib\site-packages\weave\build_tools.py", line 194, in build_extension setup(name = module_name, ext_modules = [ext],verbose=verb) File "c:\developpement\python23\lib\distutils\core.py", line 166, in setup raise SystemExit, "error: " + str(msg) CompileError: error: command 'g++' failed with exit status 1 >>> =========================== The gcc I use comes from MinGW and is version 3.2. I tried out gcc 2.95, and it was nearly the same (error at the same place, but 'cc' was blaimed). I tried cygwin, and it was not different. I tried python 2.2, and the result was similar. Any idea ? thanks a lot for your help. From martin at v.loewis.de Sun Sep 7 03:24:55 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Sep 2003 09:24:55 +0200 Subject: Need help on UNICODE conversion References: <5lbklvgtlm6l4e1n51tnbin151drrh4410@4ax.com> <3F5A5905.9E8571E3@alcyone.com> <9pdllvgk17b3cetat24g9uj4hq9la7umt3@4ax.com> <3F5AC603.C35AC004@alcyone.com> Message-ID: Erik Max Francis writes: > >>> u = unicode(codecs.BOM_UTF16_BE + u, 'utf-16') > >>> u > u'Kommentar Unicode *\xe4\xf6\xfc\xc4\xd6\xdc\xdf*\r\n\r\n' > > ... which I can convert to Latin-1 and print to then see the umlauts and > the double S. It is better to use "utf-16-be" as the codec name in the first place, instead of artificially prepending a BOM, and letting the UTF-16 codec determine byte order. Regards, Martin From op73418 at mail.telepac.pt Thu Sep 11 18:25:25 2003 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 11 Sep 2003 23:25:25 +0100 Subject: list to string References: Message-ID: On Thu, 11 Sep 2003 23:07:38 +0100, Graham Nicholls wrote: >Hi. Sorry if this is really dim, but I'm trying to do something like: > >main (args): > fhand=open(args[1:],"r+") > args[1:] is a slice. So if args is a list, args[1:] is a list, if it's a string, it's a string, etc... open expects a string -- as you probably have already figured out. >and get an error that open is expecting a string not a list. > So either you are passing the wrong argument: e.g. a list instead of a string, or then, if you do want to pass a list then you have to change your code. But now the course to follow depends on what you want to do. So you have to explain a little more. With my best regards, G. Rodrigues From bgailer at alum.rpi.edu Mon Sep 15 10:45:10 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 15 Sep 2003 08:45:10 -0600 Subject: I: caching the sql queries In-Reply-To: <003501c37b7c$486781d0$410100a4@utente65> References: <003501c37b7c$486781d0$410100a4@utente65> Message-ID: <6.0.0.22.0.20030915084315.041ddaf8@66.28.54.253> At 05:27 AM 9/15/2003, Luca Calderano wrote: >I MEAN YOU CAN ACCESS ADO TROUGHT COM >AS EXPLAINED HERE: > >import win32com.client >import locale >from os import sys > > >adCmdStoredProc = 4 # Evaluates CommandText as a stored procedure >name. >adCmdTable = 2 # Evaluates CommandText as a table name. >adInteger = 3 # A 4-byte signed integer. >adParamInput = 0x1 # from enum ParameterDirectionEnum > > >class DBConnect: > def __init__(self): > self.Cnn = win32com.client.Dispatch(r'ADODB.Connection') > self.ConnStr = r'File Name=C:\Graal.dsn' I want to learn form your excellent example. What is the function of r'File Name=C:\Graal.dsn' in this context? Can I use this approach to connect to MS SQL Server? and if so how? what would the connection string be? [snip] Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From peter at engcorp.com Thu Sep 18 09:03:11 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Sep 2003 09:03:11 -0400 Subject: was: Re: looking for MOP documentation References: <3F62123C.F671D058@engcorp.com> <3F6319E9.4C7BAA0F@engcorp.com> <3F66F516.3D06D946@engcorp.com> Message-ID: <3F69AD0F.53D51719@engcorp.com> Paul Foley wrote: > > On Tue, 16 Sep 2003 07:33:42 -0400, Peter Hansen wrote: > > > Ng Pheng Siong wrote: > >> > >> According to Peter Hansen : > >> > kasper graversen wrote: > >> > > On Fri, 12 Sep 2003 14:36:44 -0400, Peter Hansen wrote: > >> > > >> Erm, what's "MOP" mean? > >> > > what has all this talk to do with documentation of the MOP??? > >> > Er, if you'll look back, you'll see that Anthony asked what MOP > >> > meant > >> > >> Meta Object Protocol. > > > Thanks, but one might say that this is what it spells, not what it _means_. > > Read the introduction to _The Art of the Metaobject Protocol_, at > http://www2.parc.com/csl/groups/sda/publications/papers/Kiczales-AMOP/ Thanks Paul. If that description is taken as authoritative about "the MOP", then it seems to me after a first reading that Python *has no MOP*, and probably will not, given Guido's approach to language design. Am I correct? Or does the term really have a broader meaning than what I get out of that page, and Python in fact has aspects that could be called its meta-object protocol? Key phrase: "Metaobject protocols are interfaces to the language that give users the ability to incrementally modify the language's behavior and implementation...". Near as I can tell, part of the whole character of Python is that a user *cannot* do either of those things. -Peter From newsgroups at jhrothjr.com Mon Sep 15 16:27:54 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 15 Sep 2003 16:27:54 -0400 Subject: calling objects parents' __init__? References: Message-ID: wrote in message news:e13963e818473ad69d0a49230e328b91 at news.teranews.com... > Normally, when I inherit from a class that I have written, > I want instances of the new class to call the __init__ of > the old (actually, starting from the top of the tree, and > moving on down). > > What is the preferred way to do this? If you're using a new style class (one that inherits from object,) look at the super() built in function. Be a bit cautious with it, the usage isn't exactly obvious. There's also an article on the method resolution order somewhere that makes quite interesting reading. If you're using an old style class, you have to call them directly: superklas.__init__(self). John Roth > > Thanks, > > Tobiah > From aleax at aleax.it Thu Sep 25 10:01:04 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Sep 2003 14:01:04 GMT Subject: "for" with "else"? References: Message-ID: Invalid User wrote: > While trying to print a none empty list, I accidentaly put an "else" > statement with a "for" instead of "if". Here is what I had: > > if ( len(mylist)> 0) : > for x,y in mylist: > print x,y > else: > print "Empty list" > > which was supposed to be: > > if ( len(mylist)> 0) : > for x,y in mylist: > print x,y > else: > print "Empty list" > > > Is this to be expected? Sure. The else branch is executed unless the for terminates prematurely (via break, return or exception) -- just like the else branch of a while loop. Typical use case: for item in allitems: if fraboozable(item): print "first fraboozable item is", item break else: print "Sorry, no item is fraboozable" Alex From rune.hansen at viventus.no Sat Sep 27 06:45:20 2003 From: rune.hansen at viventus.no (Rune Hansen) Date: Sat, 27 Sep 2003 12:45:20 +0200 Subject: unicode 3 digit decimal conversion In-Reply-To: References: Message-ID: <5Tddb.26096$os2.360623@news2.e.nsc.no> Hi, The tip from Klaus "solved" my problem for the time beeing, but your snipplet definitively goes into my "tool chest" thanks regards /rune Martin v. L?wis wrote: > Rune Hansen writes: > > >>What I need is the converted string to read u'Gratis \248l' (* >>How do I do this without going through each and every character of the >>string? > > > You can register an error callback, like this: > > import codecs > > def decimal_escape(exc): > try: > data = exc.object > res = u"" > for i in range(exc.start, exc.end): > char = ord(data[i]) > if char < 1000: > res += u"\\%03d" % char > else: > # Unsupported character > raise exc > > return res, exc.end > except: > raise exc > > codecs.register_error("decimal-escape", decimal_escape) > > print u"Gratis \xf8l".encode("us-ascii", "decimal-escape") > > Notice That your specification is a bit unclear as to what to do with > characters > 1000; I assume they are not supported in your protocol. > > Regards, > Martin > From anthony at interlink.com.au Thu Sep 11 01:43:52 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 11 Sep 2003 15:43:52 +1000 Subject: TTF fonts rendered in Python In-Reply-To: <20030910201019.GA22261@bobas.nowytarg.pl> Message-ID: <200309110543.h8B5hqDX010079@localhost.localdomain> >>> vald wrote > > I wonder if there is any module for rendering True > Type Fonts in Python ? I need to create a GIF files > with nice antialiased text and I'm unable to find > any module with such functionality. www.pygame.org From FBatista at uniFON.com.ar Mon Sep 1 12:30:09 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 1 Sep 2003 13:30:09 -0300 Subject: HELP : class and variables Message-ID: #- class test: #- var1=1 #- var2=2 #- res=var1+var2 #- #- t=test() #- print t.res #- >> 3 So far OK. #- t.var1=6 #- print t.res #- >> 3 Because you can not change a class attribute changing the instance attribute. Just google for "class variables in python". . Facundo From __peter__ at web.de Fri Sep 19 19:56:53 2003 From: __peter__ at web.de (Peter Otten) Date: Sat, 20 Sep 2003 01:56:53 +0200 Subject: whitespace References: Message-ID: RR wrote: > Is there an easy way in python to remove whitespace from a string? >>> import string >>> "a b c".translate(string.maketrans("", ""), string.whitespace) 'abc' >>> Peter From achalk at XXXmagnacartasoftware.com Wed Sep 24 05:13:24 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Wed, 24 Sep 2003 09:13:24 GMT Subject: Executing a python script from an HTML link? References: <1t%bb.407$Q44.601209120@newssvr11.news.prodigy.com> <3F7089DA.EB6E9969@hotmail.com> Message-ID: Thanks! "Alan Kennedy" wrote in message news:3F7089DA.EB6E9969 at hotmail.com... > [Andrew Chalk] > > I want to run the script on the server. > > Then you will need to figure out how to run the script on the server > ;-) > > If you're not aware of how to do this, then it's probably best for you > to read up on CGI, which is way of getting web servers to execute > scripts (in any language) when the scripts URL is requested. > > > The problem is that I don't > > have an html page as an HREF. Viz: > > > > Fred > > What replaces Fred.htm to invoke a server-side script? > > Whatever is the URL of your script on your server. Examples include > > http://www.mydomain.com/cgi-bin/myscript.py > http://www.mydomain.com/cgi-bin/myscript.cgi > http://www.mydomain.com/cgi-bin/myscript.py?paramA=v1¶mB=v2 > > Your python script should then generate (i.e. print out) an HTML page > when it is run (actually it can generate anything, images included, > but HTML is a good place to start). The server takes the output of > your script and sends it to the requesting browser. The browser has no > way of knowing that the HTML did not come from a static file. > > You can read about Python and CGI here:- > > http://starship.python.net/crew/davem/cgifaq/faqw.cgi?req=index > > There are other "linkage mechanisms" by which you can cause the > execution of scripts on a server, e.g. mod_python, but none is > conceptually as simple as CGI. Also, CGI tends to be more portable > between different server software, and is almost always supported by > hosting providers. > > HTH, > > -- > alan kennedy > ----------------------------------------------------- > check http headers here: http://xhaus.com/headers > email alan: http://xhaus.com/mailto/alan From Vincent.Raaijmakers at ge.com Mon Sep 1 20:12:35 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Mon, 1 Sep 2003 19:12:35 -0500 Subject: Structured writing to console, such as a table Message-ID: <971323274247EB44B9A01D0A3B424C8541FC5E@FTWMLVEM02.e2k.ad.ge.com> Wow thanks! Agree, sometimes you need to reinvent the wheel. But this time I had the feeling that this way of presenting information was something that was very well "thought out", done before even markup language was 'born'. When looking at examples, modules etc I noticed indeed that data easily can be presented in PDF, HTML, LaTex format. There is a lot of good python stuff available. Sometimes I can not believe it is all for free. But such a simple thing like writing strings/data well structured to a console, who is doing that these days :-) Thanks a lot for sharing your thoughts, but also all other people who shared their code and useful links! Vincent -----Original Message----- From: Paul Moore [mailto:pf_moore at yahoo.co.uk] Sent: Monday, September 01, 2003 6:46 PM To: python-list at python.org Subject: Re: Structured writing to console, such as a table "Raaijmakers, Vincent (IndSys, GE Interlogix)" writes: > Ok, perhaps a question on a newbie level. > > I try to create a simple 'write to a console application' where all > the items in a string do have a variable size: > items = ["a", "bbbbbbbbb", "cc"] > Well, actually, I need to print a table as simple text, nice lined > up in a console. So: > > > Item: Value: Another Value: > ----------+----------+------------------ > a | 1 | 2 > bbbbbbbbb | 2 | 17 > cc | 3 | 5 > > My hope was that somewhere in python land an existing module was > waiting for me. A module that also prints lines, headers.... > > Unfortunately, I can't find it. Books, Google... > Before I reinvent this wheel... please give me some tips, > references, examples... This is going to sound unhelpful, but I suspect the problem is that the problem is too simple - everyone *does* reinvent the wheel, because it's faster than going to find a generic solution. Having said that, I didn't manage to quickly write some code for you :-) The first question is, what does your data look like? From your example, I'd say that you have a list of items items = ["a", "bbbbbbbbb", "cc"] but I'm not sure how you get your values. Let's assume that in fact you have a "list of rows" type of representation: rows = [["a", 1, 2], ["bbbbbbbbb", 2, 17], ["cc", 3, 5] ] This may or may not match your requirements, but you should be able to either adapt my code or your data as needed. The first problem is working out the column widths you need. That's not difficult, just messy (because in some senses, the data is "the wrong way round" - a list of coumns would be better for this step, but worse later on). def column_widths(titles, rows): '''Calculate column widths for a "list of rows"''' # Initialise widths to have all columns zero width to start with widths = [len(str(title)) for title in titles] # Adjust the width to allow space for each row in turn for row in rows: widths = [max(w, len(str(item))) for w, item in zip(widths, row)] return widths That's a bit messy, so let's dissect it. I use list comprehensions a lot here - if you don't know how they work, it's well worth studying them. We start by setting widths to fit the titles. We assume that all rows have the same number of elements - I don't check for this. Then, for each row, we adjust the widths to fit the items in that row. The list comprehension goes through each column, and the new width of that column is either the old width (if the new item fits already) or the length of the new item (if it is the biggest so far). For each item, we're calculating len(str(item)) which is the length of the string representation of the item - ie, the space required on screen for that item. OK, that was the ugly bit - now we just format the results. This is simple, but a little long winded. def format(titles, rows): "Format a table" # First calculate the column widths widths = column_widths(titles, rows) # Create the result as a list of lines - it's more flexible # than printing directly result = [] # Title line first (add 3 spaces between colums) line = ' '.join([t.ljust(w) for t, w in zip(titles, widths)]) result.append(line) # Separator line (add -+- between columns) line = '-+-'.join(['-' * w for w in widths]) result.append(line) # Rows of data for row in rows: line = ' | '.join([item.ljust(w) for item, w in zip(row, widths)]) result.append(line) return result Now you can do: print "\n".join(format(titles, rows)) I hope this helps. As I say, the problem is often that matching the algorithm to what you really want is harder than writing the code in the first place, so don't be afraid to play with this (it's nearly midnight, so I'm offering no guarantees that this code is correct :-)) Paul -- This signature intentionally left blank -- http://mail.python.org/mailman/listinfo/python-list From RobMEmmons at cs.com Sun Sep 21 23:21:53 2003 From: RobMEmmons at cs.com (RobE) Date: Sun, 21 Sep 2003 22:21:53 -0500 Subject: I love this language! References: Message-ID: > I'm a complete newbie to Python and have been working the tutorials for > only about 4 days (I'm doing 'How to Think Like a Computer Scientist' > right now) but I already love this language. It's much easier for me to > learn so far than others I have tried, with the possible exception of > BASIC. I'm in complete agreement. I could not have but it better. I learned it in an afternoon 3 years ago and have never gone back! I think one could argue that python is the best and most veristile langauge out there--easy to learn, fast to code, wide application range, ... and cross platform too... WOW! Rob From dave at pythonapocrypha.com Wed Sep 24 09:47:53 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Wed, 24 Sep 2003 07:47:53 -0600 Subject: Windows dialog box removal In-Reply-To: References: Message-ID: <200309240747.53550.dave@pythonapocrypha.com> On Thursday 25 September 2003 06:18 am, SectorUnknown wrote: > I've written a Python script that runs a MS Windows program using popen. > However, at the end of the Windows program, a dialog box appears and > asks for the user to click on OK. > > Is there a way to have Python set focus on the dialog box and click OK > so my script can continue? > > Does anyone have an example? I wouldn't be surprised if there's an easier or more correct way to do this, but if you can reliably know the title of the window then the code below should work (assuming you have ctypes installed): from ctypes import * user32 = windll.user32 EnumWindowsProc = WINFUNCTYPE(c_int, c_int, c_int) def GetHandles(title, parent=None): 'Returns handles to windows with matching titles' hwnds = [] def EnumCB(hwnd, lparam, match=title.lower(), hwnds=hwnds): title = c_buffer(' ' * 256) user32.GetWindowTextA(hwnd, title, 255) if title.value.lower() == match: hwnds.append(hwnd) if parent is not None: user32.EnumChildWindows(parent, EnumWindowsProc(EnumCB), 0) else: user32.EnumWindows(EnumWindowsProc(EnumCB), 0) return hwnds Here's an example of calling it to click the Ok button on any window that has the title "Downloads properties" (most likely there are 0 or 1 such windows): for handle in GetHandles('Downloads properties'): for childHandle in GetHandles('ok', handle): user32.SendMessageA(childHandle, 0x00F5, 0, 0) # 0x00F5 = BM_CLICK -Dave From godoy at metalab.unc.edu Tue Sep 30 07:08:26 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 30 Sep 2003 08:08:26 -0300 Subject: Threading and Windows. References: Message-ID: Dennis Lee Bieber writes: > Jorge Godoy fed this fish to the penguins on Monday 29 September 2003 > 07:31 pm: > >> >> This isn't the behaviour I found here on a Linux box. The caller >> process got 'stuck' and only worked again when the called proccess >> ended. >> > Strange... I thought the same thing and even thought I was using os.spawnv() in a wrong way. Even with the 'P_NOWAIT' flag it still hangs. I'm using: Python 2.2.2 (#1, Mar 6 2003, 13:36:19) [GCC 3.2.2] on linux-i386 I haven't investigated os.spawnv() alone in Windows to see if this also happens there. It will be funny if by this very first time the problem is on the Linux box instead of the Windows box (since I'm more used to unices, I'm more familiar with their quirks than with Windows', specially with all those 'flavours' of Windows...). > I think NT has the ability to go by extension, but not W9x. Windows XP can't go by extension either. > You might have to explicitly invoke the python executable, and pass > /it/ the .py file as the first argument I see. If it doesn't work using os.startfile() as suggested on another message I'll probably stick with this approach. Thanks! -- Godoy. From skip at pobox.com Fri Sep 26 14:30:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 26 Sep 2003 13:30:30 -0500 Subject: PEPs link gone from the Python homepage? In-Reply-To: References: <16244.22946.446379.622160@montanaro.dyndns.org> <16244.30758.381156.351062@montanaro.dyndns.org> Message-ID: <16244.34246.325809.733705@montanaro.dyndns.org> >> It's still readily accessible, but it's hard to see that "PEPs" >> should rank up there on the front page with more general concepts >> like "Documentation" or "Developers". Front page real estate is >> always at a premium. I think it's appropriate that they are referred >> as they are now. Dave> Yeah, but after the front page I looked under "Documentation" and Dave> didn't find it either. Ah, but it was there. ;-) I don't know if we need to more consistently name them. On the /Developers page it's called "PEP Index". On the /Documentation page it's listed twice, once as "Python Enhancement Proposals (PEPs)" and later on as simply "PEPs". In both cases, the link you were used to changed from the top margin to the left margin (I think). All three links are to the root PEP page. I'll generate those two pages and make the link read the same. "PEP Index" seems right to me. Long enough not to miss, but not so long that it wraps lines. I don't think displaying "Python Enhancement Proposals" aids comprehension anyway, since everyone refers to them as "PEPs". >> On matters such as this, I don't even bother with the website. My >> browser home page is a bunch (17) of popup menus laid out in a >> tabular format and a few
s. It has two Python-related menus: ... Dave> Setting up infrastructure takes time, though. That's what sucks Dave> about computers: you gotta spend time to save time :( Agreed. I've been using the same basic home page for several years, so the investment paid off long ago. About all I do these days is add or delete a site to one of the menus. (Another positive side effect is that if I change browsers I don't need to worry about how to migrate bookmarks from old to new.) Skip From nav+posts at bandersnatch.org Mon Sep 8 13:35:09 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 08 Sep 2003 13:35:09 -0400 Subject: OT: Americans love their guns References: Message-ID: Steve Lamb writes: > Do this simple test. Get an egg timer (or any other timing device). > Now set it to 4, maybe 5 minutes. Now lock yourself in the closet. Counter-test: Imagine your seven-year-old son finding your gun and shooting and killing your five-year-old daughter while you're working in your study. That scenario is much more likely, statistically speaking, than the absurd home invasion fantasy you posted. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From martin at v.loewis.de Thu Sep 25 18:50:47 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 26 Sep 2003 00:50:47 +0200 Subject: [Python-Dev] Re: RELEASED Python 2.3.1 In-Reply-To: References: <200309240802.h8O82mqF026019@localhost.localdomain> Message-ID: "Jason R. Mastaler" writes: > Python 2.3.1 (#1, Sep 24 2003, 15:55:24) > [GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> from os import fsync > Traceback (most recent call last): > File "", line 1, in ? > ImportError: cannot import name fsync > >>> Why is that a bug? Your system just does not have a declared fsync function. Regards, Martin From peter at engcorp.com Mon Sep 29 09:11:09 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 29 Sep 2003 09:11:09 -0400 Subject: Checking for invalid keyword arguments? References: Message-ID: <3F782F6D.29E0CF5F@engcorp.com> Roy Smith wrote: > > I've got a function that takes a couple of optional keyword arguments. > I want to check to make sure I didn't get passed an argument I didn't > expect. By the way, you didn't explain why you don't want to get passed arguments you didn't expect. Can't you simply ignore them? That way you can easily expand the API in future versions yet maintain a certain amount of compatibility. -Peter From tchur at optushome.com.au Sun Sep 28 22:21:42 2003 From: tchur at optushome.com.au (Tim Churches) Date: Mon, 29 Sep 2003 12:21:42 +1000 Subject: Python mascot? How about a Pythoneer? Message-ID: <200309290222.h8T2LqI17132@mail012.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From tjreedy at udel.edu Sat Sep 6 15:53:22 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Sep 2003 15:53:22 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <3f59014d$0$152$a1866201@newsreader.visi.com> <3f591d28$0$175$a1866201@newsreader.visi.com> <7ihe3pewu8.fsf@enark.csis.hku.hk> Message-ID: "Isaac To" wrote in message news:7ihe3pewu8.fsf at enark.csis.hku.hk... > class foo: > def __init__(msg): > self.msg = str(msg) > def f(arg): > print self.msg + ', ' + str(arg) > v = foo('hello') > v.f('world') # equivalent to foo.f(v, 'world') I think this equivalence, being an answer to the subject sentence, needs more emphasis. An instance method is a wrapped function and a *class* attribute. The 'proper' way to call such functions, consistent with all other function calls, is klass.meth(inst, *rest_of_args), with inst as an explicit first arg matching the explicit first parameter in the definition. To me, having an explicit arg match an implicit param would be a warty inconsistency. >From this viewpoint, inst.meth(*rest_of_args) is a conveinient abbreviation that works because of the attribute inheritance and lookup mechanism. Of course, beyond being just syntactic sugar, it adds the very important flexibility of the programmer not having to know precisely which base class will provide the method. I think the long form of method call should be taught first, and then the abbreviation and behavioral reason for its existence. (Perhaps then, we would have fewer threads on this topic ;-) If an ad hoc 'self'-rule were added, the inconsistency would have to be consistently applied to all function definitions. Python attaches little special importance to the presence of a def within or without a class suite. Absent a metaclass override that affects function wrapping only for those in the .__new__() dict arg but not when later assigned, class k(object): # or no object def f(self): pass nicely abbreviates def f(self): pass class k(object): pass k.f = f del f Terry J. Reedy From __peter__ at web.de Thu Sep 25 12:25:24 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2003 18:25:24 +0200 Subject: Snakeoil alert (was Re: newbie script) References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> <3f719ed5$0$14824$79c14f64@nan-newsreader-03.noos.net> <3f72eb7c$0$29964$79c14f64@nan-newsreader-02.noos.net> Message-ID: Peter Otten wrote: > However, I have noticed that when I copy and paste from KNode 7.2 using > Strg+C/Strg+V instead of the middle mouse button, all '\xa0' are magically > converted back to old '\x20' space characters. Sorry, I have tried to reproduce the behaviour stated above and was not able to reproduce it. So whatever I did differently, it was not the copy and paste method :( Peter From vze4rx4y at verizon.net Thu Sep 25 14:38:20 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 25 Sep 2003 18:38:20 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> Message-ID: [Stephen Horne] > The question is - is the exercise worthwhile. I'm not sure even though > it's my own idea. I think it is nice in its way, and a lot more > flexible than the 'iter_backward' method proposal, but that is quite > likely a bad thing as it is probably massive overkill for the problem > being solved - and in particular the extra flexibility has costs. > > What the hell, though - it was fun to play with for a bit! Yes, it's a one ton solution to a one ounce problem, but it was an interesting exercise and diversion. Raymond Hettinger From dave at 3dex.com Thu Sep 11 19:43:30 2003 From: dave at 3dex.com (Dave Benjamin) Date: Thu, 11 Sep 2003 23:43:30 GMT Subject: Flash Remoting in Python? References: <7712111.0309111357.3be3b591@posting.google.com> <2E78b.1002$8g2.829@news1.central.cox.net> Message-ID: "Dave Benjamin" wrote in message news:2E78b.1002$8g2.829 at news1.central.cox.net... > Another way to set up an RPC interface between Flash and Python would be to > use plain old HTTP GET/POST, with either urlencoded key-value pairs or WDDX > as a serialization format. (PyXML supports WDDX, as does PHP, as does Flash > if you Google around for the wddx.as script). Just FYI, you can find the ActionScript WDDX modules here: http://chattyfig.figleaf.com/ And on the Python side, for starters, try getting this to work: >>> from xml.marshal import wddx >>> wddx.dumps('hello') '
hello' Dave From __peter__ at web.de Thu Sep 18 11:53:35 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2003 17:53:35 +0200 Subject: How to inheritance overwrite non virtual? References: Message-ID: Axel Straschil wrote: > Hi! > >> The following will do: >> >> class Derived(Base): >> def method(self): >> return Base.method(self) # call base class method > > I tried in my chield-class: > class K2(KObject): > def bestCaption(self): > return "Overwritten" > def bestCaptionlong(self): > return KObject.bestCaptionlong(self) > > The Problem ist inside of KObject.bestCaptionlong(self): > return self.bestCaption() > > The mother-class is calling the method of the child-class, not > it own method. I want the mother-method to be called like "the > chield never was existing", but I find no way. > > Anny other idea? > > Thank, AXEL. What you want seems to be class KObject: def bestCaptionlong(self): # class made explicit to guard against overriding return KObject.bestCaption(self) Some additional remarks: Do-nothing accessor methods may be acceptable style in C++ but are superfluous in Python. The abundance of xxxCaption and label attributes somewhat obscures your design goal for me, but usually the ability to override a method to change its effect is a feature, not something to fight against. Peter Peter From ville.spammehardvainio at spamtut.fi Fri Sep 12 10:00:17 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 12 Sep 2003 17:00:17 +0300 Subject: Cool & Useful EmPy project, prior art? References: <1D58b.2052$vQ1.113255@nnrp1.ozemail.com.au> Message-ID: > of the Emacs distribution). They are template.el and skeleton.el. There are > no existing (to my knowledge) template definitions for Python with these > Emacs modes but I am sure they wouldn't be too hard to produce if you prefer > this form of interface. I really would like to write the templates in EmPy. I'm not actually thinking of creating a whole file, but small snippets of code to paste into pre-existing C++ code (with Python, I wouldn't even *need* such a program). I coded a few elisp functions, saw that the approach sucked, and would really prefer an external program communicating through clipboard; that way my Visual Studio wielding colleagues could benefit from the program & templates as well. -- Ville Vainio http://www.students.tut.fi/~vainio24 From bdelmee at advalvas.REMOVEME.be Wed Sep 3 16:52:22 2003 From: bdelmee at advalvas.REMOVEME.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Wed, 03 Sep 2003 22:52:22 +0200 Subject: python 2.3, cvs module specific question Message-ID: <3f565440$0$1114$6c56d894@feed0.news.be.easynet.net> Hello, I can't seem to be able to specify the delimiter when building a DictReader() I can do: inf = file('data.csv') rd = csv.reader( inf, delimiter=';' ) for row in rd: # ... But this is rejected: inf = file('data.csv') headers = inf.readline().split(';') rd = csv.DictReader( inf, headers, delimiter=';' ) for row in rd: # ... The DictReader constructor fails with a TypeError: init() got an unexpected keyword argument 'delimiter' Maybe I am missing something here? One rather convoluted workaround is the following: inf = file('data.csv') d = csv.Sniffer().sniff(s) inf.seek(0) headers = inf.readline().split(';') rd = csv.DictReader( inf, headers, dialect=d ) for row in rd: # ... If DialectReader does indeed not accept the optional "fmtparam" then at least the documentation needs fixing. But then again I may just be misreading it.... TIA, Bernard. From spam at magnetic-ink.dk Wed Sep 24 02:27:41 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Wed, 24 Sep 2003 06:27:41 +0000 (UTC) Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> Message-ID: <3f71395d-46f08129-996a-495d-a5ee-05fb1caef6e9@news.szn.dk> Fran?ois Pinard wrote: > In the less usual case you want concurrency between Python and the > forked shell command, for only later checking if the forked process > is done, the usual way is to send a zero signal to the child using > `os.kill()'. The zero signal would not do any damage in case your > forked process is still running. But if the process does not exist, > the parent will get an exception for the `os.kill()', which you may > intercept. So you know if the child is running or finished. This will yield a false positive and potential damage if the OS has spawned another process with the same pid, and running under your uid, as the task you wanted to supervise. // Klaus -- ><> unselfish actions pay back better From sholden at holdenweb.com Thu Sep 11 09:10:42 2003 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 11 Sep 2003 13:10:42 GMT Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> Message-ID: -- -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ "Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote... > On Wed, 10 Sep 2003 15:46:11 +0000 (UTC), JCM > wrote: > > >Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: > > > >... First of all, if you insist on using an invalid address, might I suggest that "x at y.invalid" would be less visually annoying, with the additional merit of actually meaning something. > > > >>>>> def Inc(ref p) : > >> ... p += 1 > >> ... > >>>>> x = 1 > >>>>> Inc(x) > >>>>> x > >> 2 > > > >While I'd not be against some sort of reference-passing mechanism in > >Python, I think this is the wrong way to go--modifiability should be > >evident to the caller. > > 1. I pointed out that this is an advantage of the C# system, which I > was proposing to imitate. > > : The C# solution uses a modifier keyword, but that keyword must be > : specified in both the function definition *and* the call. For > : instance... > > ... So, if I can summarise. You see a feature in C# that represents perhaps one of the less-well-thought-out aspects of the language. You then ask how to graft it into Python because "Python should be more like C#"? > > : The rationale for this in C#, I assume, is mostly about clarity and > : maintainability - the caller can't be surprised when value type > : parameters are changed in a function as he had to explicitly allow it. > I agree the requirement for the "ref" keyword in the call lends some clarity. Not sure I'd agree about maintainability, though. And it can only be a matter of time before people start suggesting that the ref mechanism be used because there's a two-hundred nanosecond time saving ... > > 2. You quoted the example I labelled as "(roughly) what I'd like to > be able to do" and ignored the one where I adopted the C# > approach... > > : >>> def Inc(ref p) : > : ... p += 1 > : ... > : >>> x = 1 > : >>> Inc(ref x) > : >>> x > : 2 > > So your criticism is invalid simply because the whole point of my post > was to suggest a scheme where "modifiability should be evident to the > caller". > But given Python's ability to have a function return a tuple to an unpacking assignment (which has the real advantage that the intention to modify the value of the left-hand tuple elements is explicit) I really can't see why you want to complicate things further. "Explicit is better than implicit". > > Currently, if you see a call to f(x) you know > >that x cannot be rebound. > > And if in some future version of Python the suggestion I made was > implemented, when you see f(x) you will still know that x cannot be > rebound - but when you see f(ref x) you will know that x may well be > rebound. > OK, remind me why this is better than x = Inc(x) or x, y = DoubleInc(x, y) > > I'd be more in favor of something like: > > > > >>> def Inc(ref p): > > ... p += 1 > > ... > > >>> x = 1 > > >>> Inc(x) > > >>> x > > 1 > > >>> Inc(ref x) > > >>> x > > 2 > > I wouldn't want this. To implement it, either a single compiled > version of a function would need to figure out at run time whether the > parameters where by reference or not, or several versions of each > function would have to be compiled into the .pyc file. > > Also, I don't really see the benefit. If a function has by-reference > parameters then rebinding those parameters is likely a big part of the > purpose of the function. Supplying a parameter which cannot be rebound > is likely an error caused by someone forgetting to type the 'ref', in > which case they'd equally likely appreciate an error message as > opposed to wierd, hard-to-trace logic errors. > So you introduce a "ref" keyword so that a dangerous and unneccessary mechanism can be "safely" introduced? still-not-convinced-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From adalke at mindspring.com Sat Sep 27 21:49:40 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Sun, 28 Sep 2003 01:49:40 GMT Subject: [2.2.1]How To Gracefully Shutdown an XML-RPC Server References: Message-ID: The Jetman: > Thanx ! I *swear* I always spend at least a couple hours or so looking > for stuf like this on my own ! The Python Cookbook is an impressive collection of tidbits. > BTW, I haven't tried it, but I bet os._exit will fail just like > sys.exit(). Unlikely. sys.exit actually raises a Python exception, SystemExit. This is caught by the XMLPRC server and converted into a message for the client. (And this a reason you shouldn't use "except:" in your code. Though if you really need it, you should consider except SystemExit: raise except: ... ) os._exit uses the C function '_exit' which does an exit right away, without doing the normal cleanups that exit(3C) does. It doesn't raise an exception and cannot be overriden by other Python code. (Unless os._exit was replaced.) > Besides the reason for a graceful shutdown is more > than cosmetic, since a forced shutdown (like a Ctrl-C) may occasionally > leave the sockets allocated (which *has* happened.) Let me guess, you quit a server program then restarted it only to get a "cannot rebind to port" error message? Ctrl-C raises a KeyboardInterrupt exception and its effect should be the same as SystemExit, except for a couple very minor issues. It isn't the same as using os._exit. What you're seeing is a consequence of the code not properly handling its network resources. Eg, it could register an atexit handler which forces shut all open sockets. See http://www.manualy.sk/sock-faq/unix-socket-faq-2.html#time_wait for a description of what's happening at the TCP level. Even when that happens, it doesn't "leave the socket [permanently] allocated" in the system level. If you wait long enough, the system should release the port. Andrew dalke at dalkescientific.com From syver at inout.no Tue Sep 9 07:23:52 2003 From: syver at inout.no (Syver Enstad) Date: 09 Sep 2003 13:23:52 +0200 Subject: method post References: Message-ID: "franck" writes: > Hi, > > how to do a post with python? import urllib args = {'firstArg': 2, 'secondArg':1} f = urllib.urlopen('http://myhost.com/page.cgi', urllib.urlencode(args)) From jhf at hex.no Tue Sep 2 06:34:41 2003 From: jhf at hex.no (Jørgen Hermanrud Fjeld) Date: Tue, 2 Sep 2003 12:34:41 +0200 Subject: Compiler C or Python? In-Reply-To: <20030826213316.GA7285@unpythonic.net> References: <20030826213316.GA7285@unpythonic.net> Message-ID: <20030902103441.GA10169@hex.no> On Tue, Aug 26, 2003 at 04:33:17PM -0500, Jeff Epler wrote: > 4. It's possible to write code so that __import__ uses compiler.compile > instead of the written-in-C compiler, but I don't have this code handy. > Also, a test suite is needed, and presumably a written-in-C implementation > as well. (option 2: make the compiler.compile interface the standard > compiler, and let the builtin compiler support a Python subset > sufficient to bootstrap the written-in-python compiler, or arrange > to ship .pyc of the compiler package and completely get rid of the > written-in-C compiler) Could you make an effort to locate that code, or give some suggestions to where I might locate it myself? And in general, if should want to alter the Python compiler, should I start with the Python or C version? As far as I can see from your email the Python version is easier to modify, but why two compilers? Isn't that a lot to maintain? Sincerely J?rgen From spam at magnetic-ink.dk Wed Sep 24 18:26:44 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Wed, 24 Sep 2003 22:26:44 +0000 (UTC) Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> <3f71395d-46f08129-996a-495d-a5ee-05fb1caef6e9@news.szn.dk> Message-ID: <3f721a24-4498de32-179a-496b-b6c9-d853b7c0ab3d@news.szn.dk> Fran?ois Pinard wrote: > Do you know anything reasonably simple, safer, and that does the job? I'd always use fork() + wait() so I know I killing the right process if I have to kill something. Killing blindly is gambling. // Klaus -- ><> unselfish actions pay back better From bgailer at alum.rpi.edu Mon Sep 8 08:10:10 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 08 Sep 2003 06:10:10 -0600 Subject: Ternary operator In-Reply-To: References: <3F5B6404.BD1A9709@engcorp.com> Message-ID: <6.0.0.22.0.20030908060441.03bdbda0@66.28.54.253> At 12:42 AM 9/8/2003, Michael Geary wrote: > > Andrew Chalk wrote: > > > Is there a python equivalent of the C ternery operator? > >Peter Hansen wrote: > > See http://www.python.org/cgi-bin/faqw.py?query=4.16&req=search > >As a newcomer to Python, I found it interesting to read the PEP for this: > >http://www.python.org/peps/pep-0308.html > >In retrospect, it seems obvious that the way the voting was conducted >insured that no ternary operator would be added to the language. > >There were 16 proposed syntax options, and the requirement was that a >ternary operator would be added only if an clear majority picked a single >one of those options. > >Well, with 16 options to choose from, it hardly seems surprising that none >achieved a majority-even though several of them drew quite a few votes, and >the most popular proposal did get more votes than the "reject all" option. > >Four of the options got significantly more votes than the others. Those four >options combined got more than three times the number of votes that "reject >all" got. > >It seems to me that the majority did want some kind of ternary operator, but >the large number of options prevented any one from being the clear winner. I >would wager that if the BDFL had picked his favorite from any of the most >popular options and said, "Now vote yes or no on *this* syntax", he would >have seen that clear majority he was looking for. > >I suppose this is all water under the bridge now, since the PEP stated that >this was the community's one and only chance. I just can't help but think >that the voting system guaranteed the outcome--but it's Guido's language and >it was certainly his call to make. THANK YOU. Your analysis of the process brings me a sense of relief. I was also confused and frustrated by its failure to deliver what (obviously) many of us wanted. I was dismayed by the process being defined as "the community's one and only chance" and then set up to fail. With the assumption that a majority of us want a ternary operator, I'd like to see the issue revisited with a goal of choosing an option by elimination. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From bblancett at hotmail.com Fri Sep 19 09:18:17 2003 From: bblancett at hotmail.com (Bill) Date: 19 Sep 2003 06:18:17 -0700 Subject: SMTPlib Emailing Attachments References: <4fd6e92.0309170849.287e86b6@posting.google.com> Message-ID: <4fd6e92.0309190518.3b226735@posting.google.com> Thanks to help of Rudy Shockaert I was able to solve my problem and I also added the capability to add the email body if you are curious and don't know how. I also commented the code as well. Here is the code result: import smtplib import mimetypes from email.Encoders import encode_base64 from email.MIMEAudio import MIMEAudio from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText #______________________________________________________________________________________________________ #Requirements:At least Python 2.2.2 #getAttachment takes the directory path and the filename for ex: 'c:\\MyFolder\\test.txt' #You must put double back slashes in your path. #getAttachment returns email version of the type of file it takes in, #For example if it is a text file, it will encode it as a text file, a gif, it will encode it as a gif #_______________________________________________________________________________________________________ def getAttachment(path, filename): ctype, encoding = mimetypes.guess_type(path) #mimetypes guesses the type of file and stores it in ctype if ctype is None or encoding is not None: # example: ctype can equal "application/pdf" ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) #We do a split on "/" to store "application" in maintype and "pdf" in subtype fp = open(path, 'rb') #open the file if maintype == 'text': attach = MIMEText(fp.read(),_subtype=subtype) #check for maintype value and encode and return according to elif maintype == 'message': #the type of file. attach = email.message_from_file(fp) elif maintype == 'image': attach = MIMEImage(fp.read(),_subtype=subtype) elif maintype == 'audio': attach = MIMEAudio(fp.read(),_subtype=subtype) else: print maintype, subtype #if it does not equal any of the above we print to screen and encode and return attach = MIMEBase(maintype, subtype) #the encoded value attach.set_payload(fp.read()) encode_base64(attach) fp.close attach.add_header('Content-Disposition', 'attachment', filename=filename) return attach #_______________________________________________________________________________________________ #Here we set up our email >From = 'myname at hotmail.com' To = 'yourname at hotmail.com' msg = MIMEMultipart() msg['From'] = From msg['To'] = To msg['Subject'] = 'here is your attachment' body = MIMEText('This is the body of the email!') #Here is the body path = 'C:\\YourPath\\YourFile.txt' filename = 'gfe.pdf' attach = getAttachment(path, filename) #We call our getAttachment() function here msg.attach(attach) #We create our message both attachment and the body msg.attach(body) server = smtplib.SMTP('mySMTPServerName.com') server.sendmail(From, To, msg.as_string()) #Send away server.quit() bblancett at hotmail.com (Bill) wrote in message news:<4fd6e92.0309170849.287e86b6 at posting.google.com>... > I am trying to have the capability to email attachments. Specifically > I want to be able to email a specific attachment that I name that may > be a PDF document, text doc, etc. I already have a working piece of > code that emails jpg attachments but does not work with any other > types of attachments. Could someone tell me how to modify this code to > send other types of attachments like the one's stated above(especially > PDF's)? Also how do I determine the name of the attachment? Right now > it defaults to Attach0. Here is the current code I have below: > _________________________________________________ > import sys, smtplib, MimeWriter, base64, StringIO > > message = StringIO.StringIO() > writer = MimeWriter.MimeWriter(message) > writer.addheader('Subject', 'The Text test') > writer.startmultipartbody('mixed') > > # start off with a text/plain part > part = writer.nextpart() > body = part.startbody('text/plain') > body.write('This is a picture of chess, enjoy :)') > > # now add an image part > part = writer.nextpart() > part.addheader('Content-Transfer-Encoding', 'base64') > body = part.startbody('image/jpeg') > #body = part.startbody('text/plain') > base64.encode(open('c:\email\chess01.jpg', 'rb'), body) > > # finish off > writer.lastpart() > > # send the mail > smtp = smtplib.SMTP('fc.hbu.edu') > smtp.sendmail('bblancett at hbu.edu', 'bblancett at hbu.edu', > message.getvalue()) > smtp.quit() > __________________________________________________________________________ From rogerb at netspeed.com.au Thu Sep 4 07:35:05 2003 From: rogerb at netspeed.com.au (Roger Booth) Date: Thu, 4 Sep 2003 21:35:05 +1000 Subject: Can't Open PY Files Message-ID: <000801c372d8$971abc40$48ab21cb@rogerboo> I've recently downloaded and installed Python23 and am having trouble getting it to function. I've set the Windows 2000 path variable "C:\Python23" but when I type "python" in a dos command line I get a message saying "'PYTHON' is not recognized as an internal or external command, operable program of batch file". It does open when I type in the full path, and via Start\Programs\Python23, but when I enter "import 'filename'" from a file's home directory, I get a message saying: "no module named 'filename'". Any help would be greatly appreciated. RB -------------- next part -------------- An HTML attachment was scrubbed... URL: From FBatista at uniFON.com.ar Thu Sep 18 10:13:09 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 18 Sep 2003 11:13:09 -0300 Subject: Money data type Message-ID: #- Batista, #- #- I know some old systems do allow arbitrary precision #- decimals, but Python #- doesn't have any. What's the problem with floating point, #- that makes it #- unusable for you? As far as I can see, it *IS* only when #- you come to print #- that it matters. With arbitrary precision, you are likely #- to get more #- rounding errors. Can you explain *why* the /storage/ of #- digits is so #- important ? Are you trying to tell me that if I work always with float, and in the final step (reaching the user's eyes or check in the printer) I "represent" it with str (for example) or with "%.5f", I get no rounding errors? If you are, I will believe you! (even "feeling" other way, but can not prove it). . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at alum.rpi.edu Mon Sep 15 10:54:40 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 15 Sep 2003 08:54:40 -0600 Subject: from clipper move to python In-Reply-To: <3812075547.20030915130057@chead.org> References: <3812075547.20030915130057@chead.org> Message-ID: <6.0.0.22.0.20030915085400.041dd200@66.28.54.253> At 12:00 AM 9/15/2003, ads wrote: >Hi Everyone, > >I'm starting learning python about 2 weeks, and still have >difficulties to create GUI based application because I never learn >about classes and other OOP things. Does anyone knows how to >create text console application like clipper using python In the Linux world there's the curses module. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From oren-py-l at hishome.net Thu Sep 11 03:17:09 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 11 Sep 2003 03:17:09 -0400 Subject: Opposite of yield? In-Reply-To: <3F5F7E35.B5DA4669@easystreet.com> References: <3F5F7E35.B5DA4669@easystreet.com> Message-ID: <20030911071709.GA85986@hishome.net> On Wed, Sep 10, 2003 at 12:40:37PM -0700, achrist at easystreet.com wrote: > The yield statement looks to be a big step toward some kind of > lightweight concurrency-oriented programming in python. Is there > any similarly nice way to do the opposite of yield, just sit around > (perhaps in the middle of a loop) and wait until some other routine > (unknown to the waiting module) hurls a value in? Here is a way of converting a generator function into a consumer using a single item list as a mailbox: from __future__ import generators def consumer(): print "This code runs before any data is fed to the consumer" mailbox = []; yield mailbox while mailbox: print "Here's what I got:", mailbox.pop() yield mailbox print "This code runs after end of data is signalled" # How to feed a consumer: i = 0 for mailbox in consumer(): if i < 5: mailbox.append(i) # feed next item i += 1 Output: This code runs before any data is fed to the consumer Here's what I got: 0 Here's what I got: 1 Here's what I got: 2 Here's what I got: 3 Here's what I got: 4 This code runs after end of data is signalled For a more comprehensive solution try Christian Tismer's Stackless Python. Oren From PeterAbel at gmx.net Fri Sep 26 11:45:42 2003 From: PeterAbel at gmx.net (Peter Abel) Date: 26 Sep 2003 08:45:42 -0700 Subject: eval's local arguement ignored? References: <56e1eff0.0309230923.1215833f@posting.google.com> Message-ID: <21064255.0309260745.6d3d5650@posting.google.com> jseb at cs.mcgill.ca (Jean-S?bastien Bolduc) wrote in message news:<56e1eff0.0309230923.1215833f at posting.google.com>... > Hello, > > I would like to associate a local namespace with a lambda function. To > be more specific, here is exactly what I would want: > > def foo(): > a = 1 > f = lambda x : a*x > return f > > then if "f1 = foo()", I get a function whose parameter "a" is not in > the global scope. But my functions are not to be hard-coded. I naively > expected the following to work: > > def foo(funcstring): > a = 1 > f = eval(funcstring) > return f > > but "f2 = foo( 'lambda x : a*x' )" won't work: "f2()" will look for > "a" in the globals. > > Looking at the documentation (I did!), I was then certain replacing > the evaluation with the following would work: > > f = eval(funcstring, globals(), locals()) > > Or, while we're at it, evaluating the whole thing outside of function > "foo": > > f = eval('lambda x : a*x', globals(), {'a' : 1}) > > Ooops! the new function still looks for "a" in the globals... Although > I could not find any documentation about the fact, it seems the > "local" argument to "eval" has no effect in the above cases! > > So for now, I'm doing something like > > f = eval('lambda x : a*x', {'a' : 1}) > > but then my function looses access to the globals. > > I know that only the very first case above gives me a function whose > "fun_closure" attribute is not "None". But still I cannot see where I > go wrong. > > Thank you, > > JSeb **kwa** is the solution! In your factory-function *foo* you have to declare *a* keywordarguement which is initialized with a. >>> def foo(): ... a=1 ... f=lambda x,a=a:a*x ... return f >>> f1=foo() >>> f1(3) 3 A global *a* doesn't affect your function. >>> a=1000 >>> f1(3) 3 but you even can get influence to *a*: >>> f1(3,a=100) 300 >>> or >>> f1(3,100) 300 >>> And this works too, even if you generate a lambda-function as adhoc-function in the global scope: !! You have to define *a* as first !! >>> a=100 >>> f2=lambda x,a=a:a*x >>> f2(3) 300 To change the global *a* doesn't affect your lambda-function! >>> a=0 >>> f2(3) 300 But you can give your function the additional information. >>> f2(3,a=1) 3 or more traditional >>> f2(3,1) 3 And the default kwa will stay resident. >>> f2(3) 300 >>> Regards Peter From mark at hahnca.com Thu Sep 11 22:23:30 2003 From: mark at hahnca.com (Mark Hahn) Date: Thu, 11 Sep 2003 19:23:30 -0700 Subject: ascii codec missing under py2exe Message-ID: I'm using the MIMEText module as part of sending email with no problem until I put it through py2exe. Then I get this error: LookupError: unknown encoding: ascii ... on this line ... File "email\Encoders.pyc", line 85, in encode_7or8bit ... which looks like this ... orig.encode('ascii') My guess is the ascii codec is not getting included in my build. Can someone tell me how to fix this? I know nothing about how these text codecs work. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Sep 29 13:35:03 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Mon, 29 Sep 2003 18:35:03 +0100 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <1Xhdb.130593$hE5.4445587@news1.tin.it> <9tabnvgbc4etnpp1hm3oh5dkffkru9pv0d@4ax.com> <2tsbnvob1k6tt6bkb29cfc69a4ji0q4giv@4ax.com> <136envcoppkt546p8rhjhpeqkj380a3g40@4ax.com> Message-ID: On Mon, 29 Sep 2003 08:15:41 -0400, David Abrahams wrote: >That's why I didn't understand why you were giving me such a hard >time. Because it's informal speech I'm supposed to do quadruple duty >to make sure you haven't misinterpreted me? I really was going out >of my way to explain this stuff to you politely. Nope - occasional misreadings are a fact of life and shouldn't be a big deal. But when you said "I never, anywhere, said "std::pair supports..."" that seemed very pedantic to me, as the issue wasn't your precise words but the meaning behind them. And when you said "Hey, it's not my fault you read what you want to see into what I posted." you seemed to be claiming that there was no room for reasonable misinterpretation in your original words and that I was 100% to blame for the misinterpretation. The whole point of my pedanticism was to point out that your original statement was informal and subjective and that, while that was certainly wholy appropriate, there was room for accidental misinterpretation. IIRC I was not even the first to misinterpret - I simply replied to Alex Martelli who had already misinterpreted your words the same way that I did. So being made a scapegoat seemed unfair. And now I seem to be whining about it far to much, but really I just want this point to be understood - and I wish I had been clear about it in my last post. >Then so is > > struct { int x, y; }; > >Also, so is char[4], and unsigned long is a container of at least 32 >bits. Not in the pedantic 'C++ standard definition' sense of course, but the C++ standard has taken an existing word and tied a more restrictive meaning to it. In the wider world the original unrestricted meaning is still valid. To me both structs and char arrays are containers in the less-restrictive sense. After all, if a C programmer talks about containers what is he referring to? And in C# even a fixed-size array is implemented using a library class. An unsigned long, no - that is a single atomic item. But then again, IIRC, in the pre-C++ days when I first learned programming, 'container for a value' was one common way of explaining the concept of a variable ;-) >Thanks, I think. This is somewhat of a backhanded apology, but I'll >take it. [If you had just stopped with the last message, I wouldn't >even feel it mattered]. I felt it mattered because I felt that I was being held soley and entirely responsible for a mistake that I felt wasn't unreasonable. I appologise for the misinterpretation because I did misinterpret, and I particularly appologise for the overblowing because it arises out of my oversensitivity to certain things you said - which I certainly have no right to given the sarcastic tone of my earlier post, and in any case I have no doubt your words resulted from frustration. I do not, however, accept that I am enirely and soley to responsible for the misinterpretation. My persistence in sticking to this may seem bizarre and petty, but there are reasons for my being bizarre and petty over such things. Lets just call it 'desperate defending of what little self esteem I have left' - and yes, it does tend to be counterproductive :-( >http://www.python.org/doc/current/lib/typeiter.html#l2h-149 > >Read it twice, carefully. OK - you are right and I am feeling a right fool. Sorry. >I'm afraid not. I never, ever make mistakes in the first place ;-> > >infallib-ly y'rs :-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From sheila at spamcop.net Tue Sep 2 14:49:15 2003 From: sheila at spamcop.net (Sheila King) Date: Tue, 02 Sep 2003 18:49:15 GMT Subject: MySQLdb -- any way to get "rows matched"? References: Message-ID: On Tue, 2 Sep 2003 11:00:58 -0500, Skip Montanaro wrote in comp.lang.python in article : > > Chris> When issuing updates in mysql (in the console window), mysql will > Chris> tell you if any rows matched and how many rows were updated (see > Chris> below). I know how to get number of rows udpated using MySQLdb, > Chris> but is there any way to get the number of rows matched? > > I believe the return value of the cursor's execute() method gives you the > number of rows which matched. > > Skip That's not what this says? http://groups.google.com/groups?selm=mailman.1062375303.22663.python-list%40python.org Just for confirmation, a little experimentation: MYSQL at the command line: mysql> SELECT * from example; +--------+------+---------+ | name | AGE | COUNTRY | +--------+------+---------+ | sheila | 30 | US | | arthur | 23 | NL | | bob | 30 | US | +--------+------+---------+ 3 rows in set (0.00 sec) mysql> UPDATE example SET AGE=30 WHERE AGE=30; Query OK, 0 rows affected (0.00 sec) ws matched: 2 Changed: 0 Warnings: 0 MySQLdb in Python: >>> c = conn.cursor() >>> c.execute("""UPDATE example SET AGE=30 WHERE AGE=30;""") 0L >>> c.messages [] >>> c.info() '' Being a MySQL and MySQLdb newbie, I'm not sure if there is any way to find out how many matched, via Python's MySQLdb module. I thought, from the source code, that .messages or .info() for the cursor attributes/methods might do it, but apparently not??? I'm using MySQL 3.23.57 and MySQLdb 0.92 -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From peter at engcorp.com Wed Sep 3 15:24:14 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 03 Sep 2003 15:24:14 -0400 Subject: Location of bytecode files (pyc) References: <6f03c4a5.0309021745.3a79d951@posting.google.com> <3f55de7b@shknews01> <6f03c4a5.0309031028.3df1711c@posting.google.com> Message-ID: <3F563FDE.FCA8B2C3@engcorp.com> Rim wrote: > > > If you're on Windows say: > > > > del /S *.pyc > > > > to remove all .pyc's from cwd and below. > > Yes, and in linux 'find . -name "*.pyc" -exec rm -rf {} \;', but that > is not the point. I did not ask about how to remove pyc files, I asked > about placing them far from source code, in another directory, so they > would not be seen by the backup software. > > The backup software runs continuously day, night, weekends, all the > time. Sweeping the pyc's under the carpet each time the backup is > about to be saving my files is impossible. That is why we store all > gcc object files and executables we produce on non-backed up > filesystems by prefixing target filenames in makefiles with a variable > like $OBJECT_DIR and $EXEC_DIR. You have a fancy backup system like this, involving hundreds of Gigs, and it can't apply a simple filter to avoid .pyc and .obj files?! -Peter From maney at pobox.com Thu Sep 18 00:48:21 2003 From: maney at pobox.com (Martin Maney) Date: Thu, 18 Sep 2003 04:48:21 +0000 (UTC) Subject: Advice from Jeff (Was Re: Is there "let binding" in Python?) References: <20030914214340.13608.qmail@web40904.mail.yahoo.com> Message-ID: Don Bruder wrote: > Definitely declaring variables. I'm nowhere near far enough along to > mess with templates yet. They just confuse me. Templates seem to me (now - I still remember a time when they appeared almost magical) a workaround for premature typing in C++. Reminds me of Strachey's comments on IBM's Stretch computer: "Like some early computer programs it is immensely ingenious, immensely complicated, and extremely effective, but somehow at the same time crude, wasteful, and inelegant, and one feels that there must be a better way of doing things." Python, in comparison, seems to me to be an intelligent way of employing the modern CPU. :-) -- automation: replacing what works with something that almost works, but which is faster and cheaper. - attributed to Roger Needham From stephan.diehl at gmx.net Tue Sep 9 07:54:00 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Tue, 09 Sep 2003 13:54:00 +0200 Subject: Slight metaclass confusion References: Message-ID: ben at transversal.com wrote: > I am slightly confused about the way metaclasses work, having read > "Metaclass Programming In Python, Parts 1 and 2" > > I get the fact that the instance of a metaclass is a class, but in > this case I fail to see why the following does'nt work: > >>>> class Meta(type): > ... def __str__(cls): > ... print "I am " + repr(cls) > ... >>>> >>>> Class = Meta("Fish", (), {}) >>>> Class.__str__() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: descriptor '__str__' of 'object' object needs an argument > > Whereas this does: > >>>> class Simple(object): > ... def __str__(self): > ... return "I am " + repr(self) > ... >>>> obj = Simple() >>>> obj.__str__() > I am <__main__.Simple object at 0x402f676c> > > The tutorial does mention this (slightly), but doesn't make it clear > why this is happening. I am probably missing something obvious though! The problem is perhaps the terminology (Unfortunatelly,I don't know a better one). The metaclass initializes a class. Just imagine, that the textual class definition comes fresh from the parser, so you have information about possible base classes, methods, attributes. These information can be changed within the metaclass __new__ method. Think of the metaclass as a factory that turns a class definition into a class instance. Other than that, they don't interact. What a metaclass can do, is to change that information, before the class is made into a class object. Basicly, the metaclass concept is orthogonal to the inheritence concept of OOP. > > Thanks for the help, > > Ben > --- Hope that helps Stephan From khliu at ev078.ev.nctu.edu.tw Sun Sep 21 08:32:58 2003 From: khliu at ev078.ev.nctu.edu.tw (Tinmean K.H.Liu) Date: Sun, 21 Sep 2003 20:32:58 +0800 Subject: problem about wxPython error Message-ID: <012801c3803c$7d8001c0$b2df718c@evpc178> Hi! I install wxPython under WinXP when I want to use some simple sample, there is an error message: File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Tinmean\temp_desktop\python_0921\wx1.py", line 3, in ? from frame import Frame ImportError: No module named frame >From wiki's FAQ, I add new paths in PYTHONPATH for wxPython and wx, but it is no use. any one could help me? thanks! --Tinmean Liu in Taiwan -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacek.generowicz at cern.ch Wed Sep 17 04:43:13 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Sep 2003 10:43:13 +0200 Subject: negative indices for sequence types References: Message-ID: danbmil99 at yahoo.com (dan) hypothesizes: > My explanation of the behavior is correct however. list[a] always > equals list[a % len(list)]. A negative number mod N = its absolute > value subtracted from N: Proof by counterexample: Python 2.2.2 (#1, Feb 8 2003, 12:11:31) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = '0123' >>> s[-20 % len(s)] '0' >>> s[-20] Traceback (most recent call last): File "", line 1, in ? IndexError: string index out of range Your explanation of the behaviour is incorrect. QED. From rolfedh at hotmail.com Mon Sep 29 19:06:16 2003 From: rolfedh at hotmail.com (Rolfe) Date: 29 Sep 2003 16:06:16 -0700 Subject: Running mod_python on Apache on Windows2000 * Message-ID: Hi, I struggled, and got mod_python running on Apache/Win2k. Follow these instructions verbatim and you shouldn't have any trouble. These instructions are based on "http://www.modpython.org/live/current/doc-html/inst-testing.html". I've added specific information such as Windows filepaths and filenames so there's no ambiguity on what you should do. I encourage you to copy and paste to avoid typing errors. Cheers, Rolfe INSTALLING MOD_PYTHON 1. Make a default installations of the latest/best version of Apache. 2. Make a default installation of the latest/best version of mod_python. 3. Open C:\Program Files\Apache Group\Apache2\conf\httpd.conf in Notepad. 4. In httpd.conf, just below the line "#LoadModule ssl_module modules/mod_ssl.so", copy and paste the following section: #Start of section pasted in by YOURNAMEGOESHERE LoadModule python_module modules/mod_python.so AddHandler python-program .py PythonHandler mptest PythonDebug On AddHandler python-program .py PythonHandler mptest PythonDebug On #End of section pasted in by YOURNAMEGOESHERE (NOTE: Don't mess around with the other configuration settings in httpd.conf, - leave good enough alone. Don't worry about the forward/backward slashes either - it doesn't matter.) 5. Save and close httpd.conf and wait a few seconds. 6. Restart Apache by clicking the Apache monitor icon in your systray and selecting Apache2=>Restart. PROCEDURE COMPLETED ##### TESTING MOD_PYTHON ####### 1. Create a directory called "test" in htdocs so you end up with "C:\Program Files\Apache Group\Apache2\htdocs\test" 2. Create a text file called mptest.py in "C:\Program Files\Apache Group\Apache2\htdocs\test" 3. Paste the following text into mptest.py: from mod_python import apache def handler(req): req.write("Hello World!") return apache.OK 4. Save and close mptest.py. 5. In your file browser, copy and paste mptest from "C:\Program Files\Apache Group\Apache2\htdocs\test" to "C:\Program Files\Apache Group\Apache2\cgi-bin". 6. Assuming your sitting at the same machine that's running Apache, enter the URL "http://localhost/test/mptest.py" in your web browser. The browser displays "Hello World!" and nothing else. This confirms that Apache can run cgi scripts in the /test/ directory. 7. Repeat step 6 using the URL "http://localhost/cgi-bin/mptest.py" instead. The browser displays "Hello World!" and nothing else. This confirms that Apache can run cgi scripts in the /cgi-bin/ directory. PROCEDURE COMPLETED - mod_python works! ######## NOTES ######### Remove either of the following sections (from ) in order to disable cgi scripts in a particular directory. I understand it is very poor security to run cgi scripts under htdocs, so I'd try getting rid of that one first. AddHandler python-program .py PythonHandler mptest PythonDebug On AddHandler python-program .py PythonHandler mptest PythonDebug On ######### ACKNOWLEDGEMENTS ########## Thank you, Steve Holden, for your guidance. I'm very much looking forward to your book, Python Web Programming. Thank you Peter Maas for your response on comp.lang.python From maxm at mxm.dk Mon Sep 15 07:20:43 2003 From: maxm at mxm.dk (Max M) Date: Mon, 15 Sep 2003 13:20:43 +0200 Subject: pyc2py In-Reply-To: References: Message-ID: <3f65a08e$0$97250$edfadb0f@dread12.news.tele.dk> News M Claveau /Hamster-P wrote: > Pirate ? Or perhaps: - project delivered to customer. - Fatal harddisk crash - Faulty backup. - Customer requesting changes to project. Or perhaps while preparing to distribute a project, a slip of the fingers make: rm -r *.py instead of rm -r *.pyc I don't think that those are unusual scenarios? regards Max M From forodejazz at yahoo.es Wed Sep 17 04:34:05 2003 From: forodejazz at yahoo.es (=?ISO-8859-1?Q?David_Asorey_=C1lvarez?=) Date: 17 Sep 2003 01:34:05 -0700 Subject: audio module References: <9bP9b.71118$Mb2.2369961@twister.tampabay.rr.com> Message-ID: <1759581e.0309170034.6399d799@posting.google.com> Todd Stephens wrote: > Is there such a module containing audio tools? I am looking specifically > for tools to manipulate ogg-vorbis and convert other formats (mp3, wav) to > ogg. You can try Snack --it doesn't support ogg :-( http://www.speech.kth.se/snack/ -- David. From rhunter007 at yahoo.com Mon Sep 15 12:52:25 2003 From: rhunter007 at yahoo.com (Rob Hunter) Date: Mon, 15 Sep 2003 09:52:25 -0700 (PDT) Subject: Is there "let binding" in Python? In-Reply-To: <978900BC-E795-11D7-973E-003065F081D2@unpythonic.net> Message-ID: <20030915165225.7796.qmail@web40905.mail.yahoo.com> Thanks for the reply. Some comments below: > Tutorial > 9.2 Python Scopes and Name Spaces > http://www.python.org/doc/tut/node11.html#SECTION0011200000000000000000 I actually find this reference, at least the section on Python Scopes and Namespaces, quite complicated, and pretty much unreadable. But I think I understand what's going on despite it. >... but you can't write > > def outer(): > x = 3 > def f(arg): return arg * x > x = 4 > return f(5) > > to have outer() return 15, because 'f' will > take the value of x from the > enclosing scope, and that value is 4 at the > time of the call. > I think it's actually that this will return 20 because the x = 4 "mutates" (rather than introducing a new binding) the value of x from 3 to 4. Thus, with mutation, we are able to pierce the function. (Reason #1 in this email why mutation is often a bad thing.) What you can do, though, is this: which shows that Python has (correct) static scoping: def create(): x = 3 def f(arg): return arg*x return f def use(): x = 2 someF = test() x = 4 return someF(1) Now use() returns 3, not 4 or 5. And the reason, I think, is that the x in use() is different from the x in create(). > If you want to have f capture the value of x at > that moment, you must > manually introduce another layer of nesting: > > def outer(): > x = 3 > def inner(x): > def f(arg): return arg*x > return f > f = inner(x) > x = 4 > return f(5) well no, you can just do what I did above. But yes, if you want to use the same name x in the same function it seems that, in Python, you are out of luck. But I can deal with that. > > or you can try to structure your code so that > you can avoid re-using the > name 'x'. One common example of a situation > where you can't avoid it > is something like this: > > from Tkinter import * > > def button_func(i): > print "pressed button", i > > def make_stupid_gui(): > t = Tk() > for i in range(10): > b = Button(t, text="Button #%d" % > i, > command=lambda: > button_func(i)) > b.pack() > make_stupid_gui() > > I got mutation red-handed here! The *only* reason there is a problem here is because of mutation (Reason #2). The FOR statement is mutating the variable i. Avoid mutation, and you avoid this problem. This, by the way, really illustrates the insidiousness of mutation. IMO, you can look at the code above and think it's perfectly correct...after all, you do a loop on i, creating one button for each of the 10 i's. What could go wrong? In scheme, you could write something like this: (let loop ((i 1)) (if (> i 10) empty (cons (make-button i) (loop (+ 1 i))))) This program returns a list of 10 buttons (assuming "make-button" creates numbered buttons) from 1 to 10. IMO, this looks a lot like your button code, except there's no mutation and thus no problem of making every button be button 10. Here's another Scheme program: (map make-button (enumerate 1 10)) This is the way I would write the program in Scheme *or* in Python. It's beautiful, and it does exactly what you'd think it would. > > Not an answer, but advice: when writing > programs in Python, write Python > programs. If it's your task to translate some > Scheme (or any other > language) into Python as literally as possible, > my heart goes out to > you. I'm simply trying to learn to write in Python in a way that I will find tolerable. I really like a lot of it, so far, and I find it fun to write it, and very pretty and easy to read. In general, in most cases, I find it *unacceptable* to use mutation. And, since Python is very much a Scheme-like language, and has functional components (like map, and uh...functions :) with proper scoping) I think that this is quite a reasonable thing to want. The trick is knowing when mutation happens, so that the programmer is aware when s/he is entering a scary land where things may not be what they seem. And it seems from your references and my tests that the "=" operator is mutative. In Scheme there's no issue..you introduce a binding with LET and you mutate a binding with SET!. In Python, the way I see it, you introduce a binding with "=" and you mutate a binding with "=". There seems to be some "functional" module (which isn't installed on my system for some reason) which I should look in to. From what I can tell, it prevents you from mutating...it only allows you to introduce bindings. Rob __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From skip at pobox.com Thu Sep 18 13:07:11 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 18 Sep 2003 12:07:11 -0500 Subject: Forcing getopt to process a specific option first?? In-Reply-To: References: Message-ID: <16233.58943.287151.189586@montanaro.dyndns.org> Dan> Is there any way to force getopt to process one option first?? I'd Dan> like to be able to pass in the name of a configuration file for my Dan> application, then have the remaining command-line parameters Dan> over-ride the configuration file if they are present. Not that I'm aware of. If the order of the remaining options doesn't matter, you might try splitting the argument list before the option which introduces your config file. For example, given this set of command line args: -f bar -o baz -c configfile -o bump -h locate the '-c' and use it to split the argument list, then swap the two pieces: >>> s = "-f bar -o baz -c configfile -o bump -h" >>> args = s.split() >>> args ['-f', 'bar', '-o', 'baz', '-c', 'configfile', '-o', 'bump', '-h'] >>> index = args.index('-c') >>> index 4 >>> args[:index], args[index:] (['-f', 'bar', '-o', 'baz'], ['-c', 'configfile', '-o', 'bump', '-h']) >>> args = args[index:] + args[:index] >>> args ['-c', 'configfile', '-o', 'bump', '-h', '-f', 'bar', '-o', 'baz'] Now pass that list to getopt.getopt(). If the order of the remaining arguments does matter, you just split the argument list into three pieces, the part before rearranging: >>> args[:index], args[index:index+2], args[index+2:] (['-f', 'bar', '-o', 'baz'], ['-c', 'configfile'], ['-o', 'bump', '-h']) >>> args = args[index:index+2] + args[:index] + args[index+2:] >>> args ['-c', 'configfile', '-f', 'bar', '-o', 'baz', '-o', 'bump', '-h'] Skip From newsgroups at jhrothjr.com Mon Sep 8 07:28:17 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 8 Sep 2003 07:28:17 -0400 Subject: Ternary operator (Re: Ternery operator) References: <3F5B6404.BD1A9709@engcorp.com> Message-ID: "Michael Geary" wrote in message news:vlo9699d77sj3e at corp.supernews.com... > > Andrew Chalk wrote: > > > Is there a python equivalent of the C ternery operator? > > Peter Hansen wrote: > > See http://www.python.org/cgi-bin/faqw.py?query=4.16&req=search > > As a newcomer to Python, I found it interesting to read the PEP for this: > > http://www.python.org/peps/pep-0308.html > > In retrospect, it seems obvious that the way the voting was conducted > insured that no ternary operator would be added to the language. I absolutely concur. In fact, I thought that as soon as the voting style was proposed. > There were 16 proposed syntax options, and the requirement was that a > ternary operator would be added only if an clear majority picked a single > one of those options. I don't believe that was the case originally. I think the idea of enumerating suggestions and having a vote came later. > Well, with 16 options to choose from, it hardly seems surprising that none > achieved a majority-even though several of them drew quite a few votes, and > the most popular proposal did get more votes than the "reject all" option. Yup. > Four of the options got significantly more votes than the others. Those four > options combined got more than three times the number of votes that "reject > all" got. In other words, there was a super-majority to get something in. > It seems to me that the majority did want some kind of ternary operator, but > the large number of options prevented any one from being the clear winner. I > would wager that if the BDFL had picked his favorite from any of the most > popular options and said, "Now vote yes or no on *this* syntax", he would > have seen that clear majority he was looking for. I agree. In fact, unless the syntax was truely awful, I'd have voted for it, whatever it was. I don't regard myself as a language designer. > I suppose this is all water under the bridge now, since the PEP stated that > this was the community's one and only chance. I just can't help but think > that the voting system guaranteed the outcome--but it's Guido's language and > it was certainly his call to make. I wouldn't cast the blame on Guido. It's quite clear that he doesn't like the notion, but I don't get the impression that he's got the kind of devious mind that would think this was the way to resolve it. On the contrary, he seems to be a quite straightforward fellow in most ways. The whole notion of "one and only chance" is astonishingly naive. There is no way that the vote on PEP 308 is going to keep people from bring up the idea, and having the opponents refer to it as the "community decision" when the vote was clearly in favor of having the feature added to the language will simply drive people away from the process. > -Mike (who just got my California voter's pamphlet with 135 candidates for > governor!) Interesting thought there... John Roth > > From achalk at XXXmagnacartasoftware.com Tue Sep 23 17:20:18 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Tue, 23 Sep 2003 21:20:18 GMT Subject: Executing a python script from an HTML link? References: <1co0nvk1h60qagov4v60874grijiscvluq@4ax.com> Message-ID: Thanks! "Rene Pijlman" wrote in message news:1co0nvk1h60qagov4v60874grijiscvluq at 4ax.com... > Andrew Chalk: > >Is this possible? In my CGI app. I display a web page with a link (anchor). > >When the link is clicked I want to exectute a python script rather than go > >to an HTML page. > > IIUYC: make the link tot a Python CGI script instead of to an HTML page. > > -- > Ren? Pijlman From mymail.5.tth at spamgourmet.com Mon Sep 22 11:27:27 2003 From: mymail.5.tth at spamgourmet.com (T.T.H.) Date: 22 Sep 2003 08:27:27 -0700 Subject: questions about a C++ COM object accessed in Python via win32com Message-ID: Hi I am coding a C++ COM object which I want to access in Python. For that I do have some detail questions and need help since I am not that familiar with the documentation itself of Python and win32com yet. 1. How do I know that... import win32com.client ...was successful or not? 2. In my COM object I do have the following C++ function: STDMETHODIMP CMyTestObjekt::Connect() { if (m_boolReadyToConnect == false) { return E_FAIL; } return S_OK; } How do I know in Python whether I got back a S_OK or an E_FAIL? Or is this whole concept wrong and I should better make an additional return value like: MyFunktion(......., [out, retval] BOOL *pVal); (declaration in the IDL) 3. If I execute the following command... MyObject = win32com.client.Dispatch("MyCOM.MySuperCOMObject") ...what is the return value from which I know whether it was successful? Or what can be the ""content"" of "MyObject" afterwards? 4. If I have a function in Python in which I call the (global) COM Object, what "if" do I have to use to know whether the COM object already had been allocated? I tried the following but that didn't work: def foo(): if MyObject == None: print "COM not there yet" else: print MyObject.Message I'd really appreciate any help. Or even a hint where to look in the "original" documentation. FYI: I do use Win2000 and ActiveState ActivePython 2.2 which already includes win32com. Bye, Matthias "T.T.H." Grobe From gh at ghaering.de Tue Sep 30 09:48:52 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 30 Sep 2003 15:48:52 +0200 Subject: Best Bug Tracker on Zope platform ? In-Reply-To: <62f2814b.0309300355.6091dd84@posting.google.com> References: <62f2814b.0309300355.6091dd84@posting.google.com> Message-ID: <3F7989C4.4080505@ghaering.de> Jerrykhan wrote: > Hello, > who know the best Bug tracker system on a Python/Zope server ? [...] Not ZOPE-based but written in Python: Roundup. -- Gerhard From lupan at zamek.gda.pl Sat Sep 20 06:18:15 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Sat, 20 Sep 2003 12:18:15 +0200 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <95b4b9ac.0309171233.21f4c07@posting.google.com> <87llsma4fb.fsf@psi.lupan.zamek.gda.pl> <95b4b9ac.0309181021.14b45d65@posting.google.com> Message-ID: <87ad8zsqzc.fsf@psi.lupan.zamek.gda.pl> hildegarde_roth at yahoo.de (Hilde Roth) writes: > No because in many cases the reason why you want to use the syntax > l[seq] is that you already have seq, so you would refer to it by name > and "l[s]" is definitely not hard to parse. So you want l[seq] to be a shorter way for current [l[i] for i in seq] Which is pythonic as it is explicit, easier to read if the code is not written by you yesterday, although in some situations your interpretation of l[seq] might be guessable from the context. > Not at all. I was suggesting to use a semi-colon not a colon. Thus if > l is (10,20,30,40), l[:3] -> (10,20,30) whereas l[(0,3)] -> (10, 30), > i.e., same as in your class-based example, minus the parentheses, which > I now realize are superfluous (odd that python allows you to omit the > parentheses but not the commas). Sorry for my misunderstanding, yes it would be nice to have a posibility to index a sequence with a list of indices, here is a pure Python (>= 2.2) implementation of the idea: class List(list): def __getitem__(self, index): if isinstance(index, (tuple, list)): return [list.__getitem__(self, i) for i in index] else: return list.__getitem__(self, index) >>> l = List(range(0, 100, 10)) >>> l[0,2,3] [0, 20, 30] but in this simple using both commas and slices will not work as expected >>> l[0,1,7:] [0, 10, [70, 80, 90]] > >> 2. Slicing two dimensional object will not be possible as the notion >> you proposed is used just for that (ex. l[1,2] which is equivalent >> to l[(1,2)] see below), and Numeric and numarray use it. > > Same misunderstanding as above, I believe. Let, e.g., l be > ((1,10,100),(2,20,200),(3,30,300),(4,40,400)). Then l[2:; 1:] -> > [(30, 300), (40, 400)]. This is equivalent to [i[1:] for i in l[2:]] > but, at least to me, it is the index notation that is easier to parse. > > Incidentally, it strikes me that there are a lot of superfluous > commas. Why not just (1 10 100) or even 1 10 100 instead of (1,10,100)? > The commas do make the expression harder to parse visually. > This will will work until there are no expressions in the sequence. If there are it is harder to read (and may be more error prone) (1 + 3 4 + 2) >> >>> # multi dimensional indexing >> >>> c[1,3] > > I disagree that this is "multidimensional". You are passing a list > and getting back a list, so this is still flat. I think you are > confusing dimensionality and cardinality. > That is the notion of multidimensional indexing in Python. >> Numeric and numarray use it > > This is good if it is true (I have yet to look at these two because > my work is not primarily numerical) but, again, the restriction of this > syntax to arrays, and arrays of numeric values at that, strikes me > as completely arbitrary. Here is an example of two dimentional Numeric array and it's indexing: >>> from Numeric import * >>> reshape(arange(9), (3,3)) array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> a = reshape(arange(9), (3,3)) >>> a[1][0] 3 >>> a[1,0] 3 >>> a[(1,0)] 3 So currently indexing with sequence has a settled meaning of multidimensional indexing if lists and tuples would allow indexing by sequence, than either: 1. it might be confused with multidimensional indexing of numeric types (the same notion for two different things) 2. it will require rework of multidimensional indexing maybe with your semicolon notion, but will introduce incompatibilities (back and forward) > > The bottom line is that python claims to be simple but has a syntax > which, in this little corner at least, is neither simple nor regular: > xranges and slices are both sequence abstractions but are used in > different contexts and have different syntaxes; C-style arrays are > treated differently than lists of lists of ..., although they are > conceptually equivalent; numeric structures are treated differently > than non-numeric ones etc etc > With multidimensional arrays and list of lists you may both write a[i][j], so it is consistent, with arrays you may write a[i,j] if you know that you have an 2-dim array in your hand. -- =*= Lukasz Pankowski =*= From dave at boost-consulting.com Sun Sep 28 19:35:41 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sun, 28 Sep 2003 19:35:41 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> <0acdb.128801$hE5.4391247@news1.tin.it> <1Xhdb.130593$hE5.4445587@news1.tin.it> <9tabnvgbc4etnpp1hm3oh5dkffkru9pv0d@4ax.com> <2tsbnvob1k6tt6bkb29cfc69a4ji0q4giv@4ax.com> <136envcoppkt546p8rhjhpeqkj380a3g40@4ax.com> Message-ID: Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: > On Sun, 28 Sep 2003 11:22:11 -0400, David Abrahams > wrote: > >>Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: >> >>>>Sorry, what specialization? >>> >>> Presumably template specialisation - such that the special case of >>> std::pair picks up the iterating functionality that >>> std::pair lacks (begin, end etc). That is what I thought you were >>> saying. >>> >>> Or am I still getting this wrong? >> >>Yeah, slightly. You don't need a begin() member function in order to >>make an iterator. The interface might look like: >> >> std::for_each(pair_iterator(my_pair), pair_iterator(), f); >> >>Decoupling is the way to go, man! :^) > > Ah - I get it! - std::pair doesn't exactly support iteration itself, > but a support class can be used to add that capability. > > You can do this in any language. Yes; I never implied otherwise. > For instance, did you know that Python classes supports iterating > through the subset of their attribute that have names beginning with > "a", interleaved with insults? I never, anywhere, said "std::pair supports..." > Yes, all you need is to use this > generator... > > def A_Attrib_Gen (p_Instance) : > for i in dir (p_Instance) : > if i[0] = "a" : > yield i > yield "stupid stupid stupid" > > Well, OK, maybe this is a little unfair - this generator isn't exactly > in the library, but with a little luck you see my point. Your sarcasm is briefly amusing, but unwarranted. > When you say "you can in fact iterate on std::pair with the usual > C++ iterator protocol" it implies to me that std::pair provides > the iterator protocol itself Hey, it's not my fault you read what you want to see into what I posted. > - not that some other class provides a > way to support iteration over the pair. After all, there is *always* > some way to support iteration of *anything*. > > But maybe I'm just being overliteral. No, you just don't know what "the usual iterator protocol" means. It has to do with the protocol for using iterators, and begin()/end() are nowhere in the iterator requirements. They're part of the container requirements. There are many iterators that have nothing to do with containers and have never been passed through a begin()/end(). Pointers to built-in arrays are one obvious example. This whole discussion started out talking about what the Python protocol for manipulating iterators should be. The fact that iterators must themselves have an __iter__ method in Python may just be making this more confusing than it needs to be. -- Dave Abrahams Boost Consulting www.boost-consulting.com From gh at ghaering.de Tue Sep 9 05:51:33 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 09 Sep 2003 11:51:33 +0200 Subject: GUI In-Reply-To: <3f5d9fad$0$31720$91cee783@newsreader01.highway.telekom.at> References: <3f5d9fad$0$31720$91cee783@newsreader01.highway.telekom.at> Message-ID: <3F5DA2A5.4090006@ghaering.de> daniel wrote: > [...] I've found a tiny script in the net with > throws an error, that the modules 'GUI' is > not known - in this line > 'import GUI, struct' struct is a standard module, while GUI is not. I am not even aware of a third-party module that's called 'GUI'. > In the net I haven't found a GUI module - > where I can get it? Your script was probably part of a larger application that has a GUI module or package. So your best bet is to search wherever you found the original script, and if that doesn't succeed, try to contact the author of the script. -- Gerhard From python at sarcastic-horse.com Fri Sep 19 14:25:23 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Fri, 19 Sep 2003 14:25:23 -0400 (EDT) Subject: How do I learn operator overriding? Message-ID: <53332.199.169.240.132.1063995923.squirrel@svr1.turboweb.net> Hi- I need to make a class for quartlerly dates. I need to be able to compare two quarterly dates and get the number of quarters between them. For example: >>> 2001q1 = qDate(year=2001, quarter=1) >>> 2001q4 = qDate(year=2001, quarter=4) >>> 2001q4 - 2001q1 3 The only problem is that I have no idea how to override operators in python. Can anyone give me a few trivial examples of how it is done? And, on a completely unrelated note, I am getting a truly amazing amount of spam today. Anyone else? Thanks for the help. From grey at despair.dmiyu.org Sun Sep 7 01:36:03 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sun, 07 Sep 2003 05:36:03 -0000 Subject: OT: Americans love their guns References: Message-ID: On 2003-09-06, Bengt Richter wrote: > Well, when someone "loses it" and ignorantly mistakes you for the > devil, what would you rather see in their hand, a cocked "45" or a > banana? No, that isn't the question. The question is when someone breaks into my home which do I want more in my hand, a .45 (is a caliber, not a quote) or a banana. i Do this simple test. Get an egg timer (or any other timing device). Now set it to 4, maybe 5 minutes. Now lock yourself in the closet. While there imagine dying. Imagine someone gutting you. Imagine someone shooting you in the fact, your brains leaking out. Imagine the last vision you have is being raped or someone you loved being raped. If you have kids imagine them having their arms broken, guts torn apart, necks snapped. Go ahead. Do it. Once you done it answer me this one question: In those 4 minutes in that closet, hiding, scared, alone, praying for someone to come to save you how does legislation protect you and your loved ones from violence? In that time between you *MAYBE* getting a call to the police and them actually arriving when you could die which would you rather do, fight or die? What you've all missed is that violence still happens. The criminals who are so willing to rape, steal, break-in, murder and in general be far more unpleasant as the 2nd paragraph of this message aren't going to suddenly stop and say, "Hey, you know, owning a gun is ILLEGAL, I shouldn't do that while killing, raping, stealing and being an all around naughty person!" -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From jwdillworth at yahoo.com Mon Sep 15 16:07:11 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Mon, 15 Sep 2003 13:07:11 -0700 (PDT) Subject: irritating problem In-Reply-To: <20030915200024.48393.qmail@web41112.mail.yahoo.com> Message-ID: <20030915200711.8449.qmail@web41115.mail.yahoo.com> One thing I just thought of, it could be that when running with a shortcut your current directory isn't what you expect. Here's a modified script that outputs the current directory as well. import os, sys f = open('outfile.txt', 'w') for item in os.environ.items() + sys.path: print>>f, item print>>f, "current dir", os.getcwd() f.close() --- Jeremy Dillworth wrote: > You could create a shortcut to python.exe, then modify the > shortcut, adding your script to the command line. > > I'm pretty sure windows will view Python.exe as a "DOS" program, > so it in the shortcut properties box it'll have like 5 tabs > or so. One of them should contain a checkbox which reads something > like 'close DOS box when finished'. Unless MS has change that dialog > in XP.... > > Sorry, my windoze skills are a little rusty :) > > Another option might be to write a script like this: > > import os, sys > f = open('outfile.txt', 'w') > for item in os.environ.items() + sys.path: > print>>f, item > f.close() > > Run the script in the 3 ways you mentioned (changing name of outfile.txt > in between runs) and then check for differences in the 3 files generated. > > My guess would be it's something with sys.path, but you might > as well check environ was well :) > > > --- Park997 wrote: > > Hi, > > > > I have a script that runs correctly in IDLE, runs correctly when invoked in the > > Command Prompt (Win XP), runs correctly from Komodo, but flashes a black box > > too fast to see when the icon is double clicked and produces no output. There > > are no error meassages from any of the methods that produce output. All of the > > other modules in the same directory (these are imported to the problem module) > > work correctly in any start mode. > > > > python 2.3. > > > > Obviously this isn't a disaster, but it "bugs" me. Is there a fix or method of > > obtaining diagnostic information on this? > > > > Thanks, > > > > Wendell Cropper > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list From daniel.dittmar at sap.com Thu Sep 18 07:41:51 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 18 Sep 2003 13:41:51 +0200 Subject: Closures in python References: <9caba98e.0309180208.692e9b68@posting.google.com> Message-ID: Kasper B. Graversen wrote: > Having played with Smalltalk for the past month, I'm getting used to > passing code as arguments to methods... how easy is it to do this in > python? I haven't seen any recent postings on this subject here... There is no direct equivalent of code blocks in Python. Use Callables instead. Callables are - functions def mywrite (text): sys.stdout.write (text) variable = mywrite variable ('printed text') - bound methods, a method bound to a specific object variable = sys.stdout.write variable ('printed text') - lambda, unnamed functions, which can contain only one expression variable = lambda text: sys.stdout.write (text) variable ('printed text') - classes implementing the __call__ method class Writer: def __call__ (self, text): sys.stdout.write (text) variable = Writer () variable ('printed text') Daniel From python at sarcastic-horse.com Wed Sep 17 19:27:50 2003 From: python at sarcastic-horse.com (python) Date: Wed, 17 Sep 2003 19:27:50 -0400 Subject: how to write-protect names In-Reply-To: <3F68D53B.CE7DF693@engcorp.com> References: <3F68C499.1060604@aon.at> <3F68C60C.AC611276@engcorp.com> <3F68CE89.20601@aon.at> <3F68D53B.CE7DF693@engcorp.com> Message-ID: <20030917192750.5db38989.python@sarcastic-horse.com> Can you post a trivial example of how to use __setattr__() and how to set the namespace in the interpreter? Thanks. On Wed, 17 Sep 2003 17:42:19 -0400 Peter Hansen wrote: > Gregor Lingl wrote: > > > > Peter Hansen schrieb: > > > > > What exactly do you need this for? If you describe the purpose > > > you have in mind for it we can provide the best approach, or > > > tell you that we don't think you should bother. ;-) > > > > > > -Peter > > > > I'm writing a module for teaching young students. It contains > > e. g. a function width, which assigns a value to some (hidden) > > variable: > > > > >>> width(5) > > > > Now my experience is, that from time to time some of my > > students write (erroneously) > > > > >>> width = 5 > > > > which renders the function width unaccessible for future > > use. > > Ah, good. In that case the answer is fairly simple. You > cannot "write-protect" the name in the main module, but you > could use your own namespace for the methods such as width(), > putting them in something that looks like a module but is > really an object with a __setattr__() method which prevents > "overwriting" any of the existing names. Maybe util.width() > or something like that. > > The fundamental issue is really that names are merely labels > for the things themselves, and can be rebound at will. The > students aren't really overwriting anything, and the original > width() method still exists (if any other binding to it exists > anywhere), they are simply making the label "width" reference > a different object and you can't that without providing your > own interactive environment, I suspect. > > (And as a result, you still can't stop the students from binding > the name "util" to something else and still screwing up the above, > but perhaps you can trust the students not to do this if you > demonstrate it and explain why it's a bad idea.) > > -Peter > -- > http://mail.python.org/mailman/listinfo/python-list From gh at ghaering.de Sun Sep 7 13:26:07 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 07 Sep 2003 19:26:07 +0200 Subject: in Ram database? In-Reply-To: <20030905203058.179d9630.wtrenker@shaw.ca> References: <20030905203058.179d9630.wtrenker@shaw.ca> Message-ID: <3F5B6A2F.1090907@ghaering.de> William Trenker wrote: > Here is a simple [PySQLite] example: > > import sqlite #module name exposed by the PySQLite wrapper > conn = sqlite.connect(db=':memory:') #special connect string to open an in-memory db Please use 'database' or just use an unnamed parameter instead of a named one. 'db' is deprecated. > cursor = conn.cursor() #standard DB-API-2 from this point > cursor.execute('create table test (a varchar, b int);') No need for using semicolons in SQLite statements with the Python DB-API. Don't be surprised if you create problems this way. > cursor.execute('commit;') #end PySQLite implicit transaction If you use the Python DB-API, use the .commit() and .rollback() methods on the connection object. If you invoke COMMIT/ROLLBACK using .execute(), except the unexpected. > cursor.execute('begin transaction;') #wrap the inserts in an explicit transaction for speed > for i in range(0,10000): > cursor.execute('insert into test (a,b) values (%s,%i);'%(str(i),i)) > cursor.execute('commit;') > cursor.execute('select sum(b) from test;') > print cursor.fetchall()[0][0] Yuck! What's the point of all this building connections manually crap? Also, what's the point of working around the DB-API way of quoting parameters with .execute()? The DB-API modules will quote parameters correctly for you, be it string, int, float or whatever else the backend supports. This works by *not* using the Python % quote operator, but by using a second parameter to .execute() which will hold a tuple with the parameters to be inserted. So the correct example would look something like: #v+ import sqlite cx = sqlite.connect(":memory:") cu = cx.cursor() cu.execute("create table test(a varchar, b int)") for i in xrange(10000): cu.execute("insert into test(a, b) values (%s, %s)", (str(i), i)) # Please use %s for all parameter types in PySQLite cx.commit() cu.execute("select sum(b) as RESULTCOLUMN from test") print cu.fetchone()[0] # PySQLite extension: print cu.fetchone().RESULTCOLUMN cx.close() #v- Btw. for mass inserts you can use .executemany(), which with some DB-API modules is more efficient than calling .execute() in a loop. Like all Python DB-API modules whose backends support transactions, PySQLite uses transactions transparently. All you have to do is .commit() or .rollback() on the connection object. PySQLite does have an option to disable transparent transaction management for those who think they must shoot themselves in the foot. Those should use the parameter autocommit=0 in the sqlite.connect() call. -- Gerhard From sross at connectmail.carleton.ca Fri Sep 5 22:13:03 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 5 Sep 2003 22:13:03 -0400 Subject: list to string References: Message-ID: <1ob6b.4134$I_2.601166@news20.bellglobal.com> >>> vals = ['aaa', 'bbb', 'ccc'] >>> ', '.join(vals) 'aaa, bbb, ccc' From eppstein at ics.uci.edu Sat Sep 6 23:34:25 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sat, 06 Sep 2003 20:34:25 -0700 Subject: Why python??? References: <3335321.1062775466@dbforums.com> Message-ID: In article , Johann Hibschman wrote: > > I think many people spend time on Java and university uses > > Java because Sun Microsystem spends much money to promote and > > develop the Java language. > > Actually, in my experience, students will complain endlessly if they > have to use a language that they don't think will immediately get them a > job. So, usage of C, C++, and Java is probably student-driven, not > faculty-driven. I don't remember any discussion of student fears about relevance the last few times the issue of which language to use came up at faculty meetings. Employability of our graduates, yes, but student bitching, no. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From bokr at oz.net Sun Sep 7 14:39:31 2003 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2003 18:39:31 GMT Subject: Question on Standard Types References: Message-ID: On Sun, 7 Sep 2003 13:18:57 -0400, "John Roth" wrote: > >"hostmaster" wrote in message >news:mailman.1062951612.13844.python-list at python.org... >> Hi, >> >> I'm quite new to Python and I am reading this book called 'Core Python >> Programming' by Wesley J. Chun. I think that this is not a new book but >> I believe some of the points are still valid. >> >> There is this part in the book where it says: >> >> "In Python, standard types are not classes, so creating integers and >> strings does not involve instantiation". I think that is out of date. >> >> But later in the book, it talks about 'numeric objects' created when a >> numeric literal is assigned to a reference. >> >> So my question now is, if standard types are objects, shouldn't they >> have classes as well ? Isn't it that a class is the blueprint of an >> object? If they don't have a class to begin with, how are these objects >> created? By "standard types" you mean int and str etc.? Try interactive help for sume suggestive info: >>> help(int) Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer | | Convert a string or number to an integer, if possible. A floating point | argument will be truncated towards zero (this does not include a string | representation of a floating point number!) When converting a string, use | the optional base. It is an error to supply a base when converting a | non-string. If the argument is outside the integer range a long object | will be returned instead. | | Methods defined here: | | __abs__(...) | x.__abs__() <==> abs(x) | | __add__(...) | x.__add__(y) <==> x+y | ... (etc.) >>> help(str) Help on class str in module __builtin__: class str(basestring) | str(object) -> string | | Return a nice string representation of the object. | If the argument is a string, the return value is the same object. | | Method resolution order: | str | basestring | object | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y ... (etc.) > >He's trying to make a fairly subtle point. At least, it's subtle until >you get into the nuts and bolts. > >The point is that class instances are a single type, regardless of You don't mean instances of classes are a single type, I assume. You mean classes themselves are instances of a single type class, right? (Except old-style classes, which are of type classobj). >the class. So while it's perfectly true to say what he did, it has I don't know how you are reading it. It seems out of date to me. >very little practical meaning unless you attempt to do an operation >on, say, an integer that depends on something that's unique to >an instance. You can now subclass int and str etc., which has real and practical meaning though. And it's a pretty strong indication that int and str are classes of some kind ;-) Regards, Bengt Richter From martin at v.loewis.de Mon Sep 1 17:23:22 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Sep 2003 23:23:22 +0200 Subject: error when xml.dom parse file encoded in ISO-8859-15 References: Message-ID: Harobed writes: > I have a xml file encode in ISO-8859-15. When xml.dom parse this file, it > send this error : xml.parsers.expat.ExpatError: not well-formed (invalid > token): line 9, column 46 > > Line 9 content some accent char. I would like solve this error. You should correct the error in your XML file, by adding an xml header to it. Regards, Martin From newsgroups at jhrothjr.com Tue Sep 2 11:35:45 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 2 Sep 2003 11:35:45 -0400 Subject: what's wrong with REBOL? References: <6005702b.0309020727.4ba46e78@posting.google.com> Message-ID: "Mike Henley" wrote in message news:6005702b.0309020727.4ba46e78 at posting.google.com... > I first came across rebol a while ago; it seemed interesting but then > i was put off by its proprietary nature, although the core of the > language is a free download. > > Recently however, i can't help but say i was totally impressed. I > needed an open source wikiblog/wikilog, whatever you wanna call it, > basically a hybrid of a blog and a wiki. I checked out snipsnap, which > uses java, it was said on their site to be a clone of vanilla, a > wikilog written with rebol. I wanted an open source thing so i could > modify it to my needs. > > snipsnap turned out to be, even apparent on the first day of use, way > too far from being mature and reliable, and although they said it > doesn't require a server, it required a download of the sun java sdk, > which, when installed, was well over 400Mbs of space on my hard drive. > Not to mention another over 100Mbs for the JVM. > > So as i needed a mature enough solution, but liked the way snipsnap > worked, i looked around, and on freshmeat i found vanilla, with a > development status of 5; production/stable. I went to its site, where > a working demo impressed with its capabilities. The site is though > poorly documented, very poorly documented i had to use trial and error > to work out how to install it. Anyhow, what impressed me was that the > download, which was less than half a megabyte, installed vanilla, > which is the wikilog, an apache server, and the rebol interpreter, > which is the free download version. And it self-installed! It turned > out to be a very very capable wikilog, and highly extensible. I am > still amazed and impressed by it after a couple of days of use. > > Rebol itself seemed a very easy to read language. Sorta like ho > readable SQL is. I might even say more readable than python or ruby, > or at least as readable. > > I have the intention to learn it over the coming few days, at least to > customize vanilla to my needs. > > So i ask you guys, what's wrong with Rebol? i mean other than it's > proprietary nature. 'cos anyway, there are many commercial IDEs for > open source languages, and if smitten enough i might even consider a > rebol SDK. It just amazes me for how readable it is, how much it seems > to enable to do with so little code, and the size and capability of > the final solution. > > What's wrong with Rebol? I don't know that there's anything "wrong" with it, other than it's a special purpose language designed to fit in one niche, and do its job well (at least in the eyes of its designers.) I'm not about to download a humongous reference manual to compare it with Python. If it serves your needs, go for it. John Roth From geoff at gerrietts.net Thu Sep 11 20:24:10 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Thu, 11 Sep 2003 17:24:10 -0700 Subject: Web server with Python In-Reply-To: References: Message-ID: <20030912002410.GF2085@thoth.homegain.com> Quoting Patrick Useldinger (p.useldinger at myrealbox.com): > Webserver: > - Medusa > - Twisted > - Zope > Which one is the easiest to work with? Which one is known to work on an > AIX 5.1 platform, for instance? Medusa is pretty low-level. It's really just a server framework with not much in the way of form handling or other niceties. Zope is pretty high-level. It's at its best in doing content management, and does a decent job of being an appserver. Its biggest shortcomings, in my disreputable opinion, are its use of an object database and its innovative features. The object database makes it hard to edit stuff except in the web interface. Several of the innovative features -- security roles, user authorization, and acquisition to name a few -- make serious, highly-dynamic development under Zope challenging. You are effectively learning the intricacies of a highly-evolved application. On the other hand, if your applications fit into typical categories -- content management, information publishing, forums, etc -- Zope has lots of pre-built tools that you can use. Also, it really depends on how dynamic your "dynamic" is. A friend of mine runs a job database: not too many writes to the DB and lots of reads from it, a couple common data types. Zope would be okay for his stuff. I work on a site where every user submits a profile, and lots of information is exchanged between users, and every page's content is entirely different based on the current user's nest of objects. We had to punch a hole in the side of Zope and we suffer from performance problems due to the highly dynamic content. I've looked at Twisted but not used it. It's got some of the low-level features that Medusa does, but it's also got some of the higher-level form handling and such that you get out of Zope. It's worth a look. Also worth a look is WebWare. I've only done a little bit with WebWare, but it's very similar in architecture and execution to the Java Servlet API. If I were starting from scratch, that would be my toolkit of choice for a highly stateful, highly dynamic app. I can't speak to AIX. You might be the first to try some of these on those platforms. My advice in those cases is to look at the stuff that uses as little C code as possible, because gauging portability isn't too easy. > Persistent storage > - Is ZODB easily usable from outside Python, i.e. to produce reports > without reverting to programming? No. ZODB is an object database. You put objects in and build your own indexes to those objects. You get them out the same way you put them in. ZODB is easily usable from /inside/ Python though: it does not require you to explicitly handle the object-to-relational mapping that a SQL database will. > - Is MySQL with Python a good combination? I can't comment on MySQL directly, because I've used it only a little from Python. SQL in general suffers from the difficulty that you need to write the queries to store and retrieve your objects from the databse yourself: that process is called object-to-relational mapping, and it's hard to do well and easy to do in ways you'll regret later. But, the SQL databases are easily accessible from a quadrillion other tools that can do reporting for you. Hope this helps, --G. -- Geoff Gerrietts "I think doorways are sexist." --Jayson Lockwood From nospam at here.com Thu Sep 11 16:52:59 2003 From: nospam at here.com (Richard Townsend) Date: Thu, 11 Sep 2003 21:52:59 +0100 Subject: tkinter, sockets and threads together References: <79ad5955.0309111133.5f6bf26f@posting.google.com> Message-ID: <1063313355.26667.0@iris.uk.clara.net> > i read that it is bad to use threads with tkinter. so my question is > how does one create a gui program with sockets? at one point you have > to call mainloop() which does not return. then you are not free to do > stuff with the sockets. > Take a look at http://www.python.org/doc/faq/gui.html#can-i-have-tk-events-handled-while-wa iting-for-i-o RT From tjreedy at udel.edu Thu Sep 25 19:34:48 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 25 Sep 2003 19:34:48 -0400 Subject: "for" with "else"? References: Message-ID: "Michael Geary" wrote in message news:vn67fhhom95896 at corp.supernews.com... > Mark Jackson wrote: > > (This happens to be the *reverse* of what my intuition expects - it > > would seem more natural if the syntax meant "do this for loop to > > completion, else do this extra stuff," but this is the way it is and > > one must simply remember it.) > > I'm with you there--the use of "else" here has seemed a bit confusing to me. How I plan to remember now: if the abnormal exit is a return or exception, then all code end of for block, including any else part, to the end of the function or try block will be skipped, so else part can only apply to normal exit. Terry J. Reedy From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 12:51:45 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 17:51:45 +0100 Subject: Thoughts on PEP315 References: <18kvmvobs9jsq50o91m35cveu49heev7mh@4ax.com> Message-ID: On 23 Sep 2003 06:27:44 -0400, Heather Coppersmith wrote: >Don't forget that values other than "True" are true, too >(shamelessly stolen from a previous post from Tim Peters): > > # basic file iteration (which can be done in other ways, but > # simply demonstrates my point) > while "there is another line in the file": > nextlinefromfile = getnextlinefromfile( ) > if not nextlinefromfile: > break > moresprocessing( ) Thanks - to you and Tim - score 1 for self-documenting code! -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From neil.padgen at mon.bbc.co.uk Fri Sep 5 11:04:30 2003 From: neil.padgen at mon.bbc.co.uk (Neil Padgen) Date: Fri, 05 Sep 2003 15:04:30 +0000 Subject: Massive unit test vs MySQL References: Message-ID: On Thursday 04 September 2003 20:35, Richard Wesley wrote: > I have a unit test suite for our server that loads a clean database > image for many of the tests. I use > > p = os.popen('mysql -u uid -ppassword mydatabase', 'w') > p.write(sql_commands) Your pipe is still open at this point, and therefore you have a connection to the database open. > So my question would be, is there any way to shut down the child > process so that MySQL notices and cleans up after itself before it > runs out of threads? p.close() -- Neil From mwilson at sarcastic-horse.com Sun Sep 21 16:24:22 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Sun, 21 Sep 2003 16:24:22 -0400 Subject: Download to client from a cgi script? In-Reply-To: References: Message-ID: <20030921162422.25c26aa7.mwilson@sarcastic-horse.com> If you want to trigger the browser to ask 'save this file?' then you gotta pass it a Content-Type that will trigger that. At the top of your cgi script, get rid of 'Content-Type: text/html\n\n' and replace it with 'Content-Type: application/octet-stream' or something like that. This page: http://ppewww.ph.gla.ac.uk/~flavell/www/content-type.html describes some IE bugs. Good luck! If you figure it all out, can you post a message back here for future reference? On Sun, 21 Sep 2003 21:28:46 +0200 ?ystein Johansen wrote: > Hi, > > (This question may be stupid, but I just can't find the answer...) > > How can I make the browser downlaod a cgi script from /cgi-bin/. > Obviously I can't make a link to it with , > since tha script will be executed then. > > I see how Lutz in PP2E prints the script on the screen, but I want the > user to get the "save file" message box? > > Same thing. What about a binary file? Printing a binary file with > getfile.cgi from PP2E is just silly. The surfer must be promped to save. > So, what I want is a script like getfile.cgi, that downloads insted of > prints the file. > > > (Maybe this is more a HTTP/HTML question than a Python question...) > > Clueless, > -?ystein > > -- > http://mail.python.org/mailman/listinfo/python-list From bokr at oz.net Mon Sep 29 19:06:20 2003 From: bokr at oz.net (Bengt Richter) Date: 29 Sep 2003 23:06:20 GMT Subject: A startup puzzle References: Message-ID: On Mon, 29 Sep 2003 16:27:39 -0500, "Edward K. Ream" wrote: >> Perhaps using a proxy object...might work: > >Great idea! Some complications: > >1. Sometimes the test "if not realApp:" causes unbounded recursion. To >avoid any possibility of this happening the startup code just creates the >app object before any code actually uses the app proxies. This is easily >done. 1a. I suspect Glenn's code would also need a global realApp in the __getattr__ method, or it would just keep seeing a global realApp==None and recreating the app instance to a local realApp that disappears after its desired attribute is returned. (BTW my version just let an exception happen if use was attempted before setting the real app reference). > >2. A __call__ method in the proxy allows the code to use either app().x or >app.x. > >In short, the following pattern appears like it will work in all my modules: > >from leoGlobals import * >app = leoProxy() # leoProxy defined in leoGlobals ISTM it would be safe to put the above line in leoGlobals at the top, after the class definition, and then app would just come in with the import *, so in general your modules will only need the one-line from leoGlobals import *. (see my post for more info. BTW, I didn't see Glenn's post 'til after, honest ;-) ># Now the code can reference either app.x or app().x. Cool. Gives you some backwards compatibility I guess. > >To do this, I use the following code: > Since the code is only executed once on import, I think you could put this at the top of leoGlobals >gApp = None # Set before any reference to proxy. >class leoProxy: > def __getattr__(self,attr): > return getattr(gApp,attr) > def __call__(self): > return gApp (Unlike Glenn's code, this doesn't need a global gApp declaration). and then at the bottom of leoGlobals you could do (untested) gApp = __import__('leoApp').leoApp() Or you could (untested) even do it later from somewhere else as leoGlobals.gApp = __import__('leoApp').leoApp() > >Many thanks for this great idea. I should've just blurted and not fooled with testing, I guess ;-) Actually, I wonder whether the snap-shot effect you seem to get in a secondary module's import of the module whose import code you are in the middle of executing is something one can depend on in detail not to change. (though I'm not sure what kind of change could be reasonable ;-) And what happens if there are side effects from the secondary activity that puts something in the module globals -- will that show up in subsequent imports immediately? I guess it comes down to whether import locks in a module instance and ties it to sys.modules immediately, so its state can be modified and viewed incrementally. It seems so. I guess the dict involved is the environment that the imported module code gets executed in. Further .02USD are in my other post ;-) Regards, Bengt Richter From max at ucmg.com.ua.remove.it Thu Sep 4 03:22:39 2003 From: max at ucmg.com.ua.remove.it (Max Ischenko) Date: Thu, 04 Sep 2003 10:22:39 +0300 Subject: Interoperability between VB and Python under ASP In-Reply-To: References: Message-ID: > I've mostly done option 3, converting what I needed to Python. It > results in a lot cleaner code (you can't mix html elements and code > very well, for example, in vb you can put a for loop around a section > of HTML, whereas in Python you can't) and the time it took to convert > the code (not much, really, it's a pretty clean port in most cases) > has been more than paid back in maintainability. That's sounds encouraging, thanks. I'd probably go this route. -- Regards, Max. From cygwin-help at cygwin.com Fri Sep 5 12:42:17 2003 From: cygwin-help at cygwin.com (cygwin-help at cygwin.com) Date: 5 Sep 2003 16:42:17 -0000 Subject: confirm unsubscribe from cygwin@cygwin.com Message-ID: <1062780137.21812.ezmlm@cygwin.com> Hi! This is the ezmlm program. I'm managing the cygwin at cygwin.com mailing list. To confirm that you would like python-list at python.org removed from the cygwin mailing list, please send an empty reply to this address: cygwin-uc.1062780137.kbieladcacinmagdhccn-python-list=python.org at cygwin.com Usually, this happens when you just hit the "reply" button. If this does not work, simply copy the address and paste it into the "To:" field of a new message. I haven't checked whether your address is currently on the mailing list. To see what address you used to subscribe, look at the messages you are receiving from the mailing list. Each message has your address hidden inside its return path; for example, mary at xdd.ff.com receives messages with return path: -mary=xdd.ff.com at cygwin.com. Some mail programs are broken and cannot handle long addresses. If you cannot reply to this request, instead send a message to and put the entire address listed above into the "Subject:" line. --- Administrative commands for the cygwin list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: To remove your address from the list, send a message to: Send mail to the following for info and FAQ for this list: Similar addresses exist for the digest list: To get messages 123 through 145 (a maximum of 100 per request), mail: To get an index with subject and author for messages 123-456 , mail: They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: To stop subscription for this address, mail: In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at cygwin-owner at cygwin.com. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: Received: (qmail 21804 invoked from network); 5 Sep 2003 16:42:15 -0000 Received: from unknown (HELO manatee.mojam.com) (199.249.165.175) by sources.redhat.com with SMTP; 5 Sep 2003 16:42:15 -0000 Received: from montanaro.dyndns.org (titan.itcs.northwestern.edu [129.105.214.230]) by manatee.mojam.com (8.11.6/8.11.6) with ESMTP id h85Gg8M13822 for ; Fri, 5 Sep 2003 11:42:09 -0500 Received: from montanaro.dyndns.org (localhost [127.0.0.1]) by montanaro.dyndns.org (8.12.9/8.12.2) with ESMTP id h85GgBGp029851 for ; Fri, 5 Sep 2003 11:42:12 -0500 (CDT) Received: by montanaro.dyndns.org (8.12.9/8.12.2/Submit) id h85GgBoZ029848; Fri, 5 Sep 2003 11:42:11 -0500 (CDT) From: Skip Montanaro MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <16216.48355.536824.307934 at montanaro.dyndns.org> Date: Fri, 5 Sep 2003 11:42:11 -0500 To: cygwin-unsubscribe-python-list=python.org at cygwin.com X-Mailer: VM 7.14 under 21.5 (beta9) "brussels sprouts" XEmacs Lucid Reply-To: skip at pobox.com From tjreedy at udel.edu Fri Sep 26 17:28:02 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2003 17:28:02 -0400 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> Message-ID: "Roberto A. F. De Almeida" wrote in message news:10c662fe.0309261245.1f35f43a at posting.google.com... > I found that when using negative indices, the slice object passed to > __getitem__ depends on the number of slices. An example to clarify: > >class a: > def __getitem__(self, index): > return index > > >>> b = a() > >>> print b[:-1] > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: a instance has no attribute '__len__' > > But if I pass a "multiple" slice: > > >>> print b[:-1,:-1] > (slice(None, -1, None), slice(None, -1, None)) A square-bracketed subscript (index/key) is a *single* object, in this case a tuple. The contents of the tuple are irrelevant (for this code). Any tuple will be echoed: >>> b[1,2,3] (1, 2, 3) > If we add the following __len__ to class a: > > def __len__(self): > return 42 Completely irrelevant for the processing of tuple keys. > Is there something wrong in using slices like this in objects? A > better way? What you probably want is b[:-1][:-1], etc. Each index must be separately bracketed to access items in list of lists (etc). Terry J. Reedy From pxtl at hotmail.com Wed Sep 17 22:49:53 2003 From: pxtl at hotmail.com (martin z) Date: Thu, 18 Sep 2003 02:49:53 GMT Subject: Graphic python debugger References: <20030917120146.3c5202e2.max@fr.fm> Message-ID: > GNU DDD is a graphical front-end for command-line debuggers such as GDB, > DBX, WDB, Ladebug, JDB, XDB, the Perl debugger, or the Python debugger. > ^^^^^^ A little offtopic, but you wouldn't happen to know if DDD + GDB can handle Ada? I know that GDB can do Ada code, but I don't know how well a front-end could handle Ada's idiosynchrosies if its expecting GDB to be used with C. From fumanchu at amor.org Tue Sep 30 12:54:16 2003 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 30 Sep 2003 09:54:16 -0700 Subject: How to instatiate a class of which the name is only known at runtime? Message-ID: > note that module names are stored fully qualified in sys.modules so the try > clause in your will always fail with modules like os.path.... > __import__() does a lookup in sys.modules so that you need not recode it. Thanks! I think that try: block was left over from an older version which used imp.find_module and .load_module. Now that I'm not splitting out the module name, I also don't need to have two __import__ calls. Finally, I sped up the initial parsing with rfind() and slicing. def get_func(fullFuncName): """Dynamically load a module and retrieve reference to the function (NOT an instance).""" # Parse out the path, module, and function lastDot = fullFuncName.rfind(".") funcName = fullFuncName[lastDot + 1:] modPath = fullFuncName[:lastDot] aMod = __import__(modPath, globals(), locals(), ['']) aFunc = getattr(aMod, funcName) # Assert that the function is a *callable* attribute. if not callable(aFunc): raise AssertionError("%s is not callable." % fullFuncName) # Return a reference to the function itself, not the results of the function. return aFunc > Maybe you should raise a TypeError rather than an ImportError to indicate > that what is expected to be a function is not callable. How about an AssertionError, since it's only included for programmers, not users? Robert Brewer MIS Amor Ministries fumanchu at amor.org From jepler at unpythonic.net Mon Sep 22 08:50:24 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 22 Sep 2003 07:50:24 -0500 Subject: Mutable strings In-Reply-To: <2ZBbb.100213$hE5.3539928@news1.tin.it> References: <6e990e29.0309220251.51fa648d@posting.google.com> <2ZBbb.100213$hE5.3539928@news1.tin.it> Message-ID: <20030922125024.GE32482@unpythonic.net> On Mon, Sep 22, 2003 at 12:31:58PM +0000, Alex Martelli wrote: > But, there IS one! So, hat's wrong with it...?! People seem to love to have literals for things. Otherwise, they feel that a type is second-class. Jeff From donn at u.washington.edu Mon Sep 15 14:22:04 2003 From: donn at u.washington.edu (Donn Cave) Date: Mon, 15 Sep 2003 11:22:04 -0700 Subject: Is there "let binding" in Python? References: Message-ID: In article , Rob Hunter wrote: ... > I'm simply trying to learn to write in Python in > a way that I will find tolerable. I really like > a lot of it, so far, and I find it fun to write > it, and very pretty and easy to read. > > In general, in most cases, I find it > *unacceptable* to use mutation. And, since > Python is very much a Scheme-like language, and > has functional components (like map, and > uh...functions :) with proper scoping) I think > that this is quite a reasonable thing to want. > The trick is knowing when mutation happens, so > that the programmer is aware when s/he is > entering a scary land where things may not be > what they seem. And it seems from your > references and my tests that the "=" operator is > mutative. In Scheme there's no issue..you > introduce a binding with LET and you mutate a > binding with SET!. In Python, the way I see it, > you introduce a binding with "=" and you mutate a > binding with "=". I sympathize, to some degree. I agree that this feature, call it mutation or as Python users would say "rebinding", has the potential to make it harder to reason about code. I am not convinced though that Python is so very much like Scheme, nor that the resemblance would be grounds for Python to go ahead and make all of Scheme's mistakes. Scheme users can continue to glory in their shining example of the perfectability of computing languages, because Python is just not like Scheme in this respect, and more in general is not a functional programming language. If you like the FP features that have been strapped onto it, that's great, many people do, but you don't make a donkey into a marine mammal by strapping on flotation. And for that matter it isn't clear that it's an overall improvement for the donkey. It's also not clear to me that Scheme gains an impressive victory here in terms of reasoning about code, if it still supports that pesky mutation. Is this sort of a kitchen sink language that tries to support every possible thing? If you like the FP route, wouldn't something like Haskell be better, more rigorously pure functional? Donn Cave, donn at u.washington.edu From wmgill at wmgill.com Fri Sep 12 13:32:47 2003 From: wmgill at wmgill.com (WmGill) Date: Fri, 12 Sep 2003 13:32:47 -0400 Subject: date formatting Message-ID: I want to write a script that Among other things) renames a file based on it's timestamp. I can get the date info using "strftime('%y%m%d',localtime(os.stat('thefile')[ST_MTIME])", but this seems like a long way around the block. Is there a more direct way? Bill From cfox at cfconsulting.ca Sun Sep 21 07:31:40 2003 From: cfox at cfconsulting.ca (Colin Fox) Date: Sun, 21 Sep 2003 11:31:40 GMT Subject: XML/XSLT with Python References: Message-ID: On Sat, 20 Sep 2003 22:32:59 +0200, K. N. wrote: > > Is there any good and fast Python module for XSLT > processing ? I'm going to use XML and XSLT to generate > web pages, so I need XSLT processor that will be able > to transform for example a DOM object in memory - I > don't want to create XML file containing data and then > load it and transform with XSLT, but I want to do > this at once - without writing to a temporary file. > Actually I've seen alot articles about parsing XML, > but nothing about creating XML documents and storing > it as an object that will be passed to XSLT processor, > and that is what I'm planning to do. > I think its a quite good solution, but I have no idea > which modules will be most suitable for this task. > Does anyone have some experience in this matter and > could point me where should I look ? > > Best regards, > K. Here's a CGI I wrote to do this very thing. It uses libxml2 & libxslt from the gnome libraries. I wanted to make sure it was reasonably efficient, so I put a bunch of timing code into it. It turns out that processing an XML file, and running it through this XSLT processor is really fast. I didn't bother to include page.xsl here, as it's actual contents are irrelevant to the technique. Enjoy! cf ------------------------ #! /usr/bin/env python import time st = time.time() import libxml2, libxslt import cgi, os, sys query = cgi.FieldStorage() readtimestart = time.time() styledoc = libxml2.parseFile("page.xsl") style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseFile(query['script'].value) readtimeend = time.time() start_converting = time.time() result = style.applyStylesheet(doc, None) done_converting = time.time() html = result.serialize() print "Content-type: text/html" print print html style.freeStylesheet() doc.freeDoc() result.freeDoc() et = time.time() totaltime = et-st print "" % totaltime print "" %\ (done_converting-start_converting) print "" %\ (readtimeend-readtimestart) From vze4rx4y at verizon.net Sun Sep 21 16:24:04 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 21 Sep 2003 20:24:04 GMT Subject: math.exp(complex) References: Message-ID: [David Eppstein] > Why doesn't this work? > > >>> import math > >>> math.exp(1j*math.pi) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: can't convert complex to float; use e.g. abs(z) > > The expected answer, of course, is -1. > > It does work if you do it like this: > > >>> math.e**(1j*math.pi) > (-1+1.2246467991473532e-16j) > > So why not math.exp(complex)? Use the cmath module for complex ops: >>> import cmath >>> import math >>> cmath.exp(1j*math.pi) (-1+1.2246063538223773e-016j) Raymond Hettinger From jcribbs at twmi.rr.com Thu Sep 4 08:01:06 2003 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Thu, 04 Sep 2003 12:01:06 GMT Subject: test Message-ID: <6QF5b.581$FJ5.34940@twister.columbus.rr.com> Please disregard this message. From usenet_spam at janc.invalid Sat Sep 27 20:32:28 2003 From: usenet_spam at janc.invalid (JanC) Date: Sun, 28 Sep 2003 00:32:28 GMT Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> schreef: > I do remember that the non-deletable file was in a deeply nested set > of pointless folders created by saving that web site. IIRC that is or was a bug on (some) Windows versions: the path+filename you have to pass to the Delete File API function could be too long for the reserved string buffer length (256 bytes), or something like that... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From howard at eegsoftware.com Thu Sep 4 23:10:17 2003 From: howard at eegsoftware.com (Howard Lightstone) Date: Fri, 05 Sep 2003 03:10:17 GMT Subject: Starting point for unicode conversion Message-ID: I *foolishly* started a Python project (3 years ago) with considering Unicode issues. Now, I want to resolve future problems with international versions of my software. The key point here is Tkinter. I believe (from reading this list) that I can expect that SOME returned text may be Unicode (depending on content and Windows locale settings). Would it be best to just (somehow) force all text into Unicode or would it be "better" to handle specific instances? I also have the problem of embedded text in data files I create that I have to store as *something* that I can fully recover and convert back to something reasonable even if the locale changes. Any thoughts welcome .... this is something I am NOT looking forward to. Thanks From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 24 01:07:21 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 24 Sep 2003 06:07:21 +0100 Subject: Thoughts on PEP315 References: Message-ID: <6f52nvsobkkf2n3p6stum3ipd5cp96i3pv@4ax.com> On Tue, 23 Sep 2003 21:59:15 -0400, Gordon Airport wrote: >The point of do-while loops is that you don't need setup code anymore, >right? How about this: > >... >dowhile : > >... > >where the body is run once before it becomes a standard while loop. It >looks like we all think of this structure as a "do-while loop", so the >expression is natural. This also makes it easy to change loop types - >just add or remove the "do". Slight downside is that the execution flow >isn't exactly as you read it. This doesn't really solve the problem that the PEP aims to solve. The setup code in the following example (from the PEP) is only *part* of the code in the loop... do: while : The condition is tested in the middle. The precondition form duplicates the setup - this is what the PEP was trying to avoid... while : But the postcondition-compliant form is really no better... do : if : until ! : (or if you insist) dowhile : if : You're simply duplicating the condition instead of the setup code. As loop conditions are often at least as complex as the setup code, there is really no gain here. In addition, the 'if' isn't explicitly a loop exit point - it's just a nested structure that achieves the same effect - so it doesn't express as clearly the intention behind the code. The whole point of the syntax in the PEP is to have the loop condition tested in the middle of the loop - something which in C (and current Python) is handled badly by the unstructured 'break'. Secondly, what the PEP suggests is not what most people think of as a 'do-while' loop. Anyone sufficiently familiar with C, C++, Java, ... will see a 'do-while' loop as being postconditioned (much like repeat-until in Pascal etc) - ie not having the loop condition tested in the middle as the PEP proposes. Finally, IMO execution order should match reading order unless there is a *VERY* good reason to do differently. Pascal, C and even Basic manage to show a precondition at the start of a loop, but a postcondition at the end of a loop. I don't see any good reason why Python can't follow suit. IMO, a loop exit point should... (highest priority first) 1. Be written at the point where the condition is tested, such that execution order is the same as reading order. I don't want to see variables referenced in a condition that haven't even been defined yet, for instance. You see this as minor - I see it as *very* important. 2. To be clearly identifiable be its leading keyword(s), and in particular not be confusable with the start of a new structure. This is a problem with the C 'do ... while' - it isn't always clear that the 'while' is part of the 'do' loop rather than the start of a new 'while' loop. IMO we don't need this hassle in Python. 3. Be linked to the loop itself, much as 'else' is linked to 'if', by having the same indent level and the ':' marker at the end of the line. This is IMO relatively minor - I don't object that much to the existing 'if condition : break' - but I believe it is important to the PEP authors logic. Basically, readability and maintainability are key obsessions of mine (and pretty much anyone who has had to read and maintain large systems written by other people). I'm not really sure why people don't like 'break if' - but then of course I don't, it is my invention ;-) Maybe it's to do with the return to the indent level of the earlier 'while' - but then 'elif' and 'else' already do this in 'if' blocks. More likely it is that bit in point 3 above - I think it is a good idea for a loop exit point, but it isn't exactly normal practice. Adas 'exit when' is, as I mentioned, the closest match I know of. Maybe 'break if' would end up being like a certain common reaction to Pythons use of indentation for structuring (initial shock and disgust, but growing to love it) or maybe I'm just wierd ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From niemeyer at conectiva.com Tue Sep 16 18:11:07 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Tue, 16 Sep 2003 19:11:07 -0300 Subject: Datetime utility functions In-Reply-To: References: <182bcf76.0309150707.3a8c0482@posting.google.com> Message-ID: <20030916221106.GA7721@ibook.distro.conectiva> > > you both use the same indirect way of getting to the end of the month. > > why not do what datetime.c does, like: > > Mainly because that seems even more like reinventing the wheel. > Writing code that already exists is something I dislike doing at the [...] Why not using calendar.monthrange()? -- Gustavo Niemeyer http://niemeyer.net From dakidd at sonic.net Thu Sep 25 17:25:27 2003 From: dakidd at sonic.net (Don Bruder) Date: Thu, 25 Sep 2003 21:25:27 GMT Subject: Another Python rookie trying to port to C/C++ question. References: <8yoc1wwt.fsf@python.net> Message-ID: In article <8yoc1wwt.fsf at python.net>, Thomas Heller wrote: > Don Bruder writes: > > [rewriting a Python program in C/C++] > > Something like this C construct: > > > > struct DictStruct > > { > > char *KeyArray[]; > > ValType ValArray[]; > > } > > > [...] > > Similarly, would something like: > > > > struct DictStruct > > { > > char Key[25]; > > ValType Value; > > DictStruct *PrevDictEntry; > > DictStruct *NextDictEntry; > > } > > > > [...] end up behaving at least reasonably like a Python "dict"? > > Yes. > > Except that it would be less flexible, *much* slower, and > probably much more buggy. > > Thomas Well, since I'm not worried about "flexible", have my doubts about the "much slower" part, and have no reason to believe that choice of language automatically makes a routine buggy, I'll go with the tenative plan I had. Seems you're confirming that I'm understanding things properly when it comes to "This is what a dict is, and here's how it works." Now to put finishing touches on my understanding of exactly what goes on inside that "black box" that is the "dict" class/type/whatever-it-is-you-Python-types-like-to-call-such-things, and make some working code out of it... -- Don Bruder - dakidd at sonic.net <--- Preferred Email - SpamAssassinated. Hate SPAM? See for some seriously great info. I will choose a path that's clear: I will choose Free Will! - N. Peart Fly trap info pages: From vze4rx4y at verizon.net Thu Sep 25 14:38:20 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 25 Sep 2003 18:38:20 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> Message-ID: [Andrew Dalke] > However, the example code will work on a string, because list(string) > returns a list, which does have a reverse. Right. I'll remove the comment. > ] Extending slicing minimizes the code overhead but does nothing > ] for memory efficiency, beauty, or clarity. > I don't agree with all three of those. Beauty and clarity are a matter of taste and we differ here. To some (including me), s[::-1] looks more like line noise than s.iter_backwards(). Also, I think the word form is more clear. The situation becomes more acute when the other indices have values. Compare range[n-1, 0, -1] to range(1, n-1).iterbackwards(). Whenever negative indicies are used, it takes more knowledge of the implementation rules to be able to read,write, understand, and verify the code. > ] Should file objects be included? Implementing reverse iteration > ] may not be easy though it would be useful on occasion. > > I would suggest no - the file may not be seekable. Agreed. > One thing to bear in mind is that the semantics are slightly > different. . . . > That is only a very, very minor nit. Feel free to ignore it :) Agreed. If finalizer call order is important, then the 'while elist: elist.pop()' form is the way to go. If not, then the for-loop is the way to go. > The former is more terse, but the latter, existing code is > broken down into bite-size chunks and allows verbose > documentation of each step. That isn't possible when > nearly everything is written in one line. Even the former can be broken down into more lines if that is what is needed: result.sort() result = result[-n] return [x for score, x in result.iter_backwards()] > Also, a variant implementation may be even more concise, You must be pretty confident to take on the Timbot's code ;-) > Later in your post you mention a reason against a function > which uses __riter__ magic is that it is "slower than direct > access to the underlying object." > > If that's a concern then you should also point out that using > iter_backwards for cases like this is slower than the existing > solution. (It has an extra attr lookup and function call. OTOH, > doesn't the -1, -1 require two calls of the negative unary op > code, or has that been fixed? Good, it has, says dis on > some test code.) Yes, it's true. All of the speed comments focus on the inner loop. I'll reword to make that clear. It is definitely an issue. In Py2.2, there was a generic sequence iterator that used __getitem__ in iterators for lists and tuples. In Py2.3, we went to a custom iterator for each object. There was a significant improvement in performance. > ] platform._dist_try_harder() . . . > I think a better reformulation is > > verfiles = os.listdir('/usr/lib/setup') > verfiles = [name for name in verfiles > if name.startswith("slack-version-")] I like your version better and recommend you submit it as a patch. I'll take out the ifilter() comment. > ] random.shuffle() uses for i in xrange(len(x)-1, 0, -1) > This isn't a use case. The xrange never returns a 0 while > the iter_backwards one will. It is an important use case. The replacement code is: for i in xrange(1,len(x)). iter_backwards() Whenever the indices have any complexity, the forwards version, followed by .iter_backwards() is, IMHO, much easier to mentally verify. > There were two intermediate 'reverse' proposals. Here's the four > I know about: I'll try to add these without making the PEP as long as this thread ;-) > I agree with the conclusion that the last three have unexpected > interactions with mappings. However, iter *also* has unexpected > interactions with mappings. Yes, but that doesn't make it less of a disadvantage. The proposed list.iter_backwards() method does not have that disadvantage. > In your post list a set of problems with the function approaches. ... > I would like to see this list added to the PEP. Okay. They are added. > I do have' > some qualifiers for the list. > > - it doesn't need to be a global function; it could be in, > say, itertools. (I know I originally suggested it as a builtin, > but I'm not saying I'm right ;) If there is to be a magic method, __riter__, then the access function needs to be a builtin. They go hand in hand. BTW, don't underestimate the intensity of resistance to adding new builtins. > - (see comments above that xrange(5).iter_backwards() > is likely slower than xrange(5, -1, -1) because of the > extra lookup and call) Reworded it to talk only to the inner loop, "approaches using __getitem__() are slower using a custom method for each object." > - the first variant, which only looks for __riter__ and raises > an exception if it doesn't exist, has exactly the same problems > with infinite iterators as calling the new method. > > - similarly, it doesn't have additional problems with mappings. Okay, I've moved the comments around for you. > Also, none of the use cases dealt with infinite sequences so > the lack of appropriate support for them shouldn't be considered > an outright rejection. The use cases were just the ones I found in the library. With generators and itertools being new, I expect infinite iterators to become more common. Also, I have a preference for creating something that is as robust as possible. Making a builtin function that doesn't apply to all objects; behaves badly with mappings; and crashes with an infinite iterator is not my idea of robust. I really don't understand the overpowering urge to make this a function and add a new magic method protocol. Why isn't there a similar rage against dict.iteritems()? Perhaps, you'll like it better if the method is named ireverse() instead of iter_backwards(). > BTW, my current belief is that if this PEP leads to code > then it should be: > - a new function, either builtin or in itertools > > - which uses __riter__ if present (unless we decide to > use the adapt PEP) > > - else uses "for i in itertools.count(): yield[obj[-i]]" Okay, we simply disagree here. That's fine. I appreciate the thoughtful comments and careful analysis. They have helped clarify the pep wording and helped to define the issues. Raymond From nicola-mingotti at libero.it Wed Sep 17 12:51:59 2003 From: nicola-mingotti at libero.it (Nicola Mingotti) Date: 17 Sep 2003 18:51:59 +0200 Subject: fast way to filter a set? References: Message-ID: fortepianissimo at yahoo.com.tw (Fortepianissimo) writes: > I know I can do things like > > s=Set(range(1,11)) > s=Set(filter(lambda x:x%2==0,s)) > > But this seems a bit slow since filter returns a list which then must > be converted back to a set. Any tips? Thanks! Can you ? I tried python2.3 and 2.2 and it replies : "NameError: name 'Set' is not defined" . There is a PEP but it seems it's steel 'under consideration'. http://www.python.org/peps/pep-0218.html May be , if this proposal is accepted you one day could write : { x for x in S if x%2 == 0 } # S be a set . bye. From claird at lairds.com Mon Sep 1 05:12:24 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 01 Sep 2003 09:12:24 -0000 Subject: Language categories (was: Advice to a Junior in High School?) References: Message-ID: In article , Sean Ross wrote: > >> "Sean Ross" writes: >> >> > (Lisp, Dylan, Haskell, ocaml, or some other functional programming >> > language). . . . >Okay. "..., or some other language that supports functional programming >style)" (which would include those mentioned, and many more besides). For >instance, > >http://directory.google.com/Top/Computers/Programming/Languages/Functional/?tc=1 >Aleph (1) >BETA (8) >Caml (2) >Clean (6) >Dylan (19) < >Erlang (313) >Haskell (48) < >Leda (5) >Lisp (378) < >Logo (46) >Lua (18) >Mercury (4) >Miranda (10) >ML (35) >Mozart (2) >Objective Caml (5) < >Pliant (16) >POP-11 (6) >REBOL (95) >Scheme (127) >Sisal (12) . . . Someone needs to talk with the googlers; REBOL and Dylan are not functional languages. And Lisp ... well, Lisp is universal, so let's let that pass. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From skip at pobox.com Wed Sep 17 13:43:38 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Sep 2003 12:43:38 -0500 Subject: replace %(word) in a string In-Reply-To: References: Message-ID: <16232.40266.46765.123060@montanaro.dyndns.org> Fred> Yes, that's a wonderful feature. Recently though, I've wondered a Fred> couple of times : is there an easy way to substitute with both Fred> local AND global variables ?... Sure, search the list archives for something like EvalDict. Basically, you want a class which behaves like a dict, but will search through multiple dictionaries looking for matching keys. Skip From mymail.5.tth at spamgourmet.com Tue Sep 23 13:47:51 2003 From: mymail.5.tth at spamgourmet.com (T.T.H.) Date: 23 Sep 2003 10:47:51 -0700 Subject: questions about a C++ COM object accessed in Python via win32com References: Message-ID: > Alex Martelli Praise you, Alex, that was the most precise answer I could have imagined! Bye, T.T.H. From vze4rx4y at verizon.net Mon Sep 22 14:07:05 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 22 Sep 2003 18:07:05 GMT Subject: Playing with dictionaries References: <10c662fe.0309220907.a84bea5@posting.google.com> Message-ID: [Roberto A. F. De Almeida] > Suppose I have a dictionary containg nested dictionaries. Something > like this: > > >>> pprint.pprint(dataset) > {'casts': {'experimenter': None, > 'location': {'latitude': None, > 'longitude': None}, > 'time': None, > 'xbt': {'depth': None, > 'temperature': None}}, > 'catalog_number': None, > 'z': {'array': {'z': None}, > 'maps': {'lat': None, > 'lon': None}}} > > I want to assign to the values in the dictionary the hierarchy of keys > to it. For example: > > >>> dataset['casts']['experimenter'] = 'casts.experimenter' > >>> dataset['z']['array']['z'] = 'z.array.z' > > Of course I would like to do this automatically, independent of the > structure of the dictionary. Is there an easy way to do it? >>> def f(d): for k, v in d.iteritems(): if v is None: yield k else: for name in f(v): yield k + '.' + name >>> list(f(d)) ['casts.xbt.depth', 'casts.xbt.temperature', 'casts.experimenter', 'casts.location.latitude', 'casts.location.longitude', 'casts.time', 'z.maps.lat', 'z.maps.lon', 'z.array.z', 'catalog_number'] Raymond Hettinger From colarte at telesat.com.co Sun Sep 21 06:07:44 2003 From: colarte at telesat.com.co (Camilo Olarte) Date: Sun, 21 Sep 2003 05:07:44 -0500 Subject: Pmw menubutton enable/disable In-Reply-To: References: Message-ID: <20030921050744.57cbe884.colarte@telesat.com.co> On Fri, 19 Sep 2003 15:20:57 +0200 Markus von Ehr wrote: > is it possible to enable/disable a menubutton? > My code is like this: > menuBar = Pmw.MenuBar(root, hull_relief = 'ridge', hull_borderwidth = 1) > > menuBar.pack(side=TOP, fill = 'x') > menuBar.addmenu('Help', 'help') > menuBar.addmenuitem('Help', 'command', 'Help About', command = > self.About, label = 'About', state=DISABLED) > > > > now my menubutton is disabled. > Anyone knows how to enable it? try this : menuBar.config(state=ENABLED) Camilo Olarte From link0937 at hotmail.com Tue Sep 23 03:49:26 2003 From: link0937 at hotmail.com (Link) Date: Tue, 23 Sep 2003 15:49:26 +0800 Subject: How to load the DLL with PyRun_SimpleString? Message-ID: Hi, Have anyone know how to import the DLL in C program? Actually, I have used the statement 'PyRun_SimpleString' to import .PY, Such as, r = PyRun_SimpleString("import os"); It's be fine. If importing the DLL by this commdand, Such as, r = PyRun_SimpleString("import example"); return the error code -1. Should any advice, let me know whatever you try... Thanks in advance. Link From bellman at lysator.liu.se Thu Sep 11 04:06:22 2003 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 11 Sep 2003 08:06:22 +0000 (UTC) Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <3F5F83B1.48763F85@alcyone.com> <3F5FD6D7.119F04A1@alcyone.com> Message-ID: Erik Max Francis writes: > That isn't what I meant. Look at the following code: > someFunction(thisArgument, thatArgument) > With Python as it stands right now, I know that this call can never > rebind the names thisArgument and thatArgument. It doesn't matter what > someFunction is, it doesn't matter what thisArgument or thatArgument > are. I know it can never happen. > With your proposed change, now whenever I see a function call in code I > don't know whether it's going to rebind names from the caller's side. > It might, it might not. Furthermore, with Python's dynamicism, it might > be hard to tell without running the code (since functions are first > class objects, inspecting the function name may not help). No, you *would* know. The above call would *not* be able to rebind any of thisArgument or thatArgument. In fact, if someFunction() is defined with a ref parameter, the call would *fail*, raising an exception. Just like calling it with the wrong number of parameters would. For someFunction() to be able to rebind, e.g, thisArgument, there are *two* prerequisites: 1. someFunction() must be defined as 'def someFunction(ref a, b)'. 2. the *call* must be 'someFunction(ref x, y)'. *Both* these must be met. If only one of them is met, the call will fail. Here's a sample session of what would happen under Stephen's model: >>> def ref_f(ref x): ... x = 17 ... >>> def norm_f(x): ... x = 23 ... >>> a = 0 >>> ref_f(a) Traceback (most recent call last): File "", line 1, in ? TypeError: ref_f() must have reference parameter >>> print a 0 >>> ref_f(ref a) >>> print a 17 >>> norm_f(a) >>> print a 17 >>> norm_f(ref a) Traceback (most recent call last): File "", line 1, in ? TypeError: norm_f() must not have reference parameter >>> print a 17 (For the record, I do not support Stephen's proposal, nor any other kinds of call-by-reference in Python. For one, I don't think it meshes well with the rest of Python, and moreover, I have yet to encounter a real-world example where this would actually make code more readable - and I have been using Python for eight years now, and Lisp (which has similar call semantics) for a few years before that.) -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "God is real, but Jesus is an integer." ! bellman @ lysator.liu.se ! Make Love -- Nicht Wahr! From afriere at yahoo.co.uk Mon Sep 22 02:24:15 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 21 Sep 2003 23:24:15 -0700 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> Message-ID: <38ec68a6.0309212224.1ca9edeb@posting.google.com> "Martin v. L?wis" wrote in message news:... > The usage of SZ has only been eliminated in the recent change of > the amtliche Rechtschreibung. > And replaced with what? ie. is there now a single capital for SZ? From fuerte at sci.fi Tue Sep 16 15:41:50 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Tue, 16 Sep 2003 22:41:50 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <16231.25317.741455.556170@montanaro.dyndns.org> References: <16231.25317.741455.556170@montanaro.dyndns.org> Message-ID: <3F67677E.9030408@sci.fi> Skip Montanaro wrote: > Harri> Py_None is special because it is shared between all interpreters, it is > Harri> global. Py_None is defined as: > > ... > > > Harri> From the above we see that when Py_None reference count reaches > Harri> zero, a destructor none_dealloc is called. > > ... > > Harri> This makes no sense at all. Why Py_FatalError? It would be better > Harri> to have > > Harri> static void > Harri> none_dealloc(PyObject* ignore) > Harri> { > Harri> } > >Actually, it makes perfect sense. The reference count of Py_None is never >supposed to reach zero. If that happens it's because you have a bug (too >many Py_DECREFs or not enouch Py_INCREFs). Your version of none_dealloc >silently masks the error. > Yes, and there is no error if the reference count of Py_None reaches zero. The Py_None reference count has no meaning. > Harri> so that it is not necessary to call Py_INCREF(Py_None) > Harri> Py_DECREF(Py_None) at all. Guess how many times these are called > Harri> in Python C API? Py_INCREF is called 2001 times and Py_DECREF two > Harri> times. > >You mean how many places does Py_(IN|DE)CREF(Py_None) appear? Note that in >most situations the interpreter itself calls Py_DECREF() for >you. You just can't tell that "" is Py_None using a static >scan of the C source code. > > Harri> By changing the way how Py_None is freed (by doing nothing) > Harri> Python would get simpler and faster. > >I think you are completely missing the point of Python's reference >counting. Py_None is nothing special except for the fact that it is not >allocated on the stack. In fact, if you removed all the INCREFs and >DECREFs I think you'd have to special-case the code which detects negative >reference counts. Py_None's reference count would quickly go negative and >instead of the normal reference counting dance you'd always be calling the >error function which handles negative ref counts. It would always have to >compare its argument object with Py_None to make sure it wasn't complaining >about the now-special Py_None object. > > How can you have negative reference counts? Answer: You can't. Just remove the code that checks for negative reference counts. It is not needed. The code just gets faster again. OK, you could have it in debug builds, and in that case it could also check that the object was in fact allocated on stack. I think that you are completely missing the point of Python's reference counting. :-) The idea is that when the count reaches zero, then the object is deallocated. But if the object was never allocated in the first place, why deallocate it then? That's why having empty none_dealloc is beautiful. I think that PyINCREF(Py_None) is ugly, and at least it is completely unnecessary. Harri From bergeston at yahoo.fr Fri Sep 19 09:02:49 2003 From: bergeston at yahoo.fr (Bertrand Geston) Date: Fri, 19 Sep 2003 15:02:49 +0200 Subject: Retrieve class name of caller In-Reply-To: <6512ed42.0309190035.303ba9f1@posting.google.com> References: <6512ed42.0309190035.303ba9f1@posting.google.com> Message-ID: Koen Van Herck wrote: > For debugging/logging purposes, I have a function > > def Log(msg): > print '%s.%s: %s' % (cls, method, msg) > > I call this function from a class method, and I would like to retrieve > the name of the caller method and its class. I already came up with > > method = sys._getframe(1).f_code.co_name > cls = sys._getframe(1).f_locals['self'].__class__ > > I wonder if there are better ways to retrieve this info. In > particular, my implementation assumes that the instance parameter of > the method is called 'self', which it usually is, of course. > > Regards, > Koen. Take look to the inspect module. Could be what you need (and even more). From daniel.dittmar at sap.com Wed Sep 17 09:43:31 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Wed, 17 Sep 2003 15:43:31 +0200 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <3F632226.2010607@earthlink.net> <5CH9b.81$2k.16@reader1.news.jippii.net> <20030916211148.GD29089@unpythonic.net> <3F67D36B.80709@sci.fi> Message-ID: Jeff Epler wrote: > Keep in mind that probably more than of 99.9% of machines out there > have only one CPU anyway This could very well change in the future and is probably quite different in the server segment. Although if I had 2 CPUs on my desktop, I'd prefer it if a CPU hog blocks only one of them, so Python would be perfect for that scenario. > no-ops, and use fork() to get that 2%* performance increase. Keep in mind that probably more than of machines out there use windows, so fork () is not an option. But the real problem with free threading are the reference counters as they have to be protected from concurrent accesses, which is now done cheaply by relying on the GIL. So my guess is that a free threading Python will be slower, even when no threads are used. Daniel From aahz at pythoncraft.com Sun Sep 7 13:35:23 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2003 13:35:23 -0400 Subject: Question on Standard Types References: Message-ID: In article , hostmaster wrote: > >I'm quite new to Python and I am reading this book called 'Core Python >Programming' by Wesley J. Chun. I think that this is not a new book but >I believe some of the points are still valid. > >There is this part in the book where it says: > >"In Python, standard types are not classes, so creating integers and >strings does not involve instantiation". Actually, this bit *is* definitely out of date; Python 2.2 introduced new-style classes, and all the standard types are now new-style classes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From aahz at pythoncraft.com Thu Sep 4 15:38:46 2003 From: aahz at pythoncraft.com (Aahz) Date: 4 Sep 2003 15:38:46 -0400 Subject: Quickie mail.python.org status References: <727daa7e.0309031140.1af820b2@posting.google.com> Message-ID: In article , Francois Pinard wrote: > >On the other hand, I've read somewhere (on the Symantec site, I think), t= >hat >at least some varieties of the virus will turn themselves off on Septembe= >r >9'th. I do not understand why the bad guys would have programmed such a >deadline within their code, but I still wish this deadline story is true! Actually, the date is Sept 10, and the presumption is that SoBig.G will be released on Sept 11.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From aleax at aleax.it Sat Sep 27 12:04:15 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Sep 2003 16:04:15 GMT Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: <3F71B857.2D1E3268@engcorp.com> <3F720759.34D7BD3E@engcorp.com> <3F720D28.83C3E99@engcorp.com> <3F731B17.61C17B3A@engcorp.com> <3F74A1E7.5040102@web.de> Message-ID: <3yidb.179256$R32.5736957@news2.tin.it> Dominic wrote: > > Well, first of all I agree with you that > a more traditional approach using queues > is better and more predictable. > > And yes on a single CPU machine I was > thinking about stopping all "low priority" > threads. > > This is somehow creaky and fragile but > you don't need a thread per "task" as > in your queue based alternative. Queues don't make you need a thread per task: you can perfectly well have threads from a pool peeling tasks of a queue of tasks -- that's a frequent use, in fact. > So you could have 3000 "tasks" and > one thread e.g. > However every "task" would need to recover > from it's injected exception which > is kind of unpredictable and hard to program. > > I would not use such an architecture ;-) Me neither -- exceptions can arrive at any time, and recovering and restarting a task under such conditions is frighteningly hard. Much easier to have all tasks coded as loops with reasonably frequent checks on e.g. a lock, if you do need to temporarily suspend them all to leave CPU available for an occasional high-priority task -- this way the checks come when the task is in a "reasonable", "restartable" state, implicitly. > Now to the delay: ... > As you can see it takes about 7 seconds until the > exception is injected. Offhand you seem to be testing your console drivers and the C runtime library interface to them, much more than you're testing Python. The test I posted doesn't use the console in such critical junctures -- admittedly it does use time.sleep, one does have to waste time in SOME way without melting the CPU, but that still feels less artificial to me than your console-based minuet. Alex From mpeuser at web.de Thu Sep 4 18:40:29 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 00:40:29 +0200 Subject: quick and smart way for parsing a CSV file? References: <731fc603.0309031242.4e5493ce@posting.google.com> <3F5656CA.519ABADF@easystreet.com> <731fc603.0309041328.4e83f8ab@posting.google.com> Message-ID: "Hank" schrieb im Newsbeitrag news:731fc603.0309041328.4e83f8ab at posting.google.com... > where would i get this csv module from? does it come with python 2.2? > > thanks No of course - read my posting! Kindly Michael P From mando81 at prodigy.net Mon Sep 1 19:41:55 2003 From: mando81 at prodigy.net (ARMANDO PADILLA) Date: Mon, 01 Sep 2003 23:41:55 GMT Subject: printer friendly python tutorial References: Message-ID: <7PQ4b.3799$Eb.2797@newssvr31.news.prodigy.com> Hi, im new to this group, been a member of php group but anyways... I wanted to know if you had a link to the tutorial you found. -- Armando P. Software Engineer. Computer Science/Economics, California State University Los Angeles http://www.armando.ws "winston" wrote in message news:YTb4b.235097$It4.112333 at rwcrnsc51.ops.asp.att.net... > winston wrote: > > does anyone know where i can find a printer friendly version of the > > python tutorial release 2.3? > > > never mind i found it? > > From dkuhlman at rexx.com Thu Sep 11 20:19:50 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 11 Sep 2003 17:19:50 -0700 Subject: Web server with Python References: Message-ID: Thomas Weholt wrote: [snip] > > Twisted is very easy to get a grip on if you stay away from Woven > and use the resource-class yourself. I can produce a very simple > example if you like. I find Twisted to have a very steep learning > curve in some areas and the project do have a feeling being "under > construction", but the developers/mailing-list are very friendly > and helpful and glad for input. The Twisted mailing list has been down for a few days. They're moving. To get Twisted, check: http://www.twistedmatrix.com/ I agree with the positive comments about Twisted. The Twisted documentation seems pretty good and fairly extensive. And, for Web applications, here is a document I've written that might help you to get started: http://www.rexx.com/~dkuhlman/twisted_patterns.html I've checked this document carefully myself, but have not yet been able to get any Twisted experts to review it yet (again, the email list is down temporarily), so "reader beware". Twisted is more than Web apps, by the way. [snip] > MySQL is easy to work with using Python, so yes. My experience > with ZODB has not been good. I had problems compiling earlier > version of it ( probably my fault but still ) and I quickly found > out that I needed SQL to be able to store and retrieve data the > way I wanted. If MySQL is too much for you take a look at SQLite, > it has a python-module and easy to install/distribute and it is a > "real" sql-database, ie. it can understand SQL and feels like a > SQL-database. PostgreSQL also seems to work well with Twisted. See my document (mentioned above) for code examples on using PostgreSQL (or other relational databases, with minor changes) with Twisted. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From jseb at cs.mcgill.ca Tue Sep 23 13:23:59 2003 From: jseb at cs.mcgill.ca (=?ISO-8859-1?Q?Jean-S=E9bastien_Bolduc?=) Date: 23 Sep 2003 10:23:59 -0700 Subject: eval's local arguement ignored? Message-ID: <56e1eff0.0309230923.1215833f@posting.google.com> Hello, I would like to associate a local namespace with a lambda function. To be more specific, here is exactly what I would want: def foo(): a = 1 f = lambda x : a*x return f then if "f1 = foo()", I get a function whose parameter "a" is not in the global scope. But my functions are not to be hard-coded. I naively expected the following to work: def foo(funcstring): a = 1 f = eval(funcstring) return f but "f2 = foo( 'lambda x : a*x' )" won't work: "f2()" will look for "a" in the globals. Looking at the documentation (I did!), I was then certain replacing the evaluation with the following would work: f = eval(funcstring, globals(), locals()) Or, while we're at it, evaluating the whole thing outside of function "foo": f = eval('lambda x : a*x', globals(), {'a' : 1}) Ooops! the new function still looks for "a" in the globals... Although I could not find any documentation about the fact, it seems the "local" argument to "eval" has no effect in the above cases! So for now, I'm doing something like f = eval('lambda x : a*x', {'a' : 1}) but then my function looses access to the globals. I know that only the very first case above gives me a function whose "fun_closure" attribute is not "None". But still I cannot see where I go wrong. Thank you, JSeb From kalike2003 at netscape.net Fri Sep 26 05:11:45 2003 From: kalike2003 at netscape.net (Kali K E) Date: 26 Sep 2003 02:11:45 -0700 Subject: Getting the Directory/Path details References: Message-ID: Peter Otten <__peter__ at web.de> wrote in message news:... > Kali K E wrote: > > > Hi, > > I could not understand how I can do the following things in Python. > > Please help me. > > > > 1. First I have to find the current directory from where the script is > > invoked. > > 2. Next I have to form a directory structure there. If the current > > directory in step 1 is /home/mylogin, then from there I have to build > > a directory structure like > > /home/mylogin/result > > /home/mylogin/tmp/ > > /home/mylogin/..... > > > > There are three things as I look at it. First determing the current > > directory path. Second adding a string to it like /result etc. Third > > creating the new directory. > > Thank you for the help. > > > > Kali > > 1 os.getcwd() > 2 os.path.join() > 3 os.mkdir() or os.makedirs() > > > import os > > subfolders = [ > "result", > "temp", > "something/else", > ] > > folder = os.getcwd() > > for sf in subfolders: > os.makedirs(os.path.join(folder, sf)) > Hi, Thank you very much for the answer. It works fine when used first time. But when the directory already exists I am getting the following traceback message. Traceback (most recent call last): File "temp6.py", line 15, in ? os.makedirs(os.path.join(folder, sf)) File "/usr/lib/python2.2/os.py", line 203, in makedirs mkdir(name, mode) OSError: [Errno 17] File exists: '/hda1/home/kalike/chnages/python/result' How do I take care in such a case? Also can you please let me know where I can search for all these OS or system calls. Is it available as a document some where? Thanks, Kali From rob at cs.brown.edu Mon Sep 29 16:27:33 2003 From: rob at cs.brown.edu (Rob Hunter) Date: Mon, 29 Sep 2003 16:27:33 -0400 Subject: isNumber? check In-Reply-To: <20030929142027.GA6750@nl.linux.org> Message-ID: <5B71DD32-F2BB-11D7-9145-003065F081D2@cs.brown.edu> On Monday, September 29, 2003, at 10:20 AM, Gerrit Holl wrote: > Rob Hunter wrote: >> How do I check if a value is a number in Python? >> >> One way is (x == type(1)) and (x == type(1.2)) and (x == >> type(2387482734274)) and ... >> >> but this seems kludgy. Any better way? > > Why do you want to do so? I am writing an interpreter, and my parser has to decide if an expression is a number or not. > Maybe, it is better in your > case to just run the piece of code using the number, and > if it fails, it fails. > However, if you must, you need to > do type(x) is type(1) and ... etc., or isinstance(x, int) > and isinstance(x, float), etc. > > Gerrit. From holiver at computerbums.com Mon Sep 8 12:44:58 2003 From: holiver at computerbums.com (James F. Lu - Publicity Chair) Date: Mon, 8 Sep 2003 09:44:58 -0700 Subject: Upcoming Symposium - COSST Message-ID: <007601c37642$7f4fc840$220110ac@FLUFFY> ======================================================= Coast Open Source Software Technology (COSST) Symposium by IEEE Computer Society - Orange County Chapter ======================================================= WHAT: Applying Open Source Web Technologies COSST Symposium WHEN: Saturday Oct. 18. 9am-6pm WHERE: Jazz Semiconductor auditorium, Conexant Systems Overview -------- Our technical focus will be on using LAMP and Java open-source technologies. The LAMP acronym is used to describe a typical open-source platform "stack" for web applications: * Linux operating system * Apache web server * MySQL/PostgreSQL databases * Perl/PHP/Python languages The symposium will open with foundation talks providing an overview of open-source software and Linux as an open-source web application platform. A series of application-tier talks will provide insight from the point of view of widely used web application development languages: Perl, PHP, Python, and Java. The final session will be an experience panel, which will provide an opportunity for experience reports from actual development projects to illustrate real-life problems and opportunities of OSS. Target Audience --------------- The target audience for the symposium is professional software engineers and technical management. The audience is expected to have a diverse background involving many operating systems and languages, with experience in software system development for a variety of industrial, military and commercial purposes. Attendees will include experienced professionals who have had little or no exposure with open-source software and are looking for a good introduction. Symposium Goals --------------- The goal of the symposium is to provide participants with a high-level, technically sophisticated overview of major open source software (OSS) technologies for web application development. The symposium will provide information about technology, resources, and supporting tools and processes of the OSS community. The attendee will take away from the symposium a basic understanding of the available technologies, information about how to acquire and learn more about the various packages, and insight that will enable them to make informed decisions about using and deploying specific OSS technology in web applications. The technical sessions will address: * overview - what is it, what does it do, what problems does it solve * key features - description of key features with short examples * application examples - a few simple examples of doing something useful or where/how to apply the technology * applicability - when should you use it? [or when not!] * resources - where to get it, who maintains it, where to find help, documentation, assistance, mailing lists Sessions -------- 9:00 Symposium Welcome 9:10 Introduction to open-source software Walt Scacchi Sr Research Scientist. UCI Institute of Software Research 10:00 Linux and OSS in Enterprise Development Bill Hilf Sr Architect and Linux Technical Leader. IBM 11:00 Web Application Development with Perl Eric Hammond Director of Technology. Rent.com 12:00 Lunch (Included for paid registrants) 1:OO Introduction to PHP and PEAR Jesus Castagnetto Co-author of "Professional PHP Programming" (Wrox Press) 2:00 Python-Powered Web Application Development Chuck Esterbrook Software Consultant and Creator of Webware for Python 3:00 Mid-afternoon break 3:15 Java OSS Web Technologies Dave Ford Java Consultant and Trainer. SmartSoft. 4:15 Experiences in OSS Web Application Development Panel Facilitated by Prakash Malani Principal Software Engineer. eBuilt.com 5:15 Closing Closing remarks and symposium wrapup. Cost and Registration --------------------- Your registration fees will be discounted according to your IEEE and/or Computer Society membership, as shown below: Standard $75 IEEE Member $60 IEEE Student Member $30 Student $45 You may register online at https://www.regonline.com/Checkin.asp?EventId=9769 If you are one of the first 75 paid registrants, you will get a chance to win one of two Oreilly's "Linux Server CD Bookshelf" (retail value: $119.95), or one of many other LAMP related Oreilly reference books. COSST Volunteers will get in free. There may also be T-Shirts. To volunteer, contact Sebastian: seguti at ics.uci.edu or call 1-949-509-9628 Direction --------------------- Conexant Systems-Jazz Semiconductor 4321 Jamboree Road Newport Beach, CA 92660 A map of the area may be found at http://www.jazzsemi.com/docs/jazz-directions.pdf For more information, please visit us at http://cosst.ieee-occs.org or call Toll Free 1-888-548-1969 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mfranklin1 at gatwick.westerngeco.slb.com Tue Sep 30 10:38:58 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 30 Sep 2003 15:38:58 +0100 Subject: [PMW] Rename a notebook's page - how? In-Reply-To: <3f798986@news.swissonline.ch> References: <3f798986@news.swissonline.ch> Message-ID: <1064932738.29477.1.camel@m-franklin> On Tue, 2003-09-30 at 14:49, F. GEIGER wrote: > Hi again, > > I'd like to rename a page of a notebook. Deleting the page and adding a new > one is not really an option, because the page is filled with other controls > already. So I looked into Pmw.Notebook. There are quite a few lists and > dicts which were to be changed and I wasn't successful in the first try. > > However, if nobody has ever done this, I'd have to rebuild the whole page > after deleting/adding. I really hope there's an other way to go. > > Kind regards > Franz GEIGER > > > You need to get hold of the "tab" widget and change it's text. nb = Pmw.NoteBook(root) nb.pack() nb.add("Page1") nb.add("Page2") nb.add("Page3") tab = nb.tab("Page1") tab["text"]= "Martin1" Regards -- Martin Franklin From mitchchapman at earthlink.net Fri Sep 12 10:07:35 2003 From: mitchchapman at earthlink.net (Mitch Chapman) Date: Fri, 12 Sep 2003 14:07:35 GMT Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: References: <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <5.1.1.6.0.20030911130607.02426ec0@telecommunity.com> <5.1.1.6.0.20030911142317.02b88640@telecommunity.com> <5.1.1.6.0.20030911162016.02027750@telecommunity.com> Message-ID: A.M. Kuchling wrote: > On Fri, 12 Sep 2003 07:56:55 +0300, > Harri Pesonen wrote: > On the other hand, considering that the last free threading packages were > for 1.4, and no one has bothered to update them, the community doesn't seem > to find the subject as important as you do. :) > > --amk At IPC8 Greg Wilson, then of the Software Carpentry project, noted that the GIL made it hard to write multi-threaded Python apps which could take advantage of multi-processor systems. He argued that this would limit Python's appeal in some segments of the scientific community. Perhaps those who find the subject important have left the community? Perhaps they've adopted kludgey workarounds? In my company the GIL has meant that some performance problems, which could most easily be addressed by multiple threads sharing access to large collections of Python objects, have been deferred. -- Mitch From edwards at nospam.lcs.mit.edu Tue Sep 30 22:23:37 2003 From: edwards at nospam.lcs.mit.edu (Jonathan Edwards) Date: Wed, 01 Oct 2003 02:23:37 GMT Subject: Python parser that records source ranges In-Reply-To: <3c91a864.0309291243.6fb1196f@posting.google.com> References: <3c91a864.0309291243.6fb1196f@posting.google.com> Message-ID: <3F7A3AA7.9090804@nospam.lcs.mit.edu> So the basic idea is to match up the leaves of the AST with the list of tokens from tokenizer, which do contain location info. I had thought of that, but was hoping there was a more informative parser out there. Thanks. Jonathan logistix at cathoderaymission.net wrote: > Jonathan Edwards wrote in message news:... > >>The parser library module only records source line numbers for tokens. I >>need a parser that records ranges of line and character locations for >>each AST node, so I can map back to the source. Does anyone know of such >>a thing? Thanks >> >>Jonathan > > > You know there's not going to be a one-to-one relationship, right? > Most ast nodes are symbols and aren't going to match to any tokens. > Python asts also use a lot of intermediate nodes to enforce operator > precidence. > > Anyway, I have some rather specialized code in PyXR that syncs tokens > to an ast. You probably won't be able to use it out of the box but it > should give you a good start: > > http://www.cathoderaymission.net/~logistix/PyXR/ > > The source file of particular interest to you would be astToHtml.py: > > http://tinyurl.com/p3cn From jcribbs at twmi.rr.com Thu Sep 4 13:12:34 2003 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Thu, 04 Sep 2003 17:12:34 GMT Subject: ANNOUNCE: KirbyBase 1.5 Message-ID: <6oK5b.650$FJ5.63203@twister.columbus.rr.com> KirbyBase 1.5 is now available at: http://www.netpromi.com/files/KirbyBase-1.5.zip What is KirbyBase? KirbyBase is a simple, pure-Python, plain-text, flat-file database management system that can be used either embedded in your application or in a client/server, multi-user mode. To find out more about KirbyBase, go to: http://www.netpromi.com/kirbybase.html Changes: Well after reading some posts on comp.lang.python about how slow eval can be, I set about eliminating eval from KirbyBase. It resulted in uglier code, but increased performance, enough of a performance increase that I figured I would go ahead and release a new version. Specifically, the changes are: Changed the way queries are handled internally. Instead of doing an eval to do numeric and datetime comparisons, I changed it to do the actual comparison itself. This resulted in a 40% speed increase on large queries that do comparison expressions. Changed how data is passed between the server and the client in client/server mode. I now use cPickle instead of repr and eval. This resulted in an approximately 40% speed increase in client/server operations. An anecdotal example, doing a date range select query against a 78,000 record table returning 23,800 records in the result set. Version 1.4: 13 seconds Version 1.5: 8 seconds Who says Python isn't fast? :) From jordan at krushen.com Wed Sep 17 21:19:37 2003 From: jordan at krushen.com (Jordan Krushen) Date: Thu, 18 Sep 2003 01:19:37 GMT Subject: Module to generate OpenOffice Writer documents References: <1093E8BAEB6AD411997300508BDF0A7C1571ECD0@USHEM204> Message-ID: On Wed, 17 Sep 2003 20:34:41 -0400, python wrote: > What I'd be even more interested in is if it is possible to submit the > xml to OpenOffice, and then use its rendering features to crank out > pretty PDF files, all through scripts. The Python-UNO bridge might do the trick for you. It lets you programatically control OOo apps: http://udk.openoffice.org/python/python-bridge.html J. From aleax at aleax.it Fri Sep 5 12:12:24 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 16:12:24 GMT Subject: class methods vs instance methods (was Re: Why the 'self' argument?) References: Message-ID: vivek at cs.unipune.ernet.in wrote: ... > The first argument in a class method is a reference to that class itself. Yes, that's what defines CLASS methods (as opposed to ordinary, or INSTANCE, methods). But the original poster was not asking about class methods, and you're not giving any examples of them -- I only see instance methods. I suspect a terminology problem -- you may be using the term "class method" in a way that is totally inappropriate to Python, where classes are first-level objects. So -- in Python, you see...: To make a class method you have to call on the classmethod built-in. E.g.: class Example(object): def instmeth(self): print 'Instance method of', self def clasmeth(cls): print 'Class method of', cls clasmeth = classmethod(clasmeth) inst = Example() Now you can call: inst.instmeth() or: inst.clasmeth() Example.clasmeth() (both of these do exactly the same thing), but NOT: Example.instmeth() since an INSTANCE method, differently from a CLASS method, needs to be passed the instance as the first argument, either implicitly (by CALLING it on the instance) or explicitly by passing it when calling the method on the class, as in: Example.instmeth(inst) Alex From CousinStanley at hotmail.com Wed Sep 3 10:58:19 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 3 Sep 2003 07:58:19 -0700 Subject: wxGrid? References: <3f55f478$1@news.comindico.com.au> Message-ID: I was able to run your script by adding two lines ... AND ... deleting ... return True from the __init__ method -- Cousin Stanley Human Being Phoenix, Arizona From eppstein at ics.uci.edu Tue Sep 16 22:59:21 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 16 Sep 2003 19:59:21 -0700 Subject: scoping with lambda in loops References: <7f9e1817.0309161338.20fbdcbc@posting.google.com> Message-ID: In article , "martin z" wrote: > > a = [] > > for index in range(5): > > a.append(lambda index=index: index) > > > > or maybe more concisely > > > > a = [lambda index=index: index for index in range(5)] > > You know how Python is supposed to be executable pseudocode? Well that > stuff is farking ugly. If I handed pseudocode like that into any TA in one > of my classes, I'd be toast. Is there any way to do that in a legible > manner? How about this: def makefunction(x): def thefunction(): return x return thefunction a = map(makefunction, range(5)) The identifiers are still a little uninformative, but it's hard to do better without more information from the original poster... -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From trentm at ActiveState.com Mon Sep 15 14:20:04 2003 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 15 Sep 2003 11:20:04 -0700 Subject: Processes. In-Reply-To: ; from guy.flowers@Machineworks.com on Mon, Sep 15, 2003 at 08:15:49AM -0700 References: Message-ID: <20030915112004.P12129@ActiveState.com> Guy, Basically working with processes in a cross-platform manner is a pain. :) Yes PIDs are more of a Linux/Unix thing. I think they do exist to a degree on Windows but that would only be as part of Windows' weak posix compliance layer. In Windows you generally want to talk about process handles. However, Python's standard process handling stuff doesn't generally expose the handles for started processes. I have a module called process.py that might help do what you want to do. Give it a try: http://starship.python.net/crew/tmick/#process Cheers, Trent [Guy wrote] > Hi > > I've done some projects in python for my work which invole some test > scripts etc. All quite basic stuff, I find python a good language to > work in but have come up against a brick wall. I'm been searching > google for hours about processes pids etc. My problem is as follows > the main problem code can be seen below : > > server = uc_server(HOST_str, PORT_num) > while 1: > asyncore.poll(SERVER_TIMEOUT) > > # Only pops queue when the current item is blank. > if (server.current_queue_item == [0,"","",["",0],["",""]]): > # Pops a queue item if there are any queue items to get. > Temp_Current_Item = MainQueue.Pop() > if (Temp_Current_Item != N): > server.current_queue_item = Temp_Current_Item > > Execute_Command_str = > ServerSupport.CreateCommand(Temp_Current_Item) > > # Only executes if on a win32 platform. > if (sys.platform == "win32")and(Execute_Command_str != N): > output, input = popen2("cmd.exe") > input.write(Execute_Command_str+"\n") > input.write("exit\n") > > while 1: > text = output.readline() > if text: > print text > else: > # Sets the current queue item to blank. > server.current_queue_item = > [0,"","",["",0],["",""]] > break > > What I want to have is a server which is multi platform win32, > unix(lots of differnt sorts and may be mac later but forget mac for > now.) that people can telnet onto leave a job, and then the server > runs the jobs one at a time. > What I have is a server that people can telnet on to leave a job, the > server will execute it and keep executing it until it is done. I > thought that maybe the poll thing would sort this out by switching > from the main body of the script to the server part of the script, but > it didn't. The way that I use popen2 is my fav. way of executing > processes as I can catcher all output. What would be really good if I > could execute commands or scripts by using child processes and > searching for there pids this way I would know whats running on the > box at any one time. > There's loads about pids processes on google but it mainly in unix, I > mainly want it in win32 which there is hardly anything about. > > Please Please Help > > TIA > TTFN > Guy > -- > http://mail.python.org/mailman/listinfo/python-list -- Trent Mick TrentM at ActiveState.com From alanmk at hotmail.com Sun Sep 21 12:41:59 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 21 Sep 2003 17:41:59 +0100 Subject: How to catch socket timeout? References: Message-ID: <3F6DD4D7.AF309B4@hotmail.com> Peter Otten wrote: > socket.timeout is a subclass of socket.error, so the timeout exception > should be caught by the first except clause. > So it seems there is *no* way to catch the error. > I think you should file a bug report. Hmmm. What is wrong with the following code? It seems to do what you need: #======================================================= from urllib2 import urlopen import socket import sys slowurl = "http://127.0.0.1/cgi-bin/longWait.py?wait=10" socket.setdefaulttimeout(1) try: data = urlopen(slowurl) data.read() except socket.error: errno, errstr = sys.exc_info()[:2] if errno == socket.timeout: print "There was a timeout" else: print "There was some other socket error" #========================================================== regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From jrut at spamcop.net Sun Sep 7 08:35:49 2003 From: jrut at spamcop.net (James P. Rutledge) Date: Sun, 7 Sep 2003 06:35:49 -0600 Subject: Comments on Python Redesign Message-ID: <20030907123549.GA1011@mail.earthlink.net> A suggestion for use with any Python webpage redesign would be to consider using an automated webpage checker such as the one at http://validator.w3.org/ That validator does checks on webpages and reports on the pages "conformance to W3C Recommendations and other standards." -Jim Rutledge From bignose-hates-spam at and-benfinney-does-too.id.au Sat Sep 27 21:34:55 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 28 Sep 2003 11:24:55 +0950 Subject: Tutor References: <6kqdb.146$Vb3.97520@news1.news.adelphia.net> Message-ID: On Sun, 28 Sep 2003 00:55:30 GMT, News wrote: > Hello. I've just started learning Python a few weeks ago. I'm using > the free "How to Think Like a Computer Scientist: Learning with > Python". I'm half-way through chapter 5 and I've been stumbling on a > few things. If there are parts of the tutorial that are gibing you problems, please point them out here. That way, you'll get comments that will help you understand them, and we'll be able to determine if the tutorial can be improved to avoid the confusion. -- \ "One seldom discovers a true believer that is worth knowing." | `\ -- Henry L. Mencken | _o__) | Ben Finney From nhodgson at bigpond.net.au Fri Sep 19 06:17:34 2003 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Fri, 19 Sep 2003 10:17:34 GMT Subject: SciTE References: <221d8dbe.0309180716.17d73ae2@posting.google.com> Message-ID: <2JAab.111501$bo1.103684@news-server.bigpond.net.au> Srijit: > I am unable to access http://www.scintilla.org/tags2api.py? It should be readable again. The hosting provider recently 'upgraded' their systems. Neil From syver-en+usenet at online.no Tue Sep 23 05:16:12 2003 From: syver-en+usenet at online.no (Syver Enstad) Date: 23 Sep 2003 11:16:12 +0200 Subject: How to load the DLL with PyRun_SimpleString? References: Message-ID: "Link" writes: > Hi, > > Have anyone know how to import the DLL in C program? > > > Actually, I have used the statement 'PyRun_SimpleString' to import > .PY, > > > Such as, > r = PyRun_SimpleString("import os"); > It's be fine. > > > If importing the DLL by this commdand, > > Such as, > r = PyRun_SimpleString("import example"); > > return the error code -1. Is the .dll named .pyd? Is the .pyd on your sys.path? -- Vennlig hilsen Syver Enstad From mpeuser at web.de Thu Sep 4 14:58:04 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 4 Sep 2003 20:58:04 +0200 Subject: basic language question References: Message-ID: "Stephan Diehl" schrieb im Newsbeitrag news:bj7ots$48j$06$1 at news.t-online.com... > Once in a while, I get bitten by the fact, that mutating list methods such > as 'append' or 'extend' return None instead of the (mutated) list itself. > Is there a compelling reason for that? I googled around, but didn't find > anything about this. There is a very old religious law saying: Thou shalt not cause side effects by a function. There is some wisdom in it but it is easily forgotten with languages which do not differ between functions and routines. Kindly Michael P From usenet at soraia.com Thu Sep 18 04:42:23 2003 From: usenet at soraia.com (Joe Francia) Date: Thu, 18 Sep 2003 08:42:23 GMT Subject: audio module In-Reply-To: <9bP9b.71118$Mb2.2369961@twister.tampabay.rr.com> References: <9bP9b.71118$Mb2.2369961@twister.tampabay.rr.com> Message-ID: Todd Stephens wrote: > Is there such a module containing audio tools? I am looking specifically > for tools to manipulate ogg-vorbis and convert other formats (mp3, wav) to > ogg. > Here are some Ogg Vorbis bindings for Python: http://www.andrewchatham.com/pyogg/ From aleax at aleax.it Mon Sep 29 12:01:38 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 29 Sep 2003 16:01:38 GMT Subject: Prime number module References: Message-ID: Dag wrote: > Is there a python module that includes functions for working with prime > numbers? I mainly need A function that returns the Nth prime number and > that returns how many prime numbers are less than N, but a prime number > tester would also be nice. I'm dealing with numbers in the 10^6-10^8 > range so it would have to fairly efficient gmpy is pretty good for this sort of thing, but the primitives it gives you are quite different -- is_prime to check if a number is prime, and next_prime to get the smallest prime number larger than a given number. You'd have to build your own caching on top of this to avoid repeating computation if you need, e.g., "how many primes are < N" for several different values of N; and I'm not even sure that gmpy's primitives are optimal for this (compared with, for example, some kind of sieving). Anyway, with all of these caveats, here's an example function: import gmpy def primes_upto(N): count = 0 prime = gmpy.mpz(1) while prime < N: prime = prime.next_prime() count += 1 return count and having saved it in pri.py, here's what I measure in terms of time: [alex at lancelot python2.3]$ python timeit.py -s 'import pri' -s 'M=1000*1000' \ > 'pri.primes_upto(M)' 10 loops, best of 3: 2.76e+06 usec per loop [alex at lancelot python2.3]$ python timeit.py -s 'import pri' -s 'M=2*1000*1000' 'pri.primes_upto(M)' 10 loops, best of 3: 4.03e+06 usec per loop i.e., 2.76 seconds for primes up to 1,000,000 -- about 4 seconds for primes up to 2,000,000. (This is on my good old trusty Athlon Linux machine, about 30 months old now and not top-speed even when new -- I'm sure one of today's typical PC's might take 2 or 3 times less than this, of course). If I was to use this kind of computation "in production", I'd pre-compute the counts for some typical N of interest and only generate and count primes in a narrow band, I think; but it's hard to suggest anything without a better idea of your application. Alex From c_edgar2000 at yahoo.com Thu Sep 11 05:56:04 2003 From: c_edgar2000 at yahoo.com (edgar c) Date: Thu, 11 Sep 2003 02:56:04 -0700 (PDT) Subject: how to use .wsdl files? Message-ID: <20030911095604.17512.qmail@web12908.mail.yahoo.com> Hi there, I have a problem that I'll describe bellow and is quite difficult to solve it because I'm new to python. I hope I'll get some answers here that will allow me to perform my task... The idea is that I have to perform some unit tests using python for an application that are using web services. All the available methods are in wsdl files. My question is how could I create python clients that will use the methods from the wsdl files? Thanks in advance! edg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From ngps at netmemetic.com Sat Sep 20 11:03:22 2003 From: ngps at netmemetic.com (Ng Pheng Siong) Date: 20 Sep 2003 15:03:22 GMT Subject: python script as an emergency mailbox cleaner References: Message-ID: According to Phil Weldon : > The other type of e-mail > is a fake notification of undeliverable e-mail. This one is a real bear. > There seem to be hundreds variations in the body content and thousands of > variations in the header. So far I've caught all of these using this procmail recipe: :0 B * ^


(
)*Undeliver /dev/null This scans the body for a string matching the regex in the second line. "*" is a delimiter, not part of the regex. The first several hundred I got had 3
's, then it started coming with 4. Similarly, the fake MS update first said "September 2003 Cumulative Patch", then after several hundred I started to see "July 2003". I just saw one "January 2000". The thing feels like it is mutating in response to filters! > My guess is that the internet will not open on Monday. Civilisation is under attack. -- Ng Pheng Siong http://firewall.rulemaker.net -+- Manage Your Firewall Rulebase Changes http://sandbox.rulemaker.net/ngps -+- Open Source Python Crypto & SSL From losnations at comcast.net Fri Sep 26 19:49:16 2003 From: losnations at comcast.net (Marc) Date: Fri, 26 Sep 2003 18:49:16 -0500 Subject: Listbox: How do I empty the view in the window References: <4378fa6f.0309251330.2162e494@posting.google.com> Message-ID: <4oacnVaKaKYhUumiU-KYvA@comcast.com> Actually I was using the ComboBox but was just asking about the listbox part of it. I was not aware of the .update() function. I had found a workaround by deleting out the entryfield directly, but the update may be a cleaner solution. Thanks, Marc "Michael Peuser" wrote in message news:bl1q2f$mlh$04$1 at news.t-online.com... > > "Marc" schrieb im Newsbeitrag > news:4378fa6f.0309251330.2162e494 at posting.google.com... > > Hi all, > > > > I can't figure this out. I want the ability to delete an item in a > > listbox and leave the window area blank, like it is when the listbox > > is first created and nothing selected. > > > > Right now the following is happening. If I simply delete the item in > > the listbox, that item will stay in the view window until another item > > is selected. Or I can select an item in the listbox as active and then > > view it, but I don't want to do that. > > Widgets are nor always aware whether their displayed view has been modified. > You can force this by: > > widget.update() > > > > > I'm using the listbox to allow a user to either enter or select on > > option. As a result, I need the ability to clear out the window so > > they can type in their own selection. > > > > Can someone tell me how to do this? > > Is this another question? Have you considered to use some MPW widget as > ComboBox? > > Kindly > MichaelP > > From __peter__ at web.de Fri Sep 12 07:06:09 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 Sep 2003 13:06:09 +0200 Subject: Usenet posting wiht python References: Message-ID: Fernando wrote: > Hi, > > How can I send a usenet posting from a python app? > Thanks O:-) See http://www.python.org/doc/current/lib/module-nntplib.html Peter From aahz at pythoncraft.com Mon Sep 29 07:03:21 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Sep 2003 07:03:21 -0400 Subject: extension call backs and the GIL References: Message-ID: In article , Robin Becker wrote: > >I'm trying to better my understanding of multithreading. I believe a >thread that calls an extension must have the GIL. What happens if the >extension then calls back into Python? Can a function or method somehow >'belong' to a different thread? My understanding was that things should >be OK provided the extension code doesn't mess with the GIL (which it >doesn't). You need to reacquire the GIL prior to making the callback. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From max at alcyone.com Mon Sep 29 21:48:46 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 29 Sep 2003 18:48:46 -0700 Subject: error explanation References: <13df83a2.0309291345.32db8a2b@posting.google.com> Message-ID: <3F78E0FE.B4994FE9@alcyone.com> Steve Holden wrote: > Try using raw_input() rather than input() That definitely will not work. That will just result in him trying to preform arithmetic with strings instead of numerics. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ The revolution will not televised \__/ Public Enemy From jepler at unpythonic.net Tue Sep 16 17:53:53 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 16 Sep 2003 16:53:53 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <810fmvcc18e3apgp23mt3dqc7dsdgkm3gj@4ax.com> References: <3F632226.2010607@earthlink.net> <5CH9b.81$2k.16@reader1.news.jippii.net> <810fmvcc18e3apgp23mt3dqc7dsdgkm3gj@4ax.com> Message-ID: <20030916215352.GE29089@unpythonic.net> On Wed, Sep 17, 2003 at 12:31:45AM +0300, Christos TZOTZIOY Georgiou wrote: > On Tue, 16 Sep 2003 20:22:41 +0300, rumours say that Harri Pesonen > might have written: > > [snip description of alternative python multithreading mechanisms > allowing riddance of the GIL] > > >It is more efficient to have one process and several threads, than > >several processes each having one thread. > > Please define 'efficient' as used in your statement. I hear that on Windows, processes are very inefficient compared to threads. However, I have no idea what this actually means. Does Harri? Or is he thinking of something else? Is he thinking of something like the "higher context switching cost in terms of TLB misses"? God help anybody who lets thoughts about TLB misses guide the way he writes Python code! (excepting maybe Tim Peters and anybody writing numpy/numarray) I suspect that on Windows, stuff like pipe/dup2/fork has been turned into a hopelessly complicated mess, rather than something I could "roll my own" Python object-passing system out of inside an hour (using pickle or the like). Another cool thing about the pipe approach is that you can probably distribute the processing over a network with only a little more work... wowee, that's cool. Jeff From dave at boost-consulting.com Tue Sep 2 11:34:58 2003 From: dave at boost-consulting.com (David Abrahams) Date: Tue, 02 Sep 2003 11:34:58 -0400 Subject: Simple question: How to pass a C++ class reference to a callback? References: <17fbc98a.0309020423.11ac7b8d@posting.google.com> Message-ID: "T. Panbru" writes: > Try encapsulating your C++ class reference in a CObject, using: > > PyObject* PyCObject_FromVoidPtr( void* cobj, void (*destr)(void *)) > void* PyCObject_AsVoidPtr( PyObject* self) > > and so forth, to go back and forth between the C++ and Python realms. > > Check out the Python docs at: > > http://www.python.org/doc/2.3/api/cObjects.html > Or use one of the high-level wrapping tools such as Boost.Python (http://www.boost.org/libs/python) which make this stuff much easier and safer. -- Dave Abrahams Boost Consulting www.boost-consulting.com From aicolburn at yahoo.com Wed Sep 17 15:27:59 2003 From: aicolburn at yahoo.com (Alan C.) Date: 17 Sep 2003 12:27:59 -0700 Subject: Python exercises References: <3d19203b.0309162207.153b9922@posting.google.com> Message-ID: <1a3a9ffa.0309171127.63482801@posting.google.com> Bruce Embry's Python web site includes lots of exercises to try: http://bembry.org/tech/python/index.php Have fun! -- Al From hungjunglu at yahoo.com Sat Sep 20 13:55:06 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 20 Sep 2003 10:55:06 -0700 Subject: whitespace References: Message-ID: <8ef9bea6.0309200955.b8c070d@posting.google.com> "RR" wrote in message news:... > Is there an easy way in python to remove whitespace from a string? ' hello world '.replace(' ', '') 'helloworld' Hung Jung From johnagianis at yahoo.com Fri Sep 5 09:07:07 2003 From: johnagianis at yahoo.com (johnagianis) Date: 5 Sep 2003 06:07:07 -0700 Subject: newbie question about dictionnary ? References: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Message-ID: "Sophie All?on" wrote in message news:<3f582f90$0$20952$7a628cd7 at news.club-internet.fr>... > Hi, > > CONTEXT > I do numerical simulation for which I have to process mesh. A mesh is made > of > triangle which are made of points. > I want from this information to create edges and build triangle from edges > rather > than from points. > > PROBLEM > An edge is shared by possibly more than one triangle. > > ALGORITHM > > have a triangle class (made of 3 edges) > have an edge class (made of 2 points and embeding a triangle list (those > connected to the edge) > > for each triangle construct its edges but I have to check if the edge > already exists > > for doing this I thought the dictionary was excellent but the key is a > string while I want it > to be the 2 points forming the edge ? How to do it ? > > Have you a better idea ? > > Thanks > > Guillaume Dictionary keys are not necessarily strings. It can be even class instances!! You can have the following: class edge: def __init__(self,x,y): self.a=x self.b=y def ... .... pointA=(3,1) pointB=(5,2) edgeA=edge(pointA,pointB) triangle={} triangle[edgeA]=something Well i think that a list would be ok. The use of a dictionary is for making a relation (key->value).In this case i dont know what the value could be. John From peter at engcorp.com Thu Sep 18 17:33:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Sep 2003 17:33:41 -0400 Subject: print and trailing white space References: <20030918232501.4f2ab362.max@fr.fm> Message-ID: <3F6A24B5.B26940B3@engcorp.com> Maxime Biais wrote: > > Hello, > > I know how to print a string without the trailing newline with a coma > like : > > print "hello word", > > but this example add a white space after the string :( > > Do you know how to avoid this white space without using write() What's wrong with write() ? Print is merely provided for convenience. When it's not doing what you want, you are supposed to use write(), not come up with weird hacks for print. -Peter From disgracelands at quietblue.co.uk Mon Sep 1 03:08:37 2003 From: disgracelands at quietblue.co.uk (disgracelands) Date: Mon, 1 Sep 2003 08:08:37 +0100 Subject: Accessing class members from C Message-ID: I'm starting to develop an application in Python running the interpreter from C, i've got callbacks and stuff setup (was pretty pleased with that) and i'm starting to get my head around the reference counting but i've hit a snag. I'm creating objects within python then linking them to their C counterparts, what i want to do now is directly access the python class variable objects from C. Basically i have the python class object as a C pointer and i want to access one of the class members, somevar, and even read access would be fine. I'm guessing theres a really easy way to do this but i can't find an example in any of the docs and google turns up pages of unrelated problems. I know that i could write Get() and Set() methods for each member variable but it doesn't seem like a very nice solution. Cheers for any help From max at alcyone.com Fri Sep 19 18:15:03 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 19 Sep 2003 15:15:03 -0700 Subject: [OT] New Play: SPAMELOT References: Message-ID: <3F6B7FE7.445FB3BF@alcyone.com> William Trenker wrote: > I nominate for hero: Spambayes! > > I have never received so many virus-related spam messages as this > latest 'Swen' virus. Even the recent 'Klez' virus didn't come close > on volume of spam messages received. I haven't seen any either, and my spam filters don't use Bayesian methods. The problem with this latest round of worm spam isn't that it's bypassing filters (I just have some reasonably sane filtering rules in my system, certainly nothing customized to this latest worm attack -- I don't even really know which rules are stopping it), it's putting significant loads on mail servers. Unfortunately, running an intensive, per-user customized spam filtering solution like Spambayes _increases_ that load. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Forgiveness is another word for letting go. \__/ Matthew Fox From mailing at rousselot.rg Sat Sep 20 17:27:23 2003 From: mailing at rousselot.rg (Philippe Rousselot) Date: Sat, 20 Sep 2003 23:27:23 +0200 Subject: 2nd iteration of a character Message-ID: Hi, How do I find the second iteration of a character in a string using python this gives me the first one f1 = string.find(line,sub) this the last one f2 = string.rfind(line,sub) but for the nth one ? Thanks in advance Philippe PS : any good book to recommend ? From tjreedy at udel.edu Mon Sep 15 11:12:46 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Sep 2003 11:12:46 -0400 Subject: Advice from Jeff (Was Re: Is there "let binding" in Python?) References: <20030914214340.13608.qmail@web40904.mail.yahoo.com> Message-ID: "Don Bruder" wrote in message news:o0d9b.21665$dk4.674856 at typhoon.sonic.net... > In article , > Jeff Epler wrote: > > Not an answer, but advice: when writing programs in Python, >> write Python programs. > > Gawd, but that's profound! And on several levels... No... I'm serious. > But I'm also smiling. Jeff's advice is perhaps too terse for someone not already familiar with it. Does the following seem more helpful? If you are writing a Python program to either learn Python or accomplish a computing task, you will probably be happier and more successful (in the middle to long run) if you write idiomatic Python rather than 'literal translations' in the style of some other langauge and *its* idioms. The OP is not the first to more or less ask 'how do I literally translate this foreign idiom' (which the poster may not even see as a language-specific idiom) rather than 'how do I accomplish the same function'. This questions usually garner the advice given above. > > If it's your task to translate some Scheme (or any other > > language) into Python as literally as possible, my heart goes out to you. > How miserable do you expect me to be translating from > Python to C/C++ as literally as possible? In respect to the basic data/object model, Python is more similar to Lisp than C++. In respect to syntax, the opposite is true. By default, Python code is generic -- it runs with any object with the needed interface. So, unless a block is explicitly specialized to one type with a preceeding assert or conditional, the literally 'as literal as possible' translation to C++ is to template code. Are you doing this, or specializing the C++ code by declaring variables and function parameters to a particular type? Terry J. Reedy From NO-MAIL at hotmail.com Tue Sep 16 14:43:26 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 18:43:26 GMT Subject: why pass statement? Message-ID: Why is there the pass statement? I think, the expression statement would be enough: class C: None while True: None From bhv1 at psu.edu Thu Sep 11 11:56:28 2003 From: bhv1 at psu.edu (Brian Victor) Date: Thu, 11 Sep 2003 15:56:28 GMT Subject: GET and POST References: Message-ID: franck wrote: > i know how to do a GET. >:) i have this example. > my contact tell my i must do a get AND a post :/ > > GET to fuse param et POST for the others. Without knowing urllib, I would infer from the rest of the code that you'd want to do something like this: getparams['fuseaction'] = '*****' postparams['num_card'] = '*****' getparams = urllib.urlencode(getparams) postparams = urllib.urlencode(postparams) # may not be necessary f = urllib.urlopen("http://bidule.com?%s" % getparams, postparams) -- Brian From mpeuser at web.de Sat Sep 6 06:04:56 2003 From: mpeuser at web.de (Michael Peuser) Date: Sat, 6 Sep 2003 12:04:56 +0200 Subject: Why python??? References: Message-ID: "Alex Martelli" > > >> Moore's Law is working in favour of higher level languages even harder > >> than it's working in favour of free but highly efficient OS's. > > > > There are two aspects: > > (1) More power for same price - this works in favour of 'complex software' > > (2) Same power for less money - this works in favor of 'cheap software' > > And software is developed more cheaply in higher level languages than > in lower level ones. Therefore, both [1] and [2] work in favour of HLL's, > which let you develop more complex software for the same price or the > same software (software of the same functional complexity, but more > often than not somewhat hungrier of hardware resources) faster & cheaper. No one will ever dispute this. The question is however: How much HLL is enough? Why are purely functional languages practically unknown? [Some absulutely convincing remarks and well structured destription of the current situation on the server market by Alex] My original point in answer to Facundu Bastidas' remark was: IF the hardware costs had not dropped down to the same order as (base!) software costs, than Linux would not have had any chance! This is still what I think with my zero knowledege. My other point was that there nothing like that is going on in the software development business. The price of tools is of no significance. It is the (expected increase of productivity) The DoD Ada is the best example I can think of. We have not yet reached the situation, where the vendor includea all the hardware you need when you buy a program. > >> Not necessarily. If common programmers only knew machine language, > >> it would still be cheaper to use any available high-level language, > >> say COBOL, even if you needed to supply training for it (it's not > >> hard to teach COBOL to somebody who knows assembly, anyway -- the > >> reverse is harder). > > I am on your way; maybe they more probably would be trained for some > > "macro language". This is no 'paradigm change'. Most C++ programmers (I > > know what I say!) write C programs. > History proves you are wrong: in practice, COBOL was what took over > the market for business application development, *NOT* macro assembly > as you claim would "more probably" happen. A paradigm change, to be > sure, but it's what DID win historically. By ignoring history, as > you're doing, you may not be doomed to repeat it, but you sure do > handicap grievously your chances to predict the future. Please! I do nor ignore history! I hypothetically predicted something what I know did not happen, but what would have been more plausible. It did not happen because the number of programmers was small at that time. In fact not COBOL took over but RPG, to correct your historical background. > (And no crap about "marketing" being responsible for it, please: in > the '60 the _only_ heavily marketed programming language was IBM's > PL/I... and it lost to not-heavily-marketed COBOL and Fortran, as > its technical complexity was just too high on too many issues, in > terms of both programmer training and productivity, and implementation > complexity and resulting bugginess). Yes. A > Similarly, using Python can lower costs even A> if you factor in training costs (again, teaching Python to good A> Cobol programmers is quite easy -- other higher-level languages may A> not be _quite_ as cheap in these terms, admittedly, but still the A> economics aren't _hugely_ different). In most companies you do not train programmers but (try to) hire experienced staff. > Those practices which do increase productivity do tend to get used > more: OOP, RAD and configuration control are heavily prevalent today, > and XP and test-driven design are making great strides. Yes. > > Python is by no means a "perfect" alternative to - lets say: DOT-NET > > and C# - the advantages are difficult to see for persons in power or - I > > mentiones the tool costs - are of minor relevance. > Python may get in "sneakily" -- because programmers love it or because > a desperate pennypincher has no alternative to saving "minor-relevance" > money as it can't attack the major-relevant budget items anyway -- and > proves itself enough that even "persons in power" (which aren't _always_ > total idiots) see its advantages. See the "Python Success Stories" > for many examples. As the evidence accumulates, Python also starts > getting in non-sneakily, by executive decision rather than by the above > means -- and keeps proving itself. We shall wish that. > And Moore's Law is absolutely crucial to this relentless trend. I see no reason why not C# and .NET will be the winners!? ... > > I should as well like to discuss your aspect of programmer's productivity. > > This is an important factor. However all investigations show that > > programmer's productivity is an unmeasurable quantity. > > Once again, you are totally wrong, and moreover, you are wrong in an > assertion that you choose to express in the broadest, unqualified terms. I was very well aware of what I was saying ;-) > Lutz Prechelt's study, the best-known example of empirical investigation > of programmer productivity, show Python and Perl ruling the roost, and > grinding e.g. Java into the dust. Bu some coincidence I came over that study some months ago (googling for some Python matter). I was impressed by the thouroughness of the study but not of the result. The study concentrated on coding and some string/pattern matching related task There will be different results when doing embedded applications > This only confirms in a specific case > study the well-know results of the Function Point community: the higher > level a language, the least amount of code per FP it needs, the higher > the productivity in all phases of coding and maintenance. Coding is agreed, maintenance is still questionable. > > > .... what the programmer likes to do. If he or she would like to > > program in Python everything would be fine. However most or today's > > programmers like to do what is called "mainstream" (circular reasoning, I > > know) That is a little bit document driven development, some UML charts, > > Visual Studio, something inbetween C and C++, C# and Java, and MS Office. > > As long as those are the skills that employers request, those are the > skills most employees will cultivate, of course. This is one of the problems, thus:. > > This can only change if there is competition. Competition means a Killer > > Application that could be sold for half the price of the nearest > > competitor because the developing costs had been such low! > > > > Do it with Python then and show it to the world ;-) > It's been done more than once, and it's being done again as we speak, > many times over -- again, see the Python Success Stories. Google is > an example that didn't choose to submit all details of its Python > success -- but Norvig, Google's search-quality director, has stated > unambiguously what a crucial role Python has played and still plays > in Google's amazing ongoing success. The Open-Source Applications > Foundation is doing the same with Chandler, a personal information > manager application. It is not clear whether this is just a niche market like e.g. MATLAB. > Once again, it appears that your assertions are based on essentially > zero knowledge about the subjects you're prattling about. Well, it appears so.... Kindly Michael P From bokr at oz.net Mon Sep 1 16:29:11 2003 From: bokr at oz.net (Bengt Richter) Date: 1 Sep 2003 20:29:11 GMT Subject: My script is taking 12 hours+ any suggestions? References: <3f4ff9f8$0$23588$5a62ac22@freenews.iinet.net.au> Message-ID: On Sat, 30 Aug 2003 13:08:24 -0400, Ideasman wrote: >Hi I have a made a script that process normals for a flat shaded 3D mesh's. >It compares every vert with every other vert to look for verts that can >share normals and It takes ages. n*(n-1)/2 can be big. How big is it in your case? Others have suggested using a dict to avoid that kind of search. Take the advice, unless the whole problem is bogus somehow, in which case find that out first. > >I'm not asking anyone to rewrite the script- just have a look for any >stupid errors that might be sucking up time. > Some thoughts: Check your memory usage. If your data set is huge, you could be paging and killing all semblance of performance. Upgrade to 2.3, so you can benefit from its speedups and neato features. Perhaps go back to whoever produced the source data and see if this apparent editing of a text file is really the best way to accomplish your end goal. For more detailed help with the file, post enough of an example and explanation to spec it exactly. There may be ways to avoid stuff you are doing. Further thoughts, if you really have to do what you are doing: Try timing it, so you know where the time is going. (See time, profile, hotshot modules). Don't use eval to convert strings to numeric values (use int(s) or float(s)) Don't re-evaluate expressions (especially complex ones) even twice in a hot loop. Don't evaluate constant (with respect to current loop, not necessarily globally constant) expressions within a loop (hoist them out to outer loops, and break them into subexpressions that can be hoisted out as far as possible. Don't create and store redundant information. Don't index through a list when you can iterate through it. Use enumerate if you need an index in parallel. Don't walk through a sequence to find something if you can use a dict to look it up directly. Don't leave stuff like str(saneFloat(NormX)) in code you expect to go fast. I.e., clean out desperate hacks that you don't really know what they are doing, and fix any problems that reemerge properly ;-) Don't use builtin names like float, str, int, etc. for your own variable or parameter names. It will bite you eventually. If your input text is well formatted, perhaps sorting chunks as text can accomplish some useful grouping. Consider decorate-sort to group things according to some computed feature value. Or use a dict with list values as suggested by others. Look at zip and/or list comprehensions for creating/manipulating sequences. HTH Regards, Bengt Richter From jarrodhroberson at yahoo.com Mon Sep 8 00:41:13 2003 From: jarrodhroberson at yahoo.com (Y2KYZFR1) Date: 7 Sep 2003 21:41:13 -0700 Subject: advice choosing IDE References: Message-ID: Lupe wrote in message news:... > I'm convinced to try Python! > > I've read many posts, and although I recently bought a book on C to start > learning it, I'd like to give Python a good chance. > > What IDE would you recommend for someone who needs easiness of use with a > background of Pascal and VB for MS Office? I've definitely changed to > Linux now and I would like a free IDE either for procedural or object > oriented programming. > > I'd need an easy help on syntax, if possible with examples and a front end > debugger with easy trace, breakpoints and watches. > > Programming is not my profession, just a hobby! > > With all this in mind what would be your recommendation? I've read so many > posts on the subject that I'm confused. For a beginner, I just need one > solution... > > Lupe your best bet is Komodo from ActiveState . . . not free but definately worth the money. The other bet is Visual Python from guess who, ActiveState it add great support for Python to Visual Studio 6 / .Met Last choice would be Visual SlickEdit . . . other than that, Python IDE choices are all just glorified color coded crappy text editors. From jcjouffre at bigfoot.com Fri Sep 19 05:14:55 2003 From: jcjouffre at bigfoot.com (jcj) Date: 19 Sep 2003 02:14:55 -0700 Subject: variable to be transmitted from a CGI script to a module References: <4568052b.0309180125.5fd4919a@posting.google.com> Message-ID: <4568052b.0309190114.75a2d03f@posting.google.com> "M-a-S" wrote in message news:... > Read also the thread "How to pass parameter to a module?" > M-a-S > you're right, the proper solution is : import sys print sys.modules['__main__'].myVariable thanks a lot From jjl at pobox.com Thu Sep 18 08:54:21 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Sep 2003 13:54:21 +0100 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> <3y7ab.1043$Od.78860@twister.tampabay.rr.com> <3f697584$0$10966$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <87n0d26yv6.fsf@pobox.com> "John Dean" writes: > I have to agree with the assertion that theKompany.com very slow to update > the web site, hence the reason why I have sort of taken it upon myself to do > something about it. I work for theKompany.com and no matter how hard I push, > nothing ever seems to get done. They all agree that improvement have to be > made. TheKompany.com will still handle sales but my web site will handle > promotion and marketing - www.rygannon.com [...] We have to give you full marks for honesty, I think. :-) John From tim.hochberg at ieee.org Tue Sep 23 11:44:13 2003 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Tue, 23 Sep 2003 08:44:13 -0700 Subject: Thoughts on PEP284 In-Reply-To: References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: M-a-S wrote: >>>Some more looping thoughts - this time on integer for loops... > > > I guess this should be a matter of optimization. Why don't the Python > compiler recognize 'for in [x]range(,):'? It should be > pretty easy. Microsoft does marvels optimizing loops in C. Why an open > source project like Python can't do it? FWIW, Psyco recognizes this structure and removes the overhead associated with it. -tim From llothar at web.de Sun Sep 7 06:21:25 2003 From: llothar at web.de (Lothar Scholz) Date: 7 Sep 2003 03:21:25 -0700 Subject: Any tools to print source code call hierarchy References: <6ee58e07.0309061534.5f8cf00f@posting.google.com> Message-ID: <6ee58e07.0309070221.61734da4@posting.google.com> Simon Burton wrote in message news:... > hmmm... I think (some) static analysis may be possible. The main > thing to exclude is eval/exec but even then, yes you're right, some > programs would just have to be run to find out what they do. > Whats with code like: if foo: def myfunc(): ... do something else: def myfunc(): ... calling your_func() A Language where the program calling hierarchie depends on runtime calculations is not able to provide good refactoring tools or static flow analysis. This is the huge difference to a language like Smalltalk where we live in an image. And if you say that this is a hack, then you are making a big mistake, look at currently used code and you will find so much uses of this style (or even worse styles) that it seems to be a common paradigm. From bowman at montana.com Sun Sep 28 21:30:27 2003 From: bowman at montana.com (bowman) Date: Sun, 28 Sep 2003 19:30:27 -0600 Subject: Home Environment References: Message-ID: Sperry Russ wrote: > > Warning: HOME environment variable points to > %USERPROFILE% > but the path does not exist. > > What should I do to fix this? Do you hsve a home directory? I don't believe 2000 creates one by default when creating a new user. You could either echo %userprofile% to see where it thinks your home is, and create it, or just create one and set HOME to point to it. From mcherm at mcherm.com Fri Sep 12 07:50:20 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 12 Sep 2003 04:50:20 -0700 Subject: Pass-by-reference : Could a C#-like approach work in Python? Message-ID: <1063367420.3f61b2fc3e56a@mcherm.com> I (Michael Chermside) wrote: > > I started by looking for use cases... where would this proposed > > pass-by-reference actually prove useful? Stephen basically found > > one good use case: > > > > I wish to "transfer ownership" of an object that gets passed > > into a method call, and protect against the caller accidently > > continuing to use the object. [So, we'll use a "ref" parameter and > > set the caller's variable to None.] Duncan Booth replies: > That only works if the caller hasn't assigned that object to any other > variables. If they have, they can still accidentally continue to use the > object. Since you have to trust the caller anyway, why not trust them to > stop using the object? Indeed, his use case is not the strong "provides actual security against misuse", but the MUCH weaker "protects against against one particular (fairly common) caller error which is so simple a mistake it would likely be caught by good unit tests anyhow". Which is part of why all agree that it's such a weak use case. -- Michael Chermside From linuxlists at chargedideas.com Fri Sep 5 10:25:47 2003 From: linuxlists at chargedideas.com (Andres Montiel) Date: 05 Sep 2003 22:25:47 +0800 Subject: [wee bit OT] UML tutorials Message-ID: <1062771947.3200.1.camel@kyutums> Could anyone point me to a UML tutorial for newbies? I couldn't find one that was downloadable (I use dial-up and connecting to the 'net is expensive in our country). Thanks. :) - Andre From a.edmondson at eris.qinetiq.com Wed Sep 24 09:26:07 2003 From: a.edmondson at eris.qinetiq.com (Ed) Date: Wed, 24 Sep 2003 14:26:07 +0100 Subject: newbie script References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> Message-ID: If you're UNIX based: os.system('xyz') will return the exit status of your program xyz. More importantly for you, it will return! So try an (ugly) loop like: import os while 1: os.system('xyz') -Ed ataraxia2500 wrote: > I wanna do a script that launch a programm xyz and relaunch xyz if it > crashes. what kind of module do I need for such a task? -- Andrew Edmondson Senior Analyst QinetiQ Malvern Tel: +44 1684 897433 Mobile: +44 794 1103773 PGP Key: http://search.keyserver.net:11371/pks/lookup?op=get&search=0xCEE814DC PGP Fingerprint: 7B32 4D1E AC4F 29E2 9EAA 9550 1A3D BBA4 CEE8 14DC From adsheehan at eircom.net Thu Sep 25 13:24:03 2003 From: adsheehan at eircom.net (Alan Sheehan) Date: 25 Sep 2003 10:24:03 -0700 Subject: Using Jython with JSPs Message-ID: Hi, I am re-engineering a lot of existing Web JSPs and hoping to have each JSP execute a Python script to specify the page contents i.e. a easy way for end users to modify aspects of the pages without deep Java know-how. I have proven the above by creating an interpreter in each page and simply executing a script file. I have performance concerns with the above and would like to pre-create one or more interpreters in the JVM that can be reused by the JSPs. Is the above possible and how ? I use Apache or Tomcat as the Web Server. Thanks Alan From achalk at XXXmagnacartasoftware.com Wed Sep 24 17:54:34 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Wed, 24 Sep 2003 21:54:34 GMT Subject: CGI Redirect to another page References: <09a3d6364c.tim@worthy.demon.co.uk> <2c60a528.0309240338.1e4dd261@posting.google.com> Message-ID: What is wrong with meta-refresh? "Andrew Clover" wrote in message news:2c60a528.0309240338.1e4dd261 at posting.google.com... > Tim Howarth wrote: > > > print "Location: http://abcxyz/index.html" > > > AFAIUI it simply sends a redirect header. > > Yep; however, if you include a relative URI with no hashpart: > > print 'Location: /index.html' > print > > Then the server should send that page to the browser directly, without > sending a redirect back to the browser. This may be preferable in > some cases. > > (The second print is needed to end the CGI response headers.) > > Full spec here: > > http://hoohoo.ncsa.uiuc.edu/cgi/interface.html > > (Using JavaScript or meta-refresh to do redirects is almost always a > really terrible idea.) > > -- > Andrew Clover > mailto:and at doxdesk.com > http://www.doxdesk.com/ From spam at magnetic-ink.dk Thu Sep 11 18:42:05 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Thu, 11 Sep 2003 22:42:05 +0000 (UTC) Subject: Web server with Python References: Message-ID: <3f60fa3d-a26c0463-9b36-4152-a986-61060ca18017@news.szn.dk> Thomas Weholt wrote: >> - must be able to use Python 2.3 to create dynamic pages > > If you can use anything found on www.zope.org under resource and > like to do everything in a webpage, not doing much programming > yourself, then Zope might be the thing. However, Zope still doesn't run on Python 2.3, does it? // Klaus -- ><> unselfish actions pay back better From sholden at holdenweb.com Tue Sep 16 08:05:15 2003 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 16 Sep 2003 12:05:15 GMT Subject: wanted($): mac and linux python gui coders for porting References: Message-ID: <%%C9b.11601$3Y2.9198@news2.central.cox.net> "Mark Hahn" wrote in message news:EHr9b.36540$n94.18214 at fed1read04... > (I apologize in advance if this is not an appropriate posting) > > I have written a simple windows shareware app, EzPicMailer, in Python 2.3, > wxPython 2.4.1, and PIL 1.1.4 that lets computer novices find photo files, > edit them, and mail them, all in one simple app. Everyone is encouraged to > check out my beta version at http://EzPicMailer.com. > > I wrote it to be cross-platform except for a small amout of windows code to > do the system beep and to find the desktop and home folders. > > Now I need a Mac programmer and a Linux programmer to port to these > environments for me. I'm new to shareware but I'm guessing that paying 10% > of gross license receipts would be fair. I put in close to 200 hours into > the app and I'm assuming that 20 hours to do a decent looking port would be > about right, which gives 10% of the effort. Let me know if I'm off-base > here. > > You will also be responsible for a second line of support for your platform. > In other words you will need to fix problems particular to your platform to > keep your royalty flow. You will not have to talk to customers though. > That is what I mean by second-line. > > If you are interested, please tell me about yourself and point me to some of > your existing work with GUI's. > Mark: I don't think anyone would complain about your post. You might, however, get a better response if you create a SourceForge project and add to the "help wanted" list there. People do scour that list from time to time. You'll also learn a lot about CVS :-) Good luck with your project. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From jjl at pobox.com Fri Sep 26 12:14:45 2003 From: jjl at pobox.com (John J. Lee) Date: 26 Sep 2003 17:14:45 +0100 Subject: Fastest way to get thousands of db records to client in 3 tier? References: <3f71361f$0$97182$edfadb0f@dread12.news.tele.dk> <874qz22jah.fsf@pobox.com> <5mncb.14032$cK5.5101@fe1.columbus.rr.com> Message-ID: <87r823bk7e.fsf@pobox.com> amonroejj at yahoo.com (R. Alan Monroe) writes: > In article <874qz22jah.fsf at pobox.com>, jjl at pobox.com (John J. Lee) wrote: > > >> >Why not let the client ask directly if it is faster? > > >> I thought that defeats the purpose of having 3 tiers. You'd have to > >> update the client if/every time business rules changed. Unless I'm > >[...] > > > >Why? The client asks the client in terms of "business logic", the > ^^^^^^^^^^^^^^^^^^^^^^ > Not sure what you meant to say here? The client asks the server, sorry. > Let's say I want to see all the tickets I worked on in the previous > calendar year. The server can get this from the DB in 1 second. But if > the server has to spend 30, 60 or more seconds getting those results > back to me, the client, the system wouldn't be worth using, in my > opinion. "So don't do that", was the point that somebody was making. Worry about the big issue of what network traffic you'll have and how many round trips, not the small issue of the particular means of transport of that traffic. > I _have_ used systems that returned a subset of matching records to > the client, and found it very uncomfortable. That's why in my system I > want to scratch my own itch, and return all the records. Fair enough. Would have to know more to comment. John From aahz at pythoncraft.com Thu Sep 18 12:29:16 2003 From: aahz at pythoncraft.com (Aahz) Date: 18 Sep 2003 12:29:16 -0400 Subject: Multithreading and locking References: Message-ID: In article , Ivan Voras wrote: > >Is it true what I heard (as a "rumour" of sorts), that in multithreaded >Python programs global variables are already automagically protected by >mutexes? Can someone clarify on that? In addition to Duncan's excellent answer, I'd suggest that if you're using phrases like "global variables", you probably want to learn more about how Python's object model works in addition to learning more about writing good threaded programs. You want to avoid sharing mutable names across threads as much as possible. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From mcherm at mcherm.com Tue Sep 9 12:17:16 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 9 Sep 2003 09:17:16 -0700 Subject: Ternery operator Message-ID: <1063124236.3f5dfd0c1adfc@mcherm.com> > [Michael, shouting] > > NOT TRUE! > > > > NEITHER of your options does short-circuit evaluation. Richie Hindle: > > Er: > > >>> def one(): > print 1 > return 1 > > >>> def two(): > print 2 > return 2 > > >>> (True and [one()] or [two()])[0] > 1 > 1 > >>> (False and [one()] or [two()])[0] > 2 > 2 > >>> [...] > [Not condoning the use of this idiom, just correcting a factual error.] Well, I was shouting to be sure I was heard, because I was pretty sure I was right, and was worried about spreading misinformation. Well, I clearly should have worried a bit harder. You are correct, the idiom ( and [] or [])[0] _does_ indeed short circuit correctly. And now it's ME who's spreading misinformation. Sorry. Of course it's still an ugly idiom. But there's a distinction between ugly-but-works and ugly-and-wrong. -- Michael Chermside From jjl at pobox.com Sun Sep 28 13:03:56 2003 From: jjl at pobox.com (John J. Lee) Date: 28 Sep 2003 18:03:56 +0100 Subject: Access to database other web sites References: <87n0crbi8z.fsf@pobox.com> <87eky2574t.fsf@pobox.com> Message-ID: <87eky0g803.fsf@pobox.com> claird at lairds.com (Cameron Laird) writes: [...John wrote:] > >What I was wondering was where the sales data are going to come from. > . > . > . > That's a typical part. As I understand Jenny, she's going > to look at, say, eBay, and correlate "sales" with "price" > and "marketing" variables. Oh, ebay, I see. I was thinking about non-auction sites. On auction sites, some of the sales data are public, I suppose. John From gh at ghaering.de Thu Sep 18 02:53:37 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 18 Sep 2003 08:53:37 +0200 Subject: Checking if the computer is online In-Reply-To: References: Message-ID: <3F695671.4090109@ghaering.de> Mickel Gr?nroos wrote: > Hi all, > > I have a silly question. Is there are simple way to check if the computer > is connected to the Internet? [...] No. You need to craft a platform-specific solution for this task. On Windows, I'd look into the RAS stuff in the third-party win32all package. -- Gerhard From hat at se-126.se.wtb.tue.nl Fri Sep 12 08:08:06 2003 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Fri, 12 Sep 2003 12:08:06 +0000 (UTC) Subject: Python / C: small runtime difference? References: Message-ID: On Tue, 9 Sep 2003 15:54:41 +0200, Martin Schneider wrote: > Hi, Gerhard, > > thanks for your answer :-) > > Here's my python code: > > for i in range(len(fileList)-1): > for j in range(len(fileList)-i-1): > if fileList[j+1] < fileList[j]: > tmp = fileList[j] > fileList[j] = fileList[j+1] > fileList[j+1] = tmp > > Of course I don't know what Python does here internally. You are modifying lists in-place, which means no copies of the data and no copies of the lists are made, everything is done using pointer copying (and updating reference counts). >> It's best to have an array of pointers to structs. Then in >> your bubble-sort algorithm, only exchange the pointers, don't copy the >> structs themselves. > > Okay - I'll try that :-) That should make a huge difference for anything but the simplest data. Also, using a better sort algorithm should improve performance dramatically (i.e. compare your code versus the builtin sort() function of lists). >> So if you make your C code as >> smart as Python automatically is , your C code should be a hell of >> a lot faster than your Python code :-) > > Maybe :-) I'll let you know. It probably will not become slower :-) Albert -- Unlike popular belief, the .doc format is not an open publically available format. From NO-MAIL at hotmail.com Tue Sep 16 14:35:40 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 18:35:40 GMT Subject: None, False, True Message-ID: <0KI9b.12967$x21.4828@twister.southeast.rr.com> Can anybody explain this: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> None = 3 :1: SyntaxWarning: assignment to None >>> False = 4 >>> True = 5 >>> >>> None, False, True (3, 4, 5) >>> From aahz at pythoncraft.com Mon Sep 29 17:54:16 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Sep 2003 17:54:16 -0400 Subject: A startup puzzle References: Message-ID: In article , Edward K. Ream wrote: > >I've just about convinced myself there is no good, clean solution to the >following puzzle. I wonder if you agree. > >1. My app has a module called leoGlobals that contains often-used global >functions. All of Leo's source files start with: > >from leoGlobals import * > >I don't want to discuss whether this is good style: it is simple and it >works well for me :-) Okay, I won't discuss, I'll just tell you that this is a recipe for giving yourself a headache. Have fun. ("Doctor, it hurts when I do this." "Well, stop doing that, then.") -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From jtlis at pf.NOSPAM.pl Mon Sep 15 16:22:17 2003 From: jtlis at pf.NOSPAM.pl (Tomasz Lisowski) Date: Mon, 15 Sep 2003 22:22:17 +0200 Subject: How to instatiate a class of which the name is only known at runtime? References: Message-ID: Uzytkownik "Peter Otten" <__peter__ at web.de> napisal w wiadomosci news:bjml1l$fd9$00$1 at news.t-online.com... > Marco Herrn wrote: > > > 1. How to do the import? I didn't find a way to give a string to the > > import statement. > > > > 2. How to write such code to instantiate? > > Off topic: This thread like some others is spread over a few toplevel > entries in my newsreader (KNode 0.7.2). Is this a bug? > > Anyway, putting it all together: > > import sys > > def getClass(classname, modulename): > try: > module = sys.modules[modulename] > except KeyError: > module = __import__(modulename) > return getattr(module, classname) Hmm... Why not write it directly: def getClass(classname, modulename): try: module = __import__(modulename) except ImportError: return None else: return getattr(module, classname) I have heard, that the __import__ function is smart enough to check the sys.modules dictionary without actually re-importing the once imported module. Is it true? Regards, Tomasz Lisowski From scribe at linuxht.com Thu Sep 4 00:18:38 2003 From: scribe at linuxht.com (Scribe) Date: Thu, 04 Sep 2003 04:18:38 GMT Subject: strings Message-ID: Hi Somewhat new to Python and would appreciated some help in selecting the best builtins to achieve what I want. I pass a string to a function, it is either empty spaces alpha and digits or a decimal ie. 5,789.88 if it is a decimal I want to return the number without the commer any others return 0. Should be simple or maybe I am. Any help apreciated. From mickel at csc.fi Thu Sep 18 02:16:03 2003 From: mickel at csc.fi (=?ISO-8859-1?Q?Mickel_Gr=F6nroos?=) Date: Thu, 18 Sep 2003 09:16:03 +0300 (EEST) Subject: Checking if the computer is online Message-ID: Hi all, I have a silly question. Is there are simple way to check if the computer is connected to the Internet? It seems this should be a pretty straight-forward thing to do, but as I am totally unfamiliar with sockets and such, I ask for your help before getting my hands dirty. Cheers, Mickel G. -- Mickel Gr?nroos, application specialist, linguistics, Research support, CSC PL 405 (Tekniikantie 15 a D), 02101 Espoo, Finland, phone +358-9-4572237 CSC is the Finnish IT center for science, www.csc.fi From BjornPettersen at fairisaac.com Wed Sep 17 15:48:27 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Wed, 17 Sep 2003 14:48:27 -0500 Subject: "New" style classes Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624CA1@stpmsg00.corp.fairisaac.com> > From: Tobiah [mailto:toby at rcsreg.com] > > I gather that a "new style" class inherits from object. > > Is this to be considered the way to make all classes > from now on? If not, when will I know to inherit from > object? I noticed that it clutters up pydoc output. If you don't know if you need to inherit from object, it's probably not going to make a difference. (There are semantic differences for e.g. metaclasses, descriptors and other things that are rarely used ;-) The only real issue I can remember is that you'll need to use new style classes if you want properties. Eventually, there will only be "new style" classes, but by then inheriting from object might be implicit. In other words... hakuna matata. -- bjorn From dave at pythonapocrypha.com Sat Sep 6 04:36:10 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 6 Sep 2003 02:36:10 -0600 Subject: Why the 'self' argument? In-Reply-To: References: Message-ID: <200309060236.10962.dave@pythonapocrypha.com> On Saturday 06 September 2003 02:17 pm, Terry Reedy wrote: > The main virtue of the inst.meth(*rest) abbreviation, with klass made > implicit, is not just to save typing the klass name but to push > determination of which 'klass' to the runtime inheritance tree, Pardon me if this was mentioned previously, but another benefit is to simplify the process of passing methods or stand-alone functions around - the user of such functions doesn't have to differentiate between the two: class Foo: def OnEvent(self, a, b): print 'Method', a, b def Listener(a, b): print 'Function', a,b def SomeEventGenerator(eventListener): eventListener(5, 6) SomeEventGenerator doesn't care if the callback is actually a method or a function. Both these work just fine: f = Foo() SomeEventGenerator(foo.OnEvent) SomeEventGenerator(Listener) Obviously, if the shorthand inst.meth(*rest) wasn't available there would probably be another way to do the same thing, but "inst.meth" is concise and does what you'd expect. -Dave From halloleo.PLEASE at NOSPAM.gmx.net Mon Sep 1 20:04:06 2003 From: halloleo.PLEASE at NOSPAM.gmx.net (Leo) Date: Tue, 02 Sep 2003 10:04:06 +1000 Subject: just a beep Message-ID: hi there i want python to do a beep. in the docu i found in tkinter the method bell() but the script: import Tkinter Tkinter.bell() gives the error: AttributeError: 'module' object has no attribute 'bell' so how can i make python beep? (maybe even without the tkinter overhead?) cheers, leo From freddycooper01 at yahoo.com Thu Sep 25 19:16:39 2003 From: freddycooper01 at yahoo.com (Freddy) Date: 25 Sep 2003 16:16:39 -0700 Subject: Turning Strings into Functions Message-ID: <46610d4e.0309251516.45a8eb01@posting.google.com> How do you turn a string into a callable function? I'm writing a program which takes user input and then looks up the associated function to run from a shelved dictionary. So, I have a dictionary with entries like this: myDict["Case1"] = {"desc":"This is Case1", "func1": "Handler1", "func2" : "Handler2", "args": "ACCEPT"} Then my program gets the string "Case 1" from the user, and needs to assign func1 and func2 as handlers for certain events. The argument to the handlers are sockets, and I can't know in advance what they will be. I need to assign the handler function before it is called. So I need to turn the string into a function (there IS a function in this module called Handler1() ). I don't think I can use an exec call, because that would require me to build a string with the argument first. Any suggestions? Freddy From newsgroups at jhrothjr.com Fri Sep 5 21:33:26 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 21:33:26 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <3f59014d$0$152$a1866201@newsreader.visi.com> <3f591d28$0$175$a1866201@newsreader.visi.com> Message-ID: "Bengt Richter" wrote in message news:bjbb57$bb2$0 at 216.39.172.122... > On Fri, 5 Sep 2003 20:15:00 -0400, "John Roth" wrote: > [...] > > >If you don't have to write "self" as the first parameter of a method, > >that reduces the complexity. Everything else remains the same. > > > Except for cases where two self-parameters are visible at the same time, > and both are used in an inner scope and must be distinguished by giving > them different names. ISTM you'd have to turn off some dynamic capabilities > of python to make "self" implicit. (An example came up in a past discussion, > some time ago). You could still give them different names. The proposal is to eliminate the need to specify "self" in the method header, not in the code in the method body. That's a different issue, and I don't know of any language that manages to do it consistently. John Roth > > Regards, > Bengt Richter From my at mail.ru Wed Sep 3 08:28:40 2003 From: my at mail.ru (Kerim) Date: Wed, 3 Sep 2003 16:28:40 +0400 Subject: Location of bytecode files (pyc) References: <6f03c4a5.0309021745.3a79d951@posting.google.com> Message-ID: <3f55de7b@shknews01> "Rim" wrote in message news:6f03c4a5.0309021745.3a79d951 at posting.google.com... > Hi, > > How can I control the location of the bytecode files? > > The reason I ask is I want to place the bytecode in a directory > different than source code for backup reasons. Our backup system is > directory based and I only want to have source code backed up, not > object files or pyc files. If you're on Windows say: del /S *.pyc to remove all .pyc's from cwd and below. > > Thanks, > -Rim From daniel.rawson.take!this!out! at asml.nl Thu Sep 18 14:17:39 2003 From: daniel.rawson.take!this!out! at asml.nl (Dan Rawson) Date: Thu, 18 Sep 2003 14:17:39 -0400 Subject: Forcing getopt to process a specific option first?? In-Reply-To: References: Message-ID: <3F69F6C3.50605@asml.nl> Skip Montanaro wrote: > Dan> Is there any way to force getopt to process one option first?? I'd > Dan> like to be able to pass in the name of a configuration file for my > Dan> application, then have the remaining command-line parameters > Dan> over-ride the configuration file if they are present. > > Not that I'm aware of. If the order of the remaining options doesn't > matter, you might try splitting the argument list before the option which > introduces your config file. For example, given this set of command line > args: > > -f bar -o baz -c configfile -o bump -h > > locate the '-c' and use it to split the argument list, then swap the two > pieces: > > >>> s = "-f bar -o baz -c configfile -o bump -h" > >>> args = s.split() > >>> args > ['-f', 'bar', '-o', 'baz', '-c', 'configfile', '-o', 'bump', '-h'] > >>> index = args.index('-c') > >>> index > 4 > >>> args[:index], args[index:] > (['-f', 'bar', '-o', 'baz'], ['-c', 'configfile', '-o', 'bump', '-h']) > >>> args = args[index:] + args[:index] > >>> args > ['-c', 'configfile', '-o', 'bump', '-h', '-f', 'bar', '-o', 'baz'] > > Now pass that list to getopt.getopt(). > > If the order of the remaining arguments does matter, you just split the > argument list into three pieces, the part before rearranging: > > >>> args[:index], args[index:index+2], args[index+2:] > (['-f', 'bar', '-o', 'baz'], ['-c', 'configfile'], ['-o', 'bump', '-h']) > >>> args = args[index:index+2] + args[:index] + args[index+2:] > >>> args > ['-c', 'configfile', '-f', 'bar', '-o', 'baz', '-o', 'bump', '-h'] > > Skip > Thanks! Either this solution or the one Peter Otten proposed will work . . . Wow, two good solutions in an hour . . . . Dan From etiennelabuschagne at hotmail.com Tue Sep 9 03:35:37 2003 From: etiennelabuschagne at hotmail.com (Etienne Labuschagne) Date: 9 Sep 2003 00:35:37 -0700 Subject: My future Python IDE article References: Message-ID: 1st, 2nd and 3rd Boa Constructor I find this quite stable on Windows (latest version 0.2.3) and I find the following it's best features: o THE BEST Zope support for a free IDE - create Zope objects such as Files, DTML Documents, Page Templates, etc. Debug Zope Python Scripts, external methods, Zope itself, and to a limited extent, DTML documents and Page Templates! o Out of process debugger that can attach to remote Python processes and debug Zope (THE best feature!), in multiple threads! Debugger can be a bit tempremental, but it's very powerful (I have debugged client's systems over the internet!) o Multiple transports - edit files on the file system, through FTP, Webdav, etc. o Nice editor, with tabbed view of all open files, full Regular expression search and replace functionality (over multiple files), reindetation function, code and parameter completion, code highliting and hyperlink-like "jump to declaration". Lots of other things not mentioned here. o wxPython GUI development (code generation, no XML) There are some niggles, but personally I have found it quite stable and VERY feature rich and probably the most feature rich environment for Python and Zope. (I'm beginning to sound like a Zealot) 4th. PythonWin A nice "side kick" to Boa for the very few things it does better than Boa, has a nifty "Post mortem" debugger that breaks execution on an exception (and rolls back to just before the exception). From tdelaney at avaya.com Mon Sep 8 18:45:23 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 9 Sep 2003 08:45:23 +1000 Subject: Ternary operator Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEAD4CEA@au3010avexu1.global.avaya.com> > From: Paul Moore [mailto:pf_moore at yahoo.co.uk] > > My feeling is that there is a majority who want a ternary operation > (not including me, but what the heck) but that there is violent > disagreement on the syntax. I would disagree with this. My reading of the discussion, voting, etc was that the majority would not *oppose* a ternary operator, if a reasonable syntax could be agreed on. Most people also seemed to agree that a major advantage of having a definite syntax was that it would shut up the constant questions about it (note: *a* major advantage - not *the*). The definition of "reasonable syntax" was what destroyed this. FWIW, I definitely fall in the "would not oppose" group, and not the "actively want" group. I prefer not to use a ternary operator in any language. My bias may well be affecting my understanding. Tim Delaney From jjl at pobox.com Sun Sep 7 09:05:01 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Sep 2003 14:05:01 +0100 Subject: Why python??? References: <87fzjalogu.fsf@pobox.com> <87vfs6unsx.fsf@pobox.com> <87n0dhpm1t.fsf@pobox.com> Message-ID: <8765k44uma.fsf@pobox.com> "Michael Peuser" writes: > Hi John, > "John J. Lee" [...] > These "users" need help, and I think they will get it from Python better > than from most other sources. However someone has to make these tools, > operating systems, embedded systems. This is a different task: it's Software > Engineering. This is just an arbitrary. In this popular view point, if you use an interpreter, you're suddenly not programming any more, but merely "scripting". Applications programming, apparently, is on the same level. So, Bernhard Herzog, for example (sketch.sf.net) isn't a "real programmer", and nor are the OSAF with their Chandler project. Oookay. [...] > This is no longer the argument for "glue language". As to general > application programming languages Python has its pros and cons and has to be > compared to Java, C#, C++ and even maybe VisualBasic. And my just personal > opinion is that I doubt that Python will "take over". Michael, TBH, that paragraph appears to be entirely lacking in any content -- at least, any I can understand. I'm afraid I've reached the same conclusion as Alex -- you're really not trying, so I find I've lost enthusiasm to reply any more to your posts. [...] > > And you got out of bed in the morning three hours before you went to > > sleep, I know ;-) > > The situation was more complicated. Computer time was not free and during > the normal work time there was not much chance to get a lot of CPU cycles. > So we started to work when other people left off (between 6 and 7) I still > today have my difficulties getting up early ;-) :-) John From pweldon at mindspring.com Fri Sep 19 23:44:18 2003 From: pweldon at mindspring.com (Phil Weldon) Date: Sat, 20 Sep 2003 03:44:18 GMT Subject: Factorials References: <3ee1e6f1@shknews01> Message-ID: You could just use a look-up table; it'd be a lot faster than calculation. After all, how many factorials could you possible use? Seventy? Phil Weldon, pweldon at mindspring.com "Rogue9" wrote in message news:3ee1e6f1 at shknews01... > Pardon me but could anyone enlighten me if python2.2 has a math function > to call to do factorials of integers?If not then is there a code snippet > for doing such a thing available?I tried to write some code for this > myself but with little success. > Thanks > Lol From godoy at metalab.unc.edu Tue Sep 30 12:01:46 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 30 Sep 2003 13:01:46 -0300 Subject: Threading and Windows. References: <6ojo41-424.ln1@beastie.ix.netcom.com> Message-ID: Dennis Lee Bieber writes: > Jorge Godoy fed this fish to the penguins on Tuesday 30 September 2003 > 04:08 am: > >> >> I thought the same thing and even thought I was using os.spawnv() in a >> wrong way. Even with the 'P_NOWAIT' flag it still hangs. >> > I may have found the problem (surprised the experts didn't catch it). > > From your initial post: > os.spawnv('P_NOWAIT', 'another.py', ['another.py', parameters]) > > You specified P_NOWAIT as a STRING. It should be a constant /in/ the os > module. The most interesting thing is that I get an error in Windows but I don't get such an error in Linux. This is the output on an interactive session running on Linux: >>> import os >>> os.spawnv(os.P_NOWAIT, 'ls', ['ls', '*.py']) 790 >>> os.spawnv('os.P_NOWAIT', 'ls', ['ls', '*.py']) 127 >>> os.spawnv('P_NOWAIT', 'ls', ['ls', '*.py']) 127 >>> os.spawnv(os.P_WAIT, 'ls', ['ls', '*.py']) 127 >>> os.spawnv(os.P_NOWAIT, 'ls', ['ls', '*.py']) 795 >>> Now, on the Windows box: >>> import os >>> os.spawnv(os.P_NOWAIT, 'c:/python22/python.exe', ['c:/python22/python.exe']) 112 >>> os.spawnv('P_NOWAIT', 'c:/python22/python.exe', ['c:/python22/python.exe']) Traceback (most recent call last): File "", line 1, in ? os.spawnv('P_NOWAIT', 'c:/python22/python.exe', ['c:/python22/python.exe']) TypeError: an integer is required >>> And this is how I found out where was the problem. > Note the use of os.P_NOWAIT rather than your 'P_NOWAIT' It indeed work. I'll replace the '1's with it on the code. > If you want portability, this may be the way to go -- I just changed > the spawnv() call above from "./t1.py" to "python t1.py" and it still > ran on Linux. I'd presume it would also run on Windows (I'm not going > to reboot just to prove that) Just if it is in the PATH, I suppose. I don't believe Windows scans through all directories if it can't find the executable. > NO THREADS NEEDED. :-) Solving the problem with os.P_NOWAIT is better than using threads. ;-) The problem was my misinterpretation of the docs (or maybe they don't make it explicit that I must use the 'os.' prefix...): ---------------------------------------------------------------------- Help on function spawnv: spawnv(mode, file, args) spawnv(mode, file, args) -> integer Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. ---------------------------------------------------------------------- Thanks, -- Godoy. From robin at jessikat.fsnet.co.uk Mon Sep 29 10:05:33 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 29 Sep 2003 15:05:33 +0100 Subject: extension call backs and the GIL References: <6q4qyvep55.fsf@salmakis.intevation.de> Message-ID: In article <6q4qyvep55.fsf at salmakis.intevation.de>, Bernhard Herzog writes >Robin Becker writes: > >>>You need to reacquire the GIL prior to making the callback. >> So does calling an extension release the GIL? > >No. It would be very inconvenient if it did because what most functions >do first is to call one of the PyArg_ParseTuple functions which could >execute arbitrary python code. Thank goodness for that :) > >I think it would help if you described a bit more what the actual >problem is or what the user does. > >I looked briefly at the sources and assuming tha the accelerator in >question is lib/_rl_accel.c and the callback whatever has been assigned >to _SWRecover, could it be that the problem is that your user tries to >use different callbacks in different threads? _SWRecover is a global >after all and shared by all threads. I'm not certain, but yes I think that's probably what the problem comes down to; if so I can claim there are already too many breakages in our font system to worry about that :( > > Bernhard > -- Robin Becker From gh at ghaering.de Thu Sep 4 17:55:36 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Sep 2003 23:55:36 +0200 Subject: Using python RPM on SuSE 8.1 : No libpython.a or libpython.so present. Why? In-Reply-To: References: Message-ID: <3F57B4D8.6010103@ghaering.de> Douglass Turner wrote: > Hello, > > I'm trying to install a statistics package called RSPython that > requires a python shared library to be present on my SuSE 8.1 linux > box. My python is provide as an RPM package and as far as I can tell > there is no libpython.a or libpython.so. What gives? > > How do I get these libraries on my machine? Python is split in several RPM packages in most Linux distributions. The one that will contain the files you need is the development package, commonly called python-devel, python-dev or the like. So just install that package via YaST2. -- Gerhard From duncan at NOSPAMrcp.co.uk Fri Sep 26 04:53:10 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 26 Sep 2003 08:53:10 +0000 (UTC) Subject: Another Python rookie trying to port to C/C++ question. References: <79t6nvceo80m6cumskpqdmipa921da054o@4ax.com> Message-ID: Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in news:79t6nvceo80m6cumskpqdmipa921da054o at 4ax.com: > On Thu, 25 Sep 2003 15:19:00 -0700, Brian Quinlan > wrote: > >>> Well, since I'm not worried about "flexible", have my doubts about the >>> "much slower" part, >> >>Your implementation is O(n) with the number of entries while the Python >>implementation is O(log(n)). If n is small then your implementation >>might be acceptably fast. Can't you just use the STL hash_map template >>class? > > Are you sure Python dictionaries are O(log n)? - Remember, they are > based on hashing. > > Simple hashing is O(1). Handling of collisions and stuff will affect > that (and I'm no expert on hashing techniques) but I can't help > wondering if you're confusing Pythons hashing with tree-based > techniques. > Python dictionaries are effectively O(1). Dictionaries are never more than 2/3rds full, so on average a dictionary lookup only needs a couple of probes. Python's collision resolution is designed such that in most cases lookups that collide on the first attempt will diverge for the next attempt. As some of the other posters have said dictionaries in Python have been tuned over many years, and since the whole of Python is based on fast dictionary lookups it is very unlikely that the OP will get close to the same efficiency. That may not matter though as Python dictionaries are tuned for general use, so a specific application might be able to do better by losing some of the generality. Some of the tuning extends beyond dictionaries, for example strings are commonly used as dictionary keys, and Python avoids recalculating hash values more than once for each string. It is unlikely that a C or C++ programmer would go to the effort of using a string type that cached hash values throughout their application, so for many uses, string lookups in dictionaries will almost certainly be slower (although there could be gains elsewhere). -- 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 uwe.schmitt at procoders.net Mon Sep 15 05:51:23 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 15 Sep 2003 09:51:23 GMT Subject: Is there a web templating system like ruby's amrita ? References: <6ee58e07.0309120421.622cb55@posting.google.com> Message-ID: Lothar Scholz wrote: > I there anything that completely avoid the use of python code inside > a template. I like the Amrita system because it allows me to design > the templates with WYSIWYG editors and blind text. The TAL templates from ZOPE might be a solution. A standalone solution without ZOPE is at http://www.procoders.net/pythonstuff Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt http://www.procoders.net schmitt at procoders.net "A service to open source is a service to mankind." From jjl at pobox.com Mon Sep 8 08:34:44 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Sep 2003 13:34:44 +0100 Subject: "Python Redesign" (fwd) References: Message-ID: <87fzj7cvbv.fsf@pobox.com> mertz at gnosis.cx (David Mertz) writes: > wrote: > |2) as an image created in fireworks, I expected line spacing to honor > |html spacing. It doesn't however so I've fixed it. > > I don't know what 'fireworks' is, I suppose it must be some kind of design > application. But I figured the image was a screenshot of a rendered > page... if not, it indeed might appear a bit different as rendered in an > actual browser. > > |1) it's an image > > You keep writing this; not just to me, but on c.l.py too. I can't quite > figure out what relevance you perceive this fact to have. I guess because people, seeing the .html file extension in the URL, assumed that resizing fonts and sensible scaling to your browser window should work (obviously, the .html extension is rather misleading). In fact, you were one of those people, David, IIRC -- wondering why the mockup only filled a little box inside your browser window. Quite a reasonable question for people to ask, but no need to get grumpy about it when he answers it. > |2) images don't have font tags > > Nope... but screenshot images can be made of browsers displaying pages > with font tags. I was guessing in the negative that your page was > produced (indirectly) from such an HTML document; but perhaps no HTML was > ever involved. It seems fairly clear by now that the purpose of the mockup was to give a quick feeling of the visual design (and people's violent reactions to the 'corporateness' of it and to the colour scheme show is was successful in that). Equally clearly, that isn't going to tell people a lot of other important stuff (no point in repeating those things here). Does that mean the mockup is valueless? Far from it! Visual design is at least somewhat decoupled from HTML now, thanks to the not-entirely-broken CSS implementations in many (most?) deployed browsers. He implies that it's simpler for him to set up the visual design in some non-HTML app -- fine: he, as the artist, knows best which media he can work most quickly in. If using such an app enables the design in its current form to be quickly eliminated (quite possibly by evolution to a better design, rather than dropping it entirely), he has successfully sped up the design process. In other words, it's a prototype! I think you've already made your points about the design and the choice of an image in the mockup rather than HTML quite clearly. No need to repeat any of that. > |3) haven't got a clue what you mean about it fairing badly with css > |dropped and fonts and colours changed. Name me a site that would. [...] > Your demo looks a lot like one of those types of sites. It's hard to be > sure exactly how it might render if no HTML was ever involved in the > design though. I think it's pointless to guess this on the basis of an image mockup, unless you have a very detailed knowledge of CSS and all the relevant browser bugs (and maybe not even then). You're right about the lack of HTML, but I'm right that that's a perfectly valid thing to do. > |2) The site has to reflect the expectations of commercial customers who > |are used to the likes of peoplesoft and atg, etc. > > I suppose. I'm probably not a "commercial customer", whatever that is... > on the other hand, I *am* probably the most widely read writer on Python > topics, worldwide (a lot more people read free developerWorks articles > than buy books; although a good number bought my book too). I suppose So, as you say, we're *definitely* not trying to sell Python to *you*, David. Seriously, I think there's no intrinsic reason why a glitzy commerce-friendly page should reduce the usability of python.org to developers. By all means let's point out conflicts and complain if they don't get fixed, but let's not complain about the whole idea of a glitzier site just because there's a correlation between glitziness and unusability on *other* sites. > |3) it's an image. Images don't stretch. If I make it any bigger it would > |not fit in 800 wide browsers. > > Then it should BE an image, not an HTML page that creates framing elements > but embeds an image in the middle in a way that hides what's an image and > what's HTML. If you had taken that more sensible approach, no one on > c.l.py would have missed that fact they were looking at an image. True. > I reckon you'd be a lot better off taking the near unanimous criticism of > your design seriously than you will be indignantly protesting about the I don't think it has been anywhere near unanimous. John From dialtone#NOSPAM#.despammed at aruba.it Mon Sep 15 17:45:55 2003 From: dialtone#NOSPAM#.despammed at aruba.it (Valentino Volonghi aka Dialtone) Date: Mon, 15 Sep 2003 23:45:55 +0200 Subject: Ways to improve this clock algorithm? References: <33fbf9ec.0309151302.462db544@posting.google.com> Message-ID: <87ekyhd8to.fsf@vercingetorix.caesar.org> jacobsmail at gmx.net (Jacob H) writes: > I am grateful for any suggestions and advice. :) import time class ExampleTimer(object): def __init__(self): print "This is my super clock" self.run() def run(self): while 1: self.update_time() print "%s hrs %s min %s sec" % (self.hours, self.mins, self.secs) time.sleep(1) def update_time(self): # I would use time.localtime() to update the time because doing this I am # sure that it is always syncd with my pc time. I think this is the only # improvement :). It also removes the need for all that math. self.secs = time.localtime()[5] self.mins = time.localtime()[4] self.hours = time.localtime()[3] app = ExampleTimer() app.run() -- Valentino Volonghi, Regia SpA, Milan Linux User #310274, Debian Sid Proud User From alanmk at hotmail.com Fri Sep 12 06:25:47 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 12 Sep 2003 11:25:47 +0100 Subject: Newbie-question: Fetching web-address from the browser! References: Message-ID: <3F619F2B.48953DB9@hotmail.com> dermoon wrote: > I want to fetch the address from the web-browser when it > visits a page on my web-server. Hmmm, what exactly do you mean by the "address from the web-browser". Possibilities include (with solutions for CGI scripts) 1. The IP address of the remote machine, i.e. the numerical address of computer on which the browser is running? If yes, try the "REMOTE_ADDR" environment variable, like so import cgi, os remote_addr = os.environ['REMOTE_ADDR'] 2. The name of the remote machine on which the browser is running, e.g. 'k109-8.bas1.dbn.dublin.eircom.net'? If yes, do a reverse DNS lookup on the IP address discovered above, like so import cgi, os, socket remote_addr = os.environ['REMOTE_ADDR'] remote_name = socket.gethostbyaddr(remote_addr)[0] 3. The address of the web page that contained a link to your page, i.e. the "HTTP Referer"? If yes, take a look at the "HTTP_REFERER" environment variable, like so import cgi, os referer_url = os.environ['HTTP_REFERER'] Note that not all browsers supply the "referer" header, and some firewalls/proxies drop it, for privacy reasons. Is any of these what you meant? Or did you mean something else? -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From mpeuser at web.de Thu Sep 11 12:42:56 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 11 Sep 2003 18:42:56 +0200 Subject: os.listdir References: Message-ID: "Duncan Booth" [highly interesting details from Duncun] Where did you get all these details - reading Python compiler source code? Because it sounded somehow there *could* be degradings when going up to large dicts, I benchmarked it - no noticable effects (see below). As one can see as well there is not much disadvantage over list accesss... Kindly Michael P from random import randrange,shuffle from time import clock N = 10000 hash={} t0=clock() for i in xrange(N): hash[long(i**2)]=4711 checkKeys=hash.keys() shuffle(checkKeys) print "prepare",N, clock()-t0 t0=clock() for i in checkKeys[:10000]: x=hash[i] print "access from ",N, clock()-t0 hash=None N = 1000000 hash={} t0=clock() for i in xrange(N): hash[long(i**2)]=4711 #this takes some time ;-) checkKeys=hash.keys() shuffle(checkKeys) # this probably too print "prepare",N, clock()-t0 t0=clock() for i in checkKeys[:10000]: x=hash[i] print "access from ",N, clock()-t0 hash=None t0=clock() for i in checkKeys[:10000]: pass print "empty loop", clock()-t0 From michels at linmpi.mpg.de Tue Sep 16 11:01:11 2003 From: michels at linmpi.mpg.de (Helmut Michels) Date: Tue, 16 Sep 2003 17:01:11 +0200 Subject: Dislin compilation References: <3f62eabc$0$12398$3b214f66@usenet.univie.ac.at> Message-ID: <3F6725B7.1E854D44@linmpi.mpg.de> Gaubitzer Erwin wrote: > Hi everybody > > I want to recompile the DISLIN graphics module for Python under Linux, because > I think it is one of the best graphics libraries at present. > The included module was for version 2.0 and I want it for 2.2 or maybe 2.3. > The problem is, that I use the small make_py script which only > calls the gcc compiler > > CC="gcc -fPIC -c -O" > PYTH_INC="/usr/local/include/python2.0" > PYTH_CONF="/usr/local/lib/python2.0/config" > gcc -shared -Wl,-soname,dislinmodule.so -o dislinmodule.so *.o \ > -L$DISLIN -ldislnc > > but I think many variables arent configured, > so a long list of errors follows (I copied the first few lines to > the end) > > I dont have experience with makefiles and so I want to ask what I > have to do in a short way. > You have to edit the file 'make_py' and define the variables PYTH_INC and PYTH_CONF with corresponding directories of your Python version (i.e. PYTH_INC=/"usr/local/include/python2.3" or PYTH_INC="/usr/include/python2.3"). The environment variable DISLIN is used to locate the DISLIN library. You can define it outside of the make_py script with the installation directory of DISLIN (i.e. export DISLIN=/usr/local/dislin). Regards, ------------------- Helmut Michels Max-Planck-Institut fuer Aeronomie Phone: +49 5556 979-334 Max-Planck-Str. 2 Fax : +49 5556 979-240 D-37191 Katlenburg-Lindau Mail : michels at linmpi.mpg.de DISLIN Home Page: http://www.dislin.de From newsgroups at jhrothjr.com Sat Sep 6 14:47:52 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 6 Sep 2003 14:47:52 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> Message-ID: "Harri Pesonen" wrote in message news:Ucp6b.3992$ZB4.3874 at reader1.news.jippii.net... > Jonathan Aquino wrote: > > Two reasons I cringe when I see self as the first parameter of method > > declarations (i.e. "def methodname(self, ...)" (I don't mind self in > > the method body)): > > > > 1) I abhor redundancy. My first impression on seeing self as the first > > parameter of all method declarations is that it seems redundant -- it > > probably isn't technically, but it looks redundant: (self, (self, > > (self, (self, ... > > > > 2) The number of parameters in the method call is one less than the > > number of parameters in the method declaration. I'm annoyed when I see > > this because I want the rules of the language to be obvious (in this > > case, a one-to-one mapping). I would be embarassed to have to explain > > this to a beginning programmer. > > > > (I do like how Python indenting indicates blocks, however) > > I agree, it's not logical. I'm learning Python at the moment, and like > it very much. This "self" thing seems to be the only odd feature, it > feels like the whole class feature was added later. The Quick Python > book says that Python was designed to be object oriented from the ground > up. Is it true? I'm not sure; someone who knows the history back to the beginning would have to say. However, there's a difference between "from the ground up," which is certainly true, and "from the beginning" which may or may not be true. John Roth > > Harri > From eppstein at ics.uci.edu Thu Sep 25 01:13:07 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 24 Sep 2003 22:13:07 -0700 Subject: Pre-PEP: reverse iteration methods References: Message-ID: In article , Lulu of the Lotus-Eaters wrote: > David Eppstein wrote previously: > |It would be quite cumbersome to have to identify simple generators as > |infinite or finite manually, and impossible (halting problem) to do so > |reliably automatically. > > Humans cannot solve the halting problem either, FWIW. Just because a > programmer THINKS an iterator is finite, it don't mean it is! Well, true, but if you are a programmer and don't know whether your program is always going to halt, you probably shouldn't have written it that way. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From joconnor at cybermesa.com Fri Sep 12 12:00:40 2003 From: joconnor at cybermesa.com (Fearless Freep) Date: 12 Sep 2003 09:00:40 -0700 Subject: Overlaying transparent images with PIL References: <7d3dc526.0309111903.2a4a044@posting.google.com> Message-ID: <7d3dc526.0309120800.1beec8@posting.google.com> Geoff Gerrietts wrote in message news:... > Quoting Fearless Freep (joconnor at cybermesa.com): > > > > Anyway. I have a basic image and I need to overlay an image on top of > > it and let some of the basic image show through. Just as an aside the > > images are not of the same size and the top image needs to be pasted > > over the underlying image at an offset from the origin. > > What you want is to convert both your images (or at least the top > one?) to an RGBA image. The RGB are the color codes, and the "A" is > the alpha layer. The alpha layer specifies how opaque each pixel > should be, 0 being transparent and 255 being opaque. > > If you convert the GIF you're using into an RGBA image, this should > work. The problem with GIF is that it's not really 'transparent', the > pixels are actually colored. There's just a special marker in the GIF > file format that allows you to identify one of the colors as > "transparent". > > I believe the PNG file format actually provides a full four-layer > model with variable transparency, but I'm a long way from expert or > even knowledgable in these affairs. I just know what's worked for me > before.... > > Best of luck! What I found out would work is I could create 'transparency mask' of the original image and then fill in the transparent part of the image with a background color that I'm not using in the rest of the image. --------------- colorTable = [255]*256 colorTable[0] = 0 #anything black (0) will be made transparent mask = overlay.point (colorTable, '1') #make the transparency mask #paste the overlay into the base image in the boundingBox using mask as a filter baseimage.paste (overlay, boundingBox, mask) ----------------- Everything with a zero value (black) in the original will be transparent in the final Thanks Take care, Jay O'Connor http://www.cybermesa.com/~joconnor/r4hsoftware - Custom Web And Application Software for small business From ianb at colorstudy.com Wed Sep 24 23:17:44 2003 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 24 Sep 2003 22:17:44 -0500 Subject: send email In-Reply-To: <000a01c38309$52daef50$1603a8c0@pc22> Message-ID: On Wednesday, September 24, 2003, at 09:04 PM, Alberto Vera wrote: > Could you tell me How I can send an email using WIN2000? What do I > need? > Use the smtplib module, and maybe the new email module to create the email message (but you won't need that if you want to create simple email messages). Ian From eppstein at ics.uci.edu Sat Sep 27 03:08:22 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sat, 27 Sep 2003 00:08:22 -0700 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <1NFcb.62896$gV.2762@news2.central.cox.net> Message-ID: In article , "Raymond Hettinger" wrote: > [Raymond] > > > It crashes when applied to an infinite iterator. > > [Steve Holden] > > Hmm. My little brain is having difficulty imagining anything that won't. > > What am I missing? > > The PEP proposes adding a method only to a few objects > that don't have degenerate cases: list, str, unicode, xrange > and possibly tuple. Speaking of which: str, int, etc., used to be functions, but they got changed to be the initializers of types having those names. Why is xrange still a function rather than the initializer of the xrange type? The most visible difference of changing xrange to be the type of the xrange objects would be more information shown in help(xrange), some of which could be useful if we are talking about adding more methods to the xrange objects. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From mleeds at mlp.com Fri Sep 19 12:37:42 2003 From: mleeds at mlp.com (Leeds, Mark) Date: Fri, 19 Sep 2003 12:37:42 -0400 Subject: \r for newline in readlines function Message-ID: I did more investigation into my previous problem and what happens is that my text file has \r for representing a new line instead of a \n. is there a way to tell the readlines function that the symbol for a newline is \r rather than \n ? right now the readlines function reads the\r as another item in the list and just puts everything into one big list because it doesn't find any new line characters. thanks. i'm really stuck because i can't read my data right now. mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From tzot at sil-tec.gr Tue Sep 30 10:23:26 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 17:23:26 +0300 Subject: append special chars with "\" References: <3f793544$0$64721@hades.is.co.za> Message-ID: <8e4jnvgmkcs0v1p8vneln8d12r99s2t49f@4ax.com> On Tue, 30 Sep 2003 07:58:27 GMT, rumours say that Alex Martelli might have written: >charmap = {} >for c in chr: charmap[c] = c+'\\' I believe you meant charmap[c] = '\\' + c ... -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From owen at astro.washington.edu Fri Sep 12 13:57:47 2003 From: owen at astro.washington.edu (Russell E. Owen) Date: Fri, 12 Sep 2003 10:57:47 -0700 Subject: mixing for x in file: and file.readline References: Message-ID: In article , Oren Tirosh wrote: >On Thu, Sep 11, 2003 at 01:54:53PM -0700, Russell E. Owen wrote: >> At one time, mixing for x in file and readline was dangerous. For >> example: >> >> for line in file: >> # read some lines from a file, then break >> nextline = readline() # bad >> >> would not do what a naive user might expect because the file iterator >> buffered data and readline did not read from that buffer. Hence the call >> to readline might unexpectedly skip some lines... (Oren points out that it's still a problem in Python 2.3 and after some interesting and gory detail goes on to say...) >Really fixing it amounts to reimplementing the entire I/O layer of >Python with a different strategy and thoroughly testing on multiple >platforms. > >It's possible to hide the problem in most cases by making read and >readline use the iteration readahead buffer if it's attached to the file >object and stdio if it isn't. I don't think it's a good idea. It will >require some hairy code and and seems susceptible to subtle bugs and >corner cases. I agree that fixing read would probably be too messy to justify. But it seems to me that a simple reimplementation of readline() would work fine: def readline(self): try: return self.next() except StopIteration return "" That's basically the way I ended up working around the problem (but I didn't try to modify any classes). I do see two issues with that fix: - existing code (if any) that mixes readlines and read would be harmed - it may not be efficient enough (even implemented in C) >Another alternative it to make read and readline fail noisily after >iteration starts (unless cleared by seek()) If readlines cannot be fixed, this might be worth doing since I think it's a common thing to want to mix readlines and iteration. If read is the only issue, I suspect adding a warning to the documentation for file method "read" would suffice. I'm wondering where the problem is discussed in the manual. I'm pretty sure I saw it recently, but when I read about file methods I saw nothing about it. -- Russell From see at my.signature.com Tue Sep 16 17:28:52 2003 From: see at my.signature.com (Andrei) Date: Tue, 16 Sep 2003 17:28:52 -0400 Subject: why pass statement? References: Message-ID: <3377992.1063747732@dbforums.com> Originally posted by M-A-S > A good idea! Thanks! > > "John Roth" wrote in message news:vme- > q2go7e7fq62 at news.supernews.com"]news:vmeq2go7e7fq62 at news.supernews.co- > m[/url]... > > You don't actally need Pass. A docstring is sufficient: > > class C: > > "this is a class" > > while True: > > "loop de loop de loop" > > John Roth I find "pass" shows that something could be there, sort of "insert stuff here if you like/need to". A string as such doesn't have that effect. Obviously you could always make up some useless statement instead of pass, but pass just looks more elegant IMO. You probably should use it if you plan on showing your code to others. -- Contact info (decode with rot13): cebwrpg5 at bcrenznvy.pbz Fcnzserr! Cyrnfr qb abg hfr va choyvp zrffntrf. V ernq gur yvfg, ab arrq gb PP. Posted via http://dbforums.com From jdhunter at ace.bsd.uchicago.edu Wed Sep 10 15:40:14 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 10 Sep 2003 14:40:14 -0500 Subject: sort by file/directory In-Reply-To: <9d302332.0309101042.2c0d12c3@posting.google.com> (mzupan@meso.com's message of "10 Sep 2003 11:42:24 -0700") References: <9d302332.0309101042.2c0d12c3@posting.google.com> Message-ID: >>>>> "Mike" == Mike Zupan writes: Mike> I have a list that includes files and directories ie: list = Mike> ['file', 'file2', 'dir1','file3','dir2' ] Mike> I want to sort it so it looks like this Mike> ['dir1', 'dir2', 'file1','file2','file3' ] Mike> I'm just wondering if there is an easy way to do this This is a good example of when you should use the decorate, sort, undecorate (DSU) pattern. When python sorts tuples, it compares first on the first element of the tuple and then on the next element, and then so on. If you create tuples where the first element of dirs compares less than the first element of files, and the second element is just the dir/file name, then you'll get the sort you want. All you have have to do is undecorate, ie, remove the unwanted information from the tuples. Here is the approach import os fnames = ('emacs', '.emacs', 'tex','.tcshrc','diary' ) tmp = [ (not os.path.isdir(fname), fname) for fname in fnames] # decorate tmp.sort() # sort fnamesSorted = [fname for isdir, fname in tmp] # undecorate For more info on DSU, see http://groups.google.com/groups?num=20&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&q=dsu+group%3A*python*&btnG=Google+Search and the Python Cookbook, which has a chapter on sorting mainly devoted to DSU. Mike> list = ['file', 'file2', 'dir1','file3','dir2' ] You may want to avoid the name list because it is a built-in. For example, to convert a string to a list of characters, you would do seq = list('John Hunter') After creating a variable named list, you can no longer do this. Cheers, John Hunter From skip at pobox.com Tue Sep 16 15:27:30 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 16 Sep 2003 14:27:30 -0500 Subject: None, False, True In-Reply-To: <877k48y2sd.fsf@pobox.com> References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> <877k48y2sd.fsf@pobox.com> Message-ID: <16231.25634.297176.548203@montanaro.dyndns.org> John> Dunno why None and not True / False causes a warning, but you can John> turn warnings into errors using the warnings framework, I think. Too much Python code which needs to run on 2.2 or earlier legitimately defines True and False something like so: try: True except NameError: True = (1 == 1) False = not True All that valid code would raise SyntaxWarning if it was enabled for True and False. Note that SyntaxWarning is raised at compilation time, not runtime, so the compiler doesn't know a priori whether the except clause will execute. Skip From amk at amk.ca Sat Sep 20 12:32:51 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 20 Sep 2003 11:32:51 -0500 Subject: Web server with Python References: <6o24mvcmksid33t4s9b8cbsrnctl5n2o6m@4ax.com> Message-ID: On Thu, 18 Sep 2003 21:47:43 +0200, Patrick Useldinger wrote: > now that the Python 2.3 version of Twisted is out. I spend an awful > amount of time to get a dynamic page with Medusa, specifically due to > the fact that there is no documentation except the comments in the code. Note that Quixote includes support for both Medusa and Twisted; see the modules in the quixote.server package. --amk From duduca007 at yahoo.com Thu Sep 4 16:35:13 2003 From: duduca007 at yahoo.com (Carlos Moreira) Date: Thu, 4 Sep 2003 13:35:13 -0700 (PDT) Subject: PYTHONPATH x *.pth??? Message-ID: <20030904203513.82182.qmail@web11406.mail.yahoo.com> I want to install Python third packages in a non-default directory. What?s the better way to do Python to find this packages? - set PYTHONPATH variable? - include *.pth files (that keep directory of installed package) in site-packages? I know that the two methos above are equivalents. But what method will be kept in future Python releases (for example)? []?s Cadu __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From dyoo at hkn.eecs.berkeley.edu Tue Sep 2 14:42:11 2003 From: dyoo at hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 2 Sep 2003 18:42:11 +0000 (UTC) Subject: TKinter is driving me crazy! References: <3285.208.224.10.29.1062445601.squirrel@webmail.iserv.net> Message-ID: Cousin Stanley wrote: : | Frames don't have titles, but toplevels do. : | Try using the 'title()' method of the toplevel widget. : Daniel ... : Thanks for the reply ... : I'm familar with applying the title() method : to a Tkinter root or Toplevel object, but couldn't : figure out how to change the title on a sub-classed frame Hello again! But that's because frames don't have titles. *grin* (If you're coming from a Java background, and are thinking about Java Swing's JFrames, don't! Tkinter's Frame is a grouping widget, and is more like a JPanel than a JFrame.) If we try making a widget without a toplevel container, Tkinter will automagically create a default toplevel master object for us, and use that to subsequently attach widgets. This default behavior is convenient, but can cause the confusion that we're having between frames and toplevels. In fact, it's perfectly ok to have two frames in a toplevel window: ### >>> from Tkinter import * >>> root = Tk() >>> p1 = Frame(root) >>> p2 = Frame(root) >>> Label(p1, text="hello").pack(side=TOP) >>> Label(p1, text="world").pack(side=BOTTOM) >>> Label(p2, text="tkinter").pack(side=TOP) >>> Label(p2, text="programming").pack(side=BOTTOM) >>> p1.pack(side=LEFT) >>> p2.pack(side=RIGHT) ### So in this context, asking for the title of a Frame is a meaningless question: you really want to get at the title of the toplevel object. I guess another way to do the title setting, if all we have is the frame, is to grab the 'master' from our widget, and hope that it's the toplevel: ### from Tkinter import * button = Button(text="Press me!") button.pack() button.master.title("This is a test title") ### Even so, the examples in "An Introduction to Tkinter" don't depend on the default toplevel object --- those examples explicitly create a root toplevel object --- so it's probably a better idea to do the same. ### from Tkinter import * root = Tk() button = Button(root, text="Press me!") button.pack() root.title("This is a test title") ### From ramen at lackingtalent.com Mon Sep 22 14:32:42 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 22 Sep 2003 18:32:42 -0000 Subject: DB2 driver for windows References: <3f6cc89b$0$1122$6c56d894@feed0.news.be.easynet.net> Message-ID: In article <3f6cc89b$0$1122$6c56d894 at feed0.news.be.easynet.net>, Philip wrote: > i'am looking for a db2 driver for windows > the DB2 servers runs on as400 if that makes any difference. I don't know if you're looking for a native driver, but if you can work with ODBC, I was able to get DB2's ODBC driver (the one that comes with the DB2 client installation) to talk to the mx.ODBC module. http://www.egenix.com/files/python/mxODBC.html -- .:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:. : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r : From dave at boost-consulting.com Fri Sep 26 14:51:05 2003 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 26 Sep 2003 14:51:05 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> Message-ID: Alex Martelli writes: > David Abrahams wrote: > ... >> Also, the idea of denying tuples the ability to reverse iterate seems >> arbitrary and capricious. > > Sure, but so is denying them, e.g., non-mutating methods such as > .index() and .count(). Not IMO. Immutability is a very useful trait. > At least we're _consistently_ arbitrary and capricious!-) Not in this case. -- Dave Abrahams Boost Consulting www.boost-consulting.com From robin at jessikat.fsnet.co.uk Sat Sep 20 11:01:11 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 20 Sep 2003 16:01:11 +0100 Subject: pop3 email header classifier? In-Reply-To: <6cammvoibfes7scnan7kkorctoi55n4d57@4ax.com> References: <6cammvoibfes7scnan7kkorctoi55n4d57@4ax.com> Message-ID: <8C7OnKA3uGb$Ew6x@jessikat.fsnet.co.uk> In message <6cammvoibfes7scnan7kkorctoi55n4d57 at 4ax.com>, Richie Hindle writes > someone has posted a poplib command line thing on much the same lines in another thread. >[Robin] >> Hi, I'm getting vast numbers of fake upgrade emails containing some kind >> of virus. My rather old client can be made to reject these based on some >> patterns in the subject line. They're nearly all based on the word >> 'New', 'Latest', 'Microsoft', 'Patch', 'Pack', ... etc etc. >> >> Is there a python tool that can be made to delete these from my POP3 >> mail box rather than let my client reject? > >I have a webmail application that can be made to delete messages based on >regular expressions, at http://entrian.com/cgi-bin/pop3.py > >I wrote it in response to a similar problem, whereby a spammer used my >address as his From address, and I received a couple of thousand bounce >messages a day. > >You can set up regular expression filters on To, From and Subject, and set >it to either mark messages for deletion (so you get to review them before >deleting them) or delete them straight away (via the "I'm either brave or >stupid" checkbox, TM 8-) You can save your filters for later use. > >Take EXTREME CARE with this, particularly if you check the "I'm either >brave or stupid" box. 8-) There is no way to recover a deleted message. >Don't sue me if it eats your hamster's emails. > >You probably need something like (untested): > >From: microsoft|ms\b >Subject: patch|latest|microsoft|update|upgrade|pack > >There's no SSL version of this, so your POP3 account details will pass in >plain text over the internet (in theory my provider has a scheme whereby >you can access the site over SSL using their certificate, but it doesn't >work for some reason - if there's any interest I'll see whether I can make >it work). > >(And no, I'm not going to harvest your POP3 account details. They never >even hit the hard drive.) > -- Robin Becker From martin at v.loewis.de Sun Sep 7 15:06:51 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 07 Sep 2003 21:06:51 +0200 Subject: negative indices for sequence types References: Message-ID: danbmil99 at yahoo.com (dan) writes: > This fact is *deeply* buried in the docs, and is not at all intuitive. I find it highly intuitive and very convenient. > If you want this behavior, how hard is it to say a = b[x % > len(b)] ?? *This* I would call un-intuitive. It is also much slower. To get the last element, you currently write b[-1]. If that was not available, you would have to write b[len(b)-1], which is still significantly slower. Also, you might not have a variable name, so try rewriting foo()[-1]. Regards, Martin From duncan at NOSPAMrcp.co.uk Mon Sep 22 10:09:06 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 22 Sep 2003 14:09:06 +0000 (UTC) Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale related?)) References: Message-ID: Alex Martelli wrote in news:DUCbb.100826$hE5.3550910 at news1.tin.it: >> So maybe it's about time to change the sort() method to support a >> second argument >> >> list.sort(compare=None, mapping=None) >> >> that, if provided, would perform the DSU magic. Or was that already >> proposed and rejected? > > I have not seen this proposed before, and I'm not very clear on what > the "compare" and "mapping" arguments are supposed to be in order to > let you specify any DSU. Basically it seems you would need two > callables, "decorate" to be called with each item in the list (to > return for each item the decorated tuple) and "undecorate" to be > called with each decorated tuple after the sort (to return the item > for the result). How do you turn that into "compare" and "mapping"? > > You don't need two callables because the sort function would be doing the decorating, so it knows also how to undecorate. I think the suggestion is that the mapping argument returns something that can be compared. For example, here is a DSU function that does a not-in-place sort and takes a suitable mapping argument. Changing it to in-place sort is, of course, trivial. >>> def DSU(aList, aMapping): newList = [ (aMapping(item), index, item) for (index, item) in enumerate(aList) ] newList.sort() return [ item[2] for item in newList ] >>> print DSU(['Alex Martelli', 'Duncan Booth', 'Peter Otten', 'Jeff Epler'], str.lower) ['Alex Martelli', 'Duncan Booth', 'Jeff Epler', 'Peter Otten'] >>> def lastFirst(name): names = name.split() names = names[-1:] + names[:-1] return [name.lower() for name in names] >>> print DSU(['Alex Martelli', 'Duncan Booth', 'Peter Otten', 'Jeff Epler'], lastFirst) ['Duncan Booth', 'Jeff Epler', 'Alex Martelli', 'Peter Otten'] -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From peter at engcorp.com Fri Sep 26 10:11:43 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 26 Sep 2003 10:11:43 -0400 Subject: Where to import modules? References: <3F74375A.F9D4B0EB@engcorp.com> Message-ID: <3F74491F.593D5D56@engcorp.com> JCM wrote: > > Peter Hansen wrote: > ... > > > Basically doing this is an optimization, and you shouldn't be optimizing > > before the program is working, and you shouldn't be optimizing without > > a real need for it. (That is, just because it's a little faster doesn't > > mean it's worth doing.) > > Aside from being an optimization, it's also good for documentation. > If you see an import at the top of a file it might not be immediately > clear how or why the module is being used. It's similar reasoning to > why you might define variables in the narrowest scope posible. I'm not sure it's necessarily any clearer when you put the import somewhere down in the file, effectively hiding it from casual viewing. At the top, it's at least clear that the module *is* imported. If you care how it's used, a simple search for "module." will show all the places where it's used. In the middle of code somewhere, you can clearly see how it's being used only if you're actually looking at that exact line. John Roth has the right approach: whatever you do, a comment up at the top with the others would go a long way towards appeasing any concerns about maintainability. Unfortunately, that does mean there's isolated duplication (the import, somewhere below, plus the comment at the top) and therefore another, though perhaps lesser, maintainability problem. -Peter From nomail at nomail.com Wed Sep 10 04:02:50 2003 From: nomail at nomail.com (Michael Schmitt) Date: Wed, 10 Sep 2003 10:02:50 +0200 Subject: Errors while compiling SWIG wrappers on Solaris References: Message-ID: Thanks a lot. Compiling svm.o with -fPIC worked. I found it very difficult to get information and a better understanding of the Linking process. Do you have any hints on background information, that helps to be able to debug such errors myself? Regards, Michael "Martin v. L?wis" wrote: > Michael Schmitt wrote: >> I tried some hints I found on the web: >> "-shared" for compiling and linking. >> "-fPIC". >> "-Wl,-G". >> >> But none of these (also in combinations) worked. Any ideas? >> >> Thanks for any help. >> Michael >> >> -------------------- >> Text relocation remains referenced >> against symbol offset in file >> 0x2610 ../svm.o >> 0x2614 ../svm.o > > svm.o is not position-independent. You need to compile *svm.o* > with -fPIC. Passing that option to any other compiler commands, > or the linker line, will be irrelevant. Once you've done that, > you may find that additional object files are not > position-independent, either, you then need to compile these > with -fPIC as well. > > Regards, > Martin From hokiegal99 at hotmail.com Wed Sep 17 20:48:18 2003 From: hokiegal99 at hotmail.com (hokiegal99) Date: Wed, 17 Sep 2003 20:48:18 -0400 Subject: convert ints in a range to strings References: Message-ID: <3F6900D2.7080806@hotmail.com> Thanks Heather... this did it: outputFile = file('ips.txt', 'w') r = range(256) for r in range(256): f = '192.168.1.%s\n' % r #Change this line to macth your network. outputFile.write(f) outputFile.close() Heather Coppersmith wrote: > Try any or all of these: > > print a + b + c + str( r ) > > print a + b + c + "%d" % r > > print a + b + c + "%s" % r > > print "%s%s%s%d" % (a, b, c, r) > > Regards, > Heather > From fgeiger at datec.at Mon Sep 1 15:36:54 2003 From: fgeiger at datec.at (F. GEIGER) Date: Mon, 1 Sep 2003 21:36:54 +0200 Subject: PyXR 0.9.3- Cross-Referenced HTML from Python Source References: Message-ID: <3f539f76@news.swissonline.ch> Cool! Reminds me a bit of doxygen, which I heavily use for my C++ projects. Have a look at it, if you want to add some graphics showing inheritance paths and the like. Cheers Franz "logistix" schrieb im Newsbeitrag news:mailman.1062354602.22785.python-list at python.org... > PyXR 0.9.3- Cross-Referenced HTML from Python Source > > PyXR generates HTML pages from python source files. It also generates > cross-referenced hyperlinks and integrates with the Python Library > Reference as well, which makes it distinctive from the 8 million other > prettyprinters out there. It's been tested on 2.3 for Windows, OpenBSD > 3.2 and RedHat 7.3. There's no reason it shouldn't work on other > platforms with minor configuration. > > 0.9.3 is a minor release. It was primarily issued as an "official" > 2.3-compatible release, although previous versions should run on 2.3 as > well. Other features include: > - Per-line-number hyperlinks, to make emailing source code > references easier and more accurate. > - Upgrade of the PyXR'ed source on my website to 2.3's standard > library. > > A PyXR'ed version of Python 2.3's source can be viewed at: > > http://www.cathoderaymission.net/~logistix/PyXR/python23/src/ > > More information about PyXR itself is available at: > > http://www.cathoderaymission.net/~logistix/python/pyxr.html > > The package is available at: > > http://www.cathoderaymission.net/~logistix/python/PyXR.zip > > Enjoy! > > From colinsm.spam-me-not at picsel.com Mon Sep 8 11:41:05 2003 From: colinsm.spam-me-not at picsel.com (Colin S. Miller) Date: Mon, 08 Sep 2003 16:41:05 +0100 Subject: Read file that starts with '\xff\xfe' In-Reply-To: References: <3F5BD4DD.57D90AF5@alcyone.com> <3F5BFC19.D098115B@alcyone.com> <6.0.0.22.0.20030908054530.03c42dd8@66.28.54.253> <3F5C7270.1020001@ghaering.de> Message-ID: Bob Gailer wrote: > At 07:31 AM 9/8/2003, Duncan Booth wrote: > >> Bob Gailer wrote in >> news:mailman.1063025195.15280.python-list at python.org: >> >> > That's a good start. I presume I need to use codecs.open(filename, >> > mode[, encoding[, errors[, buffering]]]) to read the file. What is the >> > actual value of the "encoding[" parameter for "Little-endian UTF-16 >> > Unicode character data, with CR line terminators" >> >> Try: >> >> myFile = codecs.open(filename, "r", "utf16") >> >> If the file starts with a UTF-16 marker (either little or big endian) it >> will be read correctly. If it doesn't start with either marker reading >> from >> it will throw a UnicodeError. > > > Interesting error: > > UniCodeError: UTF-16 decoding error: truncated data Are you doing readline on the unicode file? I bashed my head off this problem a few months ago, and ended up doing codecs.open(...).read().splitline() I think what happens is the codecs::readline calls the underlying readline code, which doesn't respect unicode, and instead splits at the first \r or \n it finds; in little-endian this will result in a string with an odd-number of bytes. Colin Miller > > Bob Gailer > bgailer at alum.rpi.edu > 303 442 2625 > > > ------------------------------------------------------------------------ > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From bfdpowers at norwoodlight.com Thu Sep 4 19:31:27 2003 From: bfdpowers at norwoodlight.com (Bradford Powers) Date: Thu, 4 Sep 2003 16:31:27 -0700 Subject: Output in color In-Reply-To: <20030904195605.20582.3332.Mailman@mail.python.org> Message-ID: <000001c3733c$a94c5590$6400a8c0@LAPTOP> I'm curious how I can make Python print text in color. From gstaniak at inka.zagiel.pl Thu Sep 11 10:26:06 2003 From: gstaniak at inka.zagiel.pl (Grzegorz Staniak) Date: Thu, 11 Sep 2003 14:26:06 +0000 (UTC) Subject: OT: Americans love their guns References: Message-ID: Arthur writes: >>I think it's a mistake to cite Lott here. As an >extreme libertarian he >>has shown his own bias a couple of times. His >famous "More guns, less >>crime" findings has been challenged recently >>(see e.g. >>http://www.jointogether.org/gv/news/alerts/reader/0,2061,562387,00.html), >>and he could not produce any evidence whatsoever that his telephone >>survey on the crime-repelling effects of gun carrying has been actually >>conducted. > > I have never owned a gun, nor can off-hand think of anyone I know well who > does own a gun. Same here. > So am not excitable on the issue. Neither am I. I've been reading a little on the subject only because pro-gun legislations are being discussed in my country at the moment. Actually, at first I completely bought the "more guns, less crime" argument. Especially the data presented for Texas and Florida were impressive. But right now I think the data ha been practically invalidated, and I cannot see any other arguments that would lead me to believe that a "right-to-carry" law does more good than evil. > But I do find that the repeated use of statistics in this thread is quite > the problem, not quite the solution. Those claiming a right to gun > ownership are specifically claiming the irrelevancy of such analysis. That > is exactly, in many ways, the point - it seems to me. > > Statistically, they have exactly one family. And statistically have the > right - in their to view - to do exactly what they statistically decide is > necessary to protect that statistic. > > To in fact specifically not be a statistic. > > Yes, there is something quite American about that viewpoint. God bless. I certainly wouldn't call this "American". "Evasive" would be a better word. Of course anyone is entitled to protecting their own, and their family's, lives and property using any means she considers appropriate. But we're all part of the big picture too, no matter how we contest it. If I believe that passing a law will cause more deaths to take place, I will oppose the law even if personally I wouldn't mind owning a gun for protection. > Art -- Grzegorz Staniak From interstar at postmaster.co.uk Mon Sep 22 13:16:56 2003 From: interstar at postmaster.co.uk (phil) Date: 22 Sep 2003 10:16:56 -0700 Subject: python cgi problem with method = post References: <3F6DC6D3.E6454738@engcorp.com> Message-ID: Sorry, my bad! I've been using other forums where there's turnaround of a couple of hours or things get lost in the depths of history. Forgot what Usenet is like :-) I'll go away and look at the problem some more and try to come back with more details. cheers phil jones Peter Hansen wrote in message news:<3F6DC6D3.E6454738 at engcorp.com>... > > The mailing list and newsgroup are working well enough, so if you > receive no useful answers it's likely because nobody could understand > the question clearly enough to think how to answer. > > One thing you might consider is including some actual samples of > code, so people don't have to imagine which of the five dozen > possible approaches you are actually using. > > Also make sure you have tried other approaches to ensure that the > problem is actually with your own code and not with some host-specific > problem which nobody else will ever be able to reproduce locally. > > > > So, I don't expect anyone to be able to answer this ... but what > > Yet you were hopeful for answers? ;-) > > > > *kind* of thing should I be looking for? Is it to do with versions of > > > python (2.1.3 locally, 2.2 remotely) or "cgi"? Or the webserver (I'm > > > using Apache on Debian locally, I suspect my host is Apache on Red Hat > > > 7.1) > > Python includes excellent facilities for debugging problems of various > kinds, including this kind. Why not experiment a little and see what you > can come up with? It's unclear from your description where your problem > might be so without additional information any suggestions are random > shots-in-the-dark, and that I suspect is why no one responded yet. > > Also, I just noticed, you waited only one day before your second post. > That's far too little time to wait, as for many people it can take > several days for Usenet posts to reach them and, furthermore, you posted > at the end of the work week and many people read Usenet only at work. > > Summary: experiment, post more and more detailed information, and be > more patient. > > -Peter From alan.gauld at btinternet.com Tue Sep 2 17:50:50 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Sep 2003 21:50:50 GMT Subject: Polymorphism the Python way References: Message-ID: <3f550e2f.254030105@news.blueyonder.co.uk> On Tue, 02 Sep 2003 16:34:37 +0200, Bertel Lund Hansen wrote: > "Encapsulation" is the word that describes the effort(s) to make > it impossible for the user of a module to access the attributes > (and hidden methods) directly and only allow him to do it through > public methods with build-in check so that no disasters occur. Does anyone else really hate this corruption as much as me? It seemed to take hold when C++ appeared. Encapsulation in OO originally meant the ability to bind data and functions together into a single thing (that we call an object). (Some early "OO" languages apparently provided objects without an explicit class type construct, so they were not encapsulated objects - does anyone remember any such beasts? They were before I joined the OOP circus in the mid '80s.) The ability to hide the internal data was called data hiding (originally coined by David Parnas talking about modular programming I believe). Encapsulation and Data Hiding were thus two different things and Encapsulation (like Python does) was an essential feature of OOP along with Polymorphism (whether based on inheritance (like C++) or inteface (like Python)). Data Hiding was desirable but optional (several OOP languages provide encapsulation and not Data Hiding). Similarly some OOP languages provide polymorphism by other means than inheritance and so inheritance also was desirable but not essential for OOP (but that has always been a point of some debate). I've been trying to find the exact point when encapsulation changed its meaning to data hiding but without success. It seems to have been around about 1990-2 somewhere... Sorry, just had to get that off my chest! :-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From hans at zephyrfalcon.org Mon Sep 29 17:11:30 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Mon, 29 Sep 2003 17:11:30 -0400 Subject: A startup puzzle In-Reply-To: References: Message-ID: <3F78A002.3000505@zephyrfalcon.org> Edward K. Ream wrote: > I've just about convinced myself there is no good, clean solution to the > following puzzle. I wonder if you agree. > > 1. My app has a module called leoGlobals that contains often-used global > functions. All of Leo's source files start with: > > from leoGlobals import * > > I don't want to discuss whether this is good style: it is simple and it > works well for me :-) Fair enough, but it's not just a matter of style... using something like import leoGlobals as g would probably have avoided this problem, since you can do: import leoGlobals as g # later... g.app = leoApp.leoApp() # every module that imported leoGlobals now knows g.app as well Cheers, -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From domma at procoders.net Tue Sep 23 17:46:39 2003 From: domma at procoders.net (Achim Domma) Date: Tue, 23 Sep 2003 23:46:39 +0200 Subject: Barcode generator for Python? References: Message-ID: Hi Jen, I wrote a wrapper around the GNU Barcode library, but nobody really used it. You can get it from here: http://www.procoders.net/download.php?fname=PyBarcode.zip It should be for python 2.2. Look at the example to see if it suits your needs. If yes, I could build a new version for python 2.3. regards, Achim From kmkstyle at hotmail.com Tue Sep 16 07:43:50 2003 From: kmkstyle at hotmail.com (Kathleen Kudzma) Date: Tue, 16 Sep 2003 07:43:50 -0400 Subject: Tkinter and Movie Player Message-ID: Does anyone know of a movie player besides pygame that can be embedded in a Tkinter widget. It needs to support Windows and Linux. It needs to play mpegs. The frame in the movie player that actually contains the video is the portion that I want to embed in Tkinter. I would like to make my own player controls in Tkinter. _________________________________________________________________ Use custom emotions -- try MSN Messenger 6.0! http://www.msnmessenger-download.com/tracking/reach_emoticon From mpeuser at web.de Tue Sep 9 07:41:48 2003 From: mpeuser at web.de (Michael Peuser) Date: Tue, 9 Sep 2003 13:41:48 +0200 Subject: What does the keyword 'global' really mean References: <3f5db3b6$0$252$fa0fcedb@lovejoy.zen.co.uk> Message-ID: "John Dean" schrieb im Newsbeitrag news:3f5db3b6$0$252$fa0fcedb at lovejoy.zen.co.uk... > Hi > I have been looking through some Python code and I came across the keyword > 'global'. I have looked through the docs and two or three Python programming > books for a full explanation of what 'global' really means. Would I be > correct in assuming that any variable prefixed with the keyword global would > allow that variable to be accessible across translation units, in other > words global is equivalent to the 'C' keyword 'extern' ? (1) No! When you 'import' a modul all variables (except __...) will be visible to you. (2) You as well have visiblity inside a modul function to variables used in the modul scope, i.e. you do have to declare them 'global' if you only want to 'read' them. (3) It does not work the other way round. It you assign something ('bind' ) to avariable ('name') (what you would call 'local definition' in some other languages, this variable will not be visible to the outside wortld (thus (1) is not quite correct ;-) ) (4) This is where 'global' enteres the scene. Declaring a name in a local (function) context as 'global' makes is visible to all the modul. (5) You as well can declare a variable as 'global' in the modul context; I am not aware of any use there, except purely informative. > Also, does Python have the equivalent of the 'C' keyword 'static'? Not as a special construct, but you can use real 'dummy keyword parameters' for that: def p(p1,p2,....myown={}): myown[....] = This trick will emulate something similar to 'static' Kindly MichaelP From nikolai.kirsebom.NOJUNK at siemens.no Thu Sep 25 03:45:31 2003 From: nikolai.kirsebom.NOJUNK at siemens.no (Nikolai Kirsebom) Date: Thu, 25 Sep 2003 09:45:31 +0200 Subject: Getting C++ object from PyObject * Message-ID: I'm using BOOST to integrate Python into our application. Could someone tell me how I get hold of the C++ object (pointer to the object instance) from a PyObject *. Example: I have defined and exposed two C++ classes: class MyObjectA { public: MyObject(); }; class MyObjectB { public: MyObjectB(); void SetInput(PyObject *o); }; In Python I'm able to write: pa = MyObjectA() pb = MyObjectB() to create an instance of each of the classes. Then using the exposed SetInput method of class MyObjectB: pb.SetInput(pa) How would I code the SetInput method: void MyObjectB::SetInput(PyObject *o) { //Check that type of 'o' is an (instance) object of class 'MyObjectA' //Fetch the pointer (reference) to the actual instance of MyObjectA MyObjectA * ca = ..... } Thanks for any help. Nikolai From anton at vredegoor.doge.nl Wed Sep 17 10:48:48 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Wed, 17 Sep 2003 16:48:48 +0200 Subject: [OT] Half the download size References: <5laemv46hi2dv8k3lo53h0ctpitnh3nmp9@4ax.com> Message-ID: Christos "TZOTZIOY" Georgiou wrote: >-Hm... Python is quite big... >-Yes, it's the philosophy I told you about, "batteries included". Lots >of useful stuff. >-Is this the reason, or is it that I'm also downloading the huge list of >contributors? ;-) >-Ah! Sorry, my mistake, pointed you to the wrong URL... you should click >the other one that's half the size. >-Which one? >-The one under the name of... uh... "Ungrateful Python". Yes it's a problem. There's too much useful stuff and the list of developers gets longer and longer. However the following script could be used to generate a placebo Python contributors list (after installation) at a fraction of the download size. It also shows that the problem won't be significant unless the number of contributors gets way bigger than 10000. Anton from random import sample,randint from string import ascii_lowercase,capitalize from zipfile import ZipFile,ZIP_DEFLATED def newname(minfirst,maxfirst,minlast,maxlast): nfirst = randint(minfirst,maxfirst) nlast = randint(minlast,maxlast) firstname = "".join(sample(ascii_lowercase,nfirst)) lastname = "".join(sample(ascii_lowercase,nlast)) return " ".join(map(capitalize,[firstname,lastname])) def main(): textfilename = "contributors.txt" archivename = "contributors.zip" n = 10000 minfirst,maxfirst,minlast,maxlast = 3,10,4,20 tup = minfirst,maxfirst,minlast,maxlast names = [newname(*tup) for i in range(n)] f = open(textfilename,"w") for name in names: f.write("%s\n" %name) f.close() Z = ZipFile(archivename,'w',ZIP_DEFLATED) Z.write(textfilename) Z.close() if __name__=='__main__': main() From aleax at aleax.it Fri Sep 5 16:59:25 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 20:59:25 GMT Subject: Why python??? References: Message-ID: Michael Peuser wrote: ... > A very good reply! But I have an answer as well: The only reason why Linux > got a market share is Moore's Law. Nobody of clear commercial thinking Moore's Law is working in favour of higher level languages even harder than it's working in favour of free but highly efficient OS's. > will pay $200 for an operating system when the hardware has the same Most Linux use of commercial significance is not happening on such incredibly cheap systems, but rather on reasonably substantial servers (or sometimes even mainframes -- IBM _has_ invested a lot in Linux:-). The issue you mention MAY play a role in ensuring a nice for Lindows (and other desktop-oriented versions of Linux), but the server side is where Linux got its first foothold. > price! There is nothing like that happening with respect to languages or > development tools. Commercially it is of no major significance whether a > tool costs $100, 1000 or 10.000. The real money has to be paid for the > programmer, for testing, for maintenance, for advertising, for waranty; > 1000 to 10.000 times as much! Moore's Law is crucial in determining how much performance is necessary to make a given piece of software good enough. Once upon a time, only machine code was good enough -- hardware performance was SO costly that it was cheaper to employ ten times as many programmers than to get HW ten times faster, for most tasks of practical significance. In the late '50s/early '60s, the first high-level programming languages began to gain substantial commercial foothold -- because, thanks to Moore's Law (not formulated yet, but already in action), the price/ performance of hardware was getting good enough to afford _some_ minor inefficiencies in order to save on programming effort. The gradual spread of higher-level languages to more and more areas is following just the same law. For any given program functionality, you can get it cheaper (and slower) by using a higher-level language than by using a lower-level one. The cheapness applies just as much to testing and maintenance as to development -- there's less to test and less to maintain for any given amount of (say) FP's. And the speed-to-market results in hitting market windows better and thus can even reduce the needed investments in advertising (as for warranties, they don't currently play any significant role in big-money software, or else Microsoft, with its level of bugginess and security issues, would be broke many times over by now;-) > So it comes to the question: What does the common programmer know? This is Not necessarily. If common programmers only knew machine language, it would still be cheaper to use any available high-level language, say COBOL, even if you needed to supply training for it (it's not hard to teach COBOL to somebody who knows assembly, anyway -- the reverse is harder). Similarly, using Python can lower costs even if you factor in training costs (again, teaching Python to good Cobol programmers is quite easy -- other higher-level languages may not be _quite_ as cheap in these terms, admittedly, but still the economics aren't _hugely_ different). Alex From mrroach at okmaybe.com Wed Sep 3 10:31:05 2003 From: mrroach at okmaybe.com (Mark Roach) Date: Wed, 03 Sep 2003 14:31:05 GMT Subject: How to accelerate python application GUI speed References: <43e3984e.0309030532.3fe88bbc@posting.google.com> Message-ID: On Wed, 03 Sep 2003 06:32:42 -0700, ulysses wrote: > Hi,all > > I use wxPython make a bittorrent client. I find wxPython very slow and > use many many memory. > When app start, it need 19MB memory. I only use common GUI components. > Python is a really good > programming language. But how to do a small,smart, efficency GUI in > win32,it's a big question. [snip] > 5. I have a another idea. use wxWindows (c lan) build a GUI. embed > python code . > or embed wxWindows code to python by SWIG. I have't test it. if you > have do it. > Please tell us. Swig is how wxPython works already. If you wanted to do the whole gui in C++, and just have python launch the code, you can do an extension pretty easily, see my wiki entry here: http://wiki.wxpython.org/index.cgi/C_2b_2bExtensions (I'm not sure that this will make any difference wrt memory usage though.) I think that letting C++ "drive" your code will be a significantly greater time investment, I'm not sure how much of an effort it is to get the python mainloop and the wxWin mainloop to work together, but since it is already done for me with wxPython, I don't think I'll go trying to find out either :-) -Mark From nospam at here.com Tue Sep 16 15:39:29 2003 From: nospam at here.com (Richard Townsend) Date: Tue, 16 Sep 2003 20:39:29 +0100 Subject: Tkinter: tooltips (Windows) References: Message-ID: <1063740937.38115.0@doris.uk.clara.net> "M-a-S" wrote in message news:lsJ9b.13162$x21.6784 at twister.southeast.rr.com... > How can I have tooltips for buttons of a toolbar > or for control items of a dialog? > Does such feature exist at all? > You can use the Pmw.Balloon widget to do this. For Pmw (Python Mega Widgets), see: http://pmw.sourceforge.net/ John Grayson's book 'Python and Tkinter Programming' (see http://www.manning.com/grayson/index.html) has some examples which use it. The code in the book can be downloaded from http://www.manning.com/getpage.html?project=grayson&filename=Source.html RT From oystein at gnubg.org Wed Sep 17 16:15:23 2003 From: oystein at gnubg.org (=?ISO-8859-1?Q?=D8ystein_Johansen?=) Date: Wed, 17 Sep 2003 22:15:23 +0200 Subject: texi2html in a cgi ? In-Reply-To: <33803989.0309171007.28ca7fda@posting.google.com> References: <8vL9b.30567$Hb.466972@news4.e.nsc.no> <33803989.0309171007.28ca7fda@posting.google.com> Message-ID: <3F68C0DB.8030305@gnubg.org> Miki Tebeka wrote: > I see two ways: > 1. Write the texi file to disk (use tempfile.mkstemp) and run the script > (using os.system) on it and send back the result > 2. Import texi2html (make sure it's in sys.path) and use it (this is not tested...) > ---- > from texi2html import TexinfoParser, HTMLHelp > from tempfile import mkdtemp > from os.path import dirname, join > > def to_html(file): > '''Convert texinfo to html. Return top html file''' > outdir = mkdtemp() > parser = TexinfoParser() > parser.sethtmlhelp(HTMLHelp("","")) > parser.setincludedir(dirname(file)) > parser.setdirname(outdir) > parser.parse(open(file)) > return join(outdir, "%s.html" % parser.topname) It works locally with the file below: #!/usr/bin/python from texi2html import TexinfoParser, HTMLHelp from tempfile import gettempdir from os.path import dirname, join def to_html(file): '''Convert texinfo to html. Return top html file''' outdir = gettempdir() parser = TexinfoParser() parser.sethtmlhelp(HTMLHelp("","")) parser.setincludedir(dirname(file)) parser.setdirname(outdir) parser.parse(open(file,"r")) return join(outdir, "%s.html" % parser.topname) to_html("faq.texi") It creates several html files in /tmp/, one file for each section, but how do I create only one file, faq.html? > Remeber to delete the directory from time to time ... I will! >>(Unexperienced Python programmer, who has just fallen in love with this >>beautiful programming language.) > > The more you'll know the deeper you'll fall in love :-) More and more each day! Thanks, -?ystein From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 11:12:28 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 16:12:28 +0100 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> <10c662fe.0309270545.1fd5d839@posting.google.com> Message-ID: On 27 Sep 2003 06:45:23 -0700, roberto at dealmeida.net (Roberto A. F. De Almeida) wrote: >Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:... >> I would have expected, given that the tuple contains slice objects >> constructed from the multiple-slice notation, that the same >> translations would be performed on the slices that are inserted into >> the tuple that are applied when the single slice is created. >> >> That is, whether the single or multiple notation is used, and whether >> the slice objects are placed in a tuple or not, they are constructed >> from the tuple notation - the translation from notation to slice >> object should be done consistently. > >Yes, I believe I was not very clear. This is the inconsistency I was >talking about. (And this is with Python 2.3.1) Hmmm. I basically used your earlier print-the-index-to-getitem code (on Python 2.3) and got... """ >>> a[:-1] slice(None, -1, None) """ but then I realised I did one thing different compared with your example - I inherited from 'object', creating a new-style class (which is getting to be a habit). Doing it without the inheritence from object, I got... """ >>> b[:-1] Traceback (most recent call last): File "", line 1, in ? AttributeError: y instance has no attribute '__len__' """ which is exactly what you got. Which suggests that the attempt to translate that '-1' to a positive subscript is an old convenience, kept for backward compatibility in old-style classes, but dropped for greater generality in new-style classes. I can understand the assumed-to-be old approach - slicing isn't implemented at present on any builtin container except those that use subscripts (it works on lists but not dictionaries, for example) but in terms of generality I'm rather glad we can opt out of it by using new style classes. While hashing doesn't support it, some mapping-style data structures can reasonably support slicing by key - and as in your example, even when using subscripts (as in your example) the length may be unknown in advance, and the container may not even have a simple scalar length. >Data is only retrieved when you slice a variable like above, and only >the data sliced is requested from the OPeNDAP server, instead of the >whole range. If I use multiple slices, eg, Makes good sense. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From pieter.lust at katho.overbodig.be Fri Sep 12 03:16:16 2003 From: pieter.lust at katho.overbodig.be (Pieter Lust) Date: Fri, 12 Sep 2003 07:16:16 GMT Subject: [newbie] File handle destroyed before pending write is executed? Message-ID: <3f6172be.1493111@news.tijd.com> Hello, I'm trying to learn myself Python. Doing that, I tried to implement something logfile-ish. The essence looked like this: # main module import logmodule mylog = logmodule.logfile() mylog.enter('something') # pass # end main module # logmodule class logfile: def __init__(self): self.fh = file('log.txt', 'w') def __del__(self): self.fh.close() def enter(self, text): self.fh.write('%s\n' % text) # end logmodule After running the main module, log.txt was empty, though no exceptions were raised. To get the text into the file, I had to add the pass statement that's commented out above. In debug mode, the line cursor jumps from the last line of the main module into the __del__() method of the logmodule, but not into the enter() method. It seems that when the pass statement is not there: - the interpreter parses the mylog.enter() line - then sees that it is the last statement in the module - because of that at once destroys all local objects in it, even though the last statement requires one of those local objects - this causes the __del__ method of the logfile to be called, so the file is closed - and only afterwards actually executes the last statement, which fails but does not raise an error. Is this what actually happened? And if so, is this triggerhappy destroying required behaviour of a Python interpreter? (I'm using v2.2, in the ActiveState PythonWin distribution.) Thanks for improving my understanding of Python. Pieter Lust From mwh at python.net Fri Sep 19 08:12:38 2003 From: mwh at python.net (Michael Hudson) Date: Fri, 19 Sep 2003 12:12:38 GMT Subject: Access to Win API References: <0c58d500ac94b27d7f8ff87a2a59f6e1@news.meganetnews.com> Message-ID: <7h33cetj818.fsf@pc150.maths.bris.ac.uk> Gerhard H?ring writes: > Ladv?nszky K?roly wrote: > > Thanks for your help. I remember once I tried a Python cookbook sample code > > that included ctypes but now 'import ctypes' does not work. > > Should ctypes come together with the 2.3 installation? [...] > > No, it's a third-party module that you need to download and install. > > Google says it's at http://starship.python.net/crew/theller/ctypes/, > but the Starship seems to be down ATM [1]. It's only DNS woes. Try IP 217.160.219.194. Cheers, mwh -- Darned confusing, unless you have that magic ingredient coffee, of which I can pay you Tuesday for a couple pounds of extra-special grind today. -- John Mitchell, 11 Jan 1999 From JoeyTaj at netzero.com Sun Sep 28 14:05:02 2003 From: JoeyTaj at netzero.com (Paradox) Date: 28 Sep 2003 11:05:02 -0700 Subject: Distutils Configuration for Visual Studio 6? Message-ID: <924a9f9c.0309280919.188478bb@posting.google.com> I have tried to run setup from source for PyOpenGL and PIL and on both I get this error "error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed." I definitely have VS6 installed. I can't figure out were in the code this error is getting generated and it doesn't mention anything about VS in the distutils documentation. Does anyone know how to get around this error? Thanks Joey From cartermark46 at ukmail.com Mon Sep 29 06:22:11 2003 From: cartermark46 at ukmail.com (Mark Carter) Date: 29 Sep 2003 03:22:11 -0700 Subject: VB6 thin client Message-ID: Suppose I wanted to combine a thin client written in VB6 with a server on a remote machine. Since this is the python group, assume for now that it could be written in python (although VB6 would be a nice alternative). What technologies would I use? From mpeuser at web.de Mon Sep 8 02:01:16 2003 From: mpeuser at web.de (Michael Peuser) Date: Mon, 8 Sep 2003 08:01:16 +0200 Subject: negative indices for sequence types References: Message-ID: "dan" > I was recently surprised, and quite shocked in fact, to find that > Python treats negative indices into sequence types as if they were > mod(length-of-sequence), at least up to -len(seq). > > This fact is *deeply* buried in the docs, and is not at all intuitive. I think it is addressed even in most tutorials because it is quite handy as others already pointed out. There is the same fetaure in Perl. Kindly Michael P From jacek.generowicz at cern.ch Fri Sep 5 07:48:39 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Sep 2003 13:48:39 +0200 Subject: Invisible function attributes References: <51809ae4.0309030715.7706cadb@posting.google.com> <87he3tfopa.fsf@pobox.com> <51809ae4.0309040627.28d7a075@posting.google.com> Message-ID: lefevrol at yahoo.com (Olivier Lefevre) writes: > Nudged by the dot syntax, I was thinking of this function attribute as > if it were a sort of class member (i.e., pretending for a while this > function is a class) and, since functions can't have instances, treating > it as a sort of static member of the function, which should be available > as soon as declared. There is no declaration in Python; you just create attributes by binding objects to names. > Obviously I got it all wrong. Instead, they work like local > variables except that they "persist" after the function has exited. Hmmm. No. Functions are first class objects, and you can dynamically add attributes to them as you go along (as is the case for many, but not all, other types of objects). Do you realize that the foo identifier you used in your example is not inextricably linked to any function whose name is foo? The name of a function, and the variables to which it is bound are two different concepts. Consequently, the foo.a in the function body only _coincidentally_ refers to an attribute of the function in which it appears. Consider: >>> def foo(arg): foo.a = arg ... >>> bar = foo # Now the function is known by two different names >>> bar(3) >>> foo.a 3 >>> foo = 1 # Now the function called "foo" can only be accessed via bar ! >>> bar(4) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in foo TypeError: 'int' object has only read-only attributes (assign to .a) >>> bar # I call it "bar", bit it thinks it's called "foo" >>> The error at "bar(4)" in the above should hint at the fact that the "foo" in "foo.a" in the definition of the function foo, does not refer to the function itself but to whatever object which happens to be bound to the name "foo" at the time the function is being exectuted. > What are they used for? Give me a compelling reason to have such a > beast in the language. Now there's a good question :-) I haven't found a use for these myself ... but then I haven't looked very hard for one. Given that function attributes were added to the language (in version 2.1 or 2.2 ?), I guess someone felt a need for them, and Guido agreed. From dfh at forestfield.co.uk Thu Sep 25 09:07:00 2003 From: dfh at forestfield.co.uk (David Hughes) Date: Thu, 25 Sep 2003 14:07 +0100 (BST) Subject: Stuck building a Python extension Message-ID: I'm nearly there building a Python extension module to access a set of functions in a .dll, but I'm getting an unresolved external error for one of the function calls (using MS Visual C++ V6). The function prototype is: extern short __stdcall SharewareLimit(char * s1, char * s2, short i); which I'm calling from: static PyObject *oneway_SharewareLimit(self, args) PyObject *self; /* Not used */ PyObject *args; { char * company; char * software; short evalperiod; short expired; if (!PyArg_ParseTuple(args,"ssh:SharewareLimit",&company ,&software, &evalperiod)) return NULL; expired = SharewareLimit(company ,software, evalperiod); return Py_BuildValue("h",expired); } I would expect the code to be calling a function called _SharewareLimit at 10 to match the size of the arguments (and which I have called successfully from a Fortran program in the past), but the unresolved external is _SharewareLimit at 12, implying that somewhere the short 2-byte integer is being promoted to 4 bytes. I know this is probably a C compiler (settings?) not a Python problem, but I'd appreciate some assistance as my knowledge in this area is sketchy. Thanks, David. From mpeuser at web.de Sun Sep 7 10:36:43 2003 From: mpeuser at web.de (Michael Peuser) Date: Sun, 7 Sep 2003 16:36:43 +0200 Subject: Why python??? References: <87fzjalogu.fsf@pobox.com> <87vfs6unsx.fsf@pobox.com> <87n0dhpm1t.fsf@pobox.com> <8765k44uma.fsf@pobox.com> Message-ID: "John J. Lee" schrieb im Newsbeitrag news:8765k44uma.fsf at pobox.com... > I'm afraid I've reached the same conclusion as Alex -- you're really > not trying, so I find I've lost enthusiasm to reply any more to your > posts. So sorry - most probably my fault. But maybe this article may make you smile a little. http://spike.scu.edu.au/~barry/RealProgrammers1.html Kindly Michael P From guettli at thomas-guettler.de Mon Sep 15 03:01:33 2003 From: guettli at thomas-guettler.de (Thomas Guetttler) Date: Mon, 15 Sep 2003 09:01:33 +0200 Subject: pyc2py Message-ID: Hi! Is there a script which converts compiled python code to human readable code? Google found no result for "pyc2py". thomas From tibi87 at hanmail.net Fri Sep 26 11:53:57 2003 From: tibi87 at hanmail.net (Jenny) Date: 26 Sep 2003 08:53:57 -0700 Subject: Access to database other web sites Message-ID: I am doing research about realationship between sales rates and discounted prices or recommendation frequency. To do this, I need to access the database of commercial web sites via internet. I think this is possible because it it simmilar to the work of price comparison sites and web robot. I am studying python these days because I thinks it is a good language for the work. Actually I am a novice at python. I welcome any informaion about this problem. Thanks in advance. From tchur at optushome.com.au Sat Sep 27 16:55:12 2003 From: tchur at optushome.com.au (Tim Churches) Date: 28 Sep 2003 06:55:12 +1000 Subject: Here is a new, free Python icon/logo In-Reply-To: References: Message-ID: <1064696112.1190.15.camel@emilio> On Sun, 2003-09-28 at 03:57, Stephen Ferg wrote: > I've developed a little Python icon/logo suitable for use on a Web > page. It is in the public domain. > > http://www.ferg.org/python_logos/index.html > > It is not the most artistically sophisticated thing in the world, but > it is bold and colorful. Feel free to use it as you wish. Nice logo, but why the herpetological obsession? We all know why Python is called Python, so isn't a mascot like this far more Pythonic: http://solair.eunet.yu/~janko/birdman.gif -- Tim C PGP/GnuPG Key 1024D/EAF993D0 available from keyservers everywhere or at http://members.optushome.com.au/tchur/pubkey.asc Key fingerprint = 8C22 BF76 33BA B3B5 1D5B EB37 7891 46A9 EAF9 93D0 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From gerrit.muller at embeddedsystems.nl Thu Sep 11 02:47:01 2003 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Thu, 11 Sep 2003 08:47:01 +0200 Subject: Arctec newsletter mentions Guido's move Message-ID: <3F601A65.3040804@embeddedsystems.nl> At the move of Guido is brought to the attention of the broader enterprise and IT world: > Stay Tuned for Security Improvements > A development that went unnoticed by major IT media which may turn out to > have positive and broad implications for security and development occurred > at Elemental Security. Python programming language inventor Guido van > Rossum joined the very productive Dan Farmer, author of security tools > such as SATAN and COPS, at Elemental Security. > http://www.onlamp.com/pub/a/python/2003/08/14/gvr_interview.html > kind regards Gerrit -- Gaudi systems architecting: http://www.extra.research.philips.com/natlab/sysarch/ From tzot at sil-tec.gr Wed Sep 3 12:01:21 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 03 Sep 2003 19:01:21 +0300 Subject: Extracting TIFF from emails References: Message-ID: <5m3clv83ud55ml14kcof9nnpuurifb6n11@4ax.com> On 3 Sep 2003 07:04:17 -0700, rumours say that ryan at ryanswift.com (Ryan Swift) might have written: >Hi, I'm new to Python, so this may be an easy solution. I'm having >trouble extracting TIFF files from incoming emails. Actually, I think >the root of my problem is that I'm having trouble reading the email >header. Does anyone have an easy solution? Thanks in advance. Check the email package. Read about the following: * email.message_from_file (Assuming you have your incoming mail in a text file) * class email.Message, its walk method For each part in the .walk() call, check the .get_content_type() result, and if it's an 'image/tiff', you have the image data calling .get_payload(decode=True) Roughly :) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From max at alcyone.com Wed Sep 24 19:28:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 24 Sep 2003 16:28:07 -0700 Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> <3f71395d-46f08129-996a-495d-a5ee-05fb1caef6e9@news.szn.dk> <3f721b0c-fce176ad-f4e1-4bdc-8527-cc05ef24ad42@news.szn.dk> Message-ID: <3F722887.F4521F68@alcyone.com> Klaus Alexander Seistrup wrote: > Anyway you look at it, killing blindly is bad programming practice. But he's killing with a signal of 0. From kill(2): If sig is 0, then no signal is sent, but error checking is still performed. It's perfectly reasonable behavior to kill a process with a 0 signal; it does no harm. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I love mankind; it's people I can't stand. \__/ Charles Schultz From tjreedy at udel.edu Fri Sep 5 22:16:51 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 5 Sep 2003 22:16:51 -0400 Subject: Anybody else having problem *sending* mail to this list? References: Message-ID: "Skip Montanaro" wrote in message news:mailman.1062780020.16308.python-list at python.org... > > Terry> Yes, a worldwide virus-induced mail blizzard. > > This has been my biggest gripe about the damn virus. The virus itself was > no problem for me since I don't use Windows, but the thousands of "you have > a virus!" mails sent in response clogged my inbox until I trained SpamBayes > to view them as spam. Is there any reasonable way to get the anti-virus > vendors to realize they are a very large part of the problem? Shouldn't > virus scanners simply eat the virus and not send another mail? Does anyone > have a list of a-v vendors' email addresses so I can harangue them a bit on > the topic? How about sending them 'virus' mail with their own addresses as the faked return, so they can spam themselves and each other? Terry ;-) From davidcfox at post.harvard.edu Wed Sep 24 16:35:45 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Wed, 24 Sep 2003 20:35:45 GMT Subject: Newbie: Changing a string to a class attribute. In-Reply-To: <33fbf9ec.0309241210.7acfddb9@posting.google.com> References: <33fbf9ec.0309241210.7acfddb9@posting.google.com> Message-ID: Jacob H wrote: > This is a very simple problem and I'm sure the answer is a no brainer. > However my brain can't see the answer. ;) > > Given code like this: > > def exec_method(object, method): > # object is an instantiated object, e.g. log > # method is a string that matches a method of object, e.g. > "update" > # code stuff here that calls object.method, e.g. log.update() > > What is the best way to turn method, a string, into a valid reference > to the actual class method? My first thought was eval(). But I can't > do this: > > eval("class.method()") > > Eval will look for a method actually called method() and there isn't > one. What's a good solution for this? Heck, for all I know, Python > implicitly provides functionality to solve this problem. Can anyone > help? :) getattr(x, method)() However, it isn't usually necessary to do this, because if x is an object with method update, x.update is an object which can be passed or stored. David > > Jake From tim.one at comcast.net Thu Sep 4 21:16:39 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 4 Sep 2003 21:16:39 -0400 Subject: Anybody else having problem *sending* mail to this list? In-Reply-To: Message-ID: [Terry Reedy] > Yes, a worldwide virus-induced mail blizzard. Someone (Skip M. I > think) annouced yesterday or so that the Python mail server was down > for a breather. Today, someone said it was backed-up, back up, but > slow. Hence, this arrived at Giganews over a day after you sent it. During part of this mess, the email server also ran out of disk space, and the older exim version in use appeared to keep crashing under the load. As a result, last I heard (this afternoon) Barry was pretty sure that a great many messages are simply going to be lost forever, on the order of 100,000(!). Almost all of those are worm turds (idiotic "you have a virus!" warnings sent back by other email servers in response to a Sobig message with headers forged to make it look like it came from python.org). Still, some real email is doubtless lost too. People looking for someone to blame should focus on Sobig's author -- Barry has endured enough abuse <0.6 wink>. From colarte at telesat.com.co Mon Sep 22 02:05:30 2003 From: colarte at telesat.com.co (Camilo Olarte) Date: Mon, 22 Sep 2003 01:05:30 -0500 Subject: Pmw menubutton enable/disable, better answer .. In-Reply-To: References: Message-ID: <20030922010530.4432840b.colarte@telesat.com.co> Well i needed to do something like that , so i came up with this example . the main idea here is using the entryconfig with an index that can be the same as the label you gave to the menubutton Hope it helps ... !/usr/bin/python #tkex1.py - tkDemo#1 1.1 - 30 May 01 #A Windows/Unix script to demonstrate basic Tkinter programming #Update at http://www.3dartist.com/WP/python/tknotes.htm#tkex1 #Created by Bill Allen --Modified by Camilo Olarte .9/22/2003 usingIDLE = 0 #set = 1 if running from IDLE, otherwise 0 import tkMessageBox import Tkinter as tk #--- classes --- class uiClass: #user interface class def __init__(self,master,ar,xy,flex): # used once for main GUI self.master = master menubar = tk.Menu(master) #create a menu object tied master.config(menu=menubar) # to the root parent self.mainmenu = tk.Menu(menubar,tearoff=0) #create a dropdown menu self.mainmenu.add_command(label='Exit',underline=1,command=self.quit) self.mainmenu.add_command(label='Do Something',underline=1,command=self.fnDoSomething) self.mainmenu.add_command(label='Kill Exit :) ',underline=1,command=self.fnDeactivateMenu) menubar.add_cascade(label='Main', #give the dropdown menu a menu=self.mainmenu, # name & add it to the underline=0) # menu object self.frame = tk.Toplevel(relief='ridge', #border style borderwidth=2, #create the main GUI window menu=menubar) # with its menu object self.frame.geometry(ar+xy) #set its size & location self.frame.resizable(flex,flex) #(dis)allow resize horiz/vert if not usingIDLE: #system window exit protocol self.frame.protocol('WM_DELETE_WINDOW',self.quit) #end def self.__init__ def fnDoSomething(self): tkMessageBox.showinfo('!!','Doin Somethin!:') def quit(self): if usingIDLE: self.frame.destroy() else: self.frame.quit() root.quit() def fnDeactivateMenu(self): self.mainmenu.entryconfig(self.mainmenu.index("Exit"), state=tk.DISABLED) #end define uiClass #--- do some work --- if __name__ == '__main__': #optional, but good practice root = tk.Tk() root.title('tkDemo#1') root.withdraw() #suppress unwanted window mainUI = uiClass(root, #set up the main GUI window '400x200', # width & height '+20+20' # initial XY screen location ,0) # resizing turned off if not usingIDLE: #avoid IDLE or other Tkinter IDEs root.mainloop() #outer event loop -------------- next part -------------- A non-text attachment was scrubbed... Name: tkex1.py Type: application/octet-stream Size: 2814 bytes Desc: not available URL: From nick.keighley at marconi.com Wed Sep 24 05:13:39 2003 From: nick.keighley at marconi.com (Nick Keighley) Date: 24 Sep 2003 02:13:39 -0700 Subject: Python <-> C via sockets Message-ID: <8ad2cfb3.0309240113.19d9198a@posting.google.com> I'm probably missing something rather obvious, but is there a known problem with getting a Python based socket program to communicate with a C based socket program? A simple echo server written in Python (the example from Python in a Nutshell actually) will happily talk to a Python based client. If a C based client is substitued the connection is refused (or so the C client reports). The C client will talk to a C server. -- Nick Keighley From tjreedy at udel.edu Sat Sep 6 16:56:36 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Sep 2003 16:56:36 -0400 Subject: [2.3] object does not appear to be a reserved word References: Message-ID: "Daniel Klein" wrote in message news:v89klvsupdoe39e6trqbbqvmhfgecnoum8 at 4ax.com... > Is it potentially dangerous to use the variable 'object' in code? Yes, it is potentially dangerous to use any of the names in the builtin module. It is disrecommended for posted/public code without good reason (intentional override). TJR From bokr at oz.net Mon Sep 8 14:20:56 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Sep 2003 18:20:56 GMT Subject: Comments on Python Redesign References: Message-ID: On Mon, 8 Sep 2003 09:13:45 +0100, "Tim Parkin" wrote: >Bengt Wrote >>It looks slick, but not really technically slick in a way >>that would lead me to expectations about Python, just >>eye-candy/we-spend-more-on-advertising-than-research >>kind of slick (though for largely irrelevant photos, I >>prefer pretty things and/or great photography ;-) > >What has amazed me throughout the pulling of a discussion >Onto the Python list is the amount of furor that has been >generated by the use of three photographs. The marketing >content of the website takes only 7% of the space of the >main page. The remaining is textual navigation content. > Being goosed is not a matter of percentages ;-) >If we're in a position where people hate photography then If you take my post to mean I hate photography, then you misread. I said, "I prefer pretty things and/or great photography." >I think we have to accept that this is an irrational >problem and that it shouldn't affect the promotion of >Python in the computer industry. > Emotional responses are irrational, yes, but that is what "promotion" is about. Simply making information easily available for rational decision-making promotes use, but that's not "promotion" in the sales department sense of "pushing" sales. I suspect this distinction is at the root of some of the "furor." My concern is that Python will be "sold" on some basis other than its many objectively solid merits. (Of course, the merits of interest to software developers and to business executives are not identical. Success stories will interest the latter more than metaclasses and mro. So a single portal page for all must lead easily to resources of interest to all on first encounter. As has been mentioned, developers will no doubt bookmark dev.python.org or whatever becomes the main page for developers, so the home page now becomes a matter of balanced PR and well thought out top level indexing). Photographs of people in role settings serve to trigger identification/wannabe responses (sometimes the role is in relation to the depicted rather than the depicted's role). (So why don't we have a picture of a hot Victoria's-secret model as businesswoman in a hot roadster giving a ride to an Armani-dressed(?) geek with an armload of Python books? And maybe work in a collage of success-reward recreation resort images for subliminal background effect? Sex, food, energy to squander -- buy it, buy it! ;-) I'm not quite immune ;-) But what is the goal here? >For those still commenting on the contrast issue, please >understand that there are accessibility guidelines that >suggest a use of 70% contrast in order to maximise readability >for all users. Hopefully a minor adjustment issue. > >These are my last comments on the comp.lang.python mailing list. >If anyone wants to continue the disucssion and really help to >create/promote Python, please move to either > I can hardly keep up with c.l.py, never mind more ;-/ >http://pythonology.org/mailman/listinfo/marketing-python > >or > >http://pythonology.org/mailman/listinfo/py-design-forum > >The second list if it's website or design related. > Hope my reactions are useful data. Regards, Bengt Richter From roy at panix.com Fri Sep 5 13:46:31 2003 From: roy at panix.com (Roy Smith) Date: 5 Sep 2003 13:46:31 -0400 Subject: OT: best book in years References: Message-ID: In article , Mark Jackson wrote: >Patrick Useldinger writes: >> Hi All, >> >> I am going to stay in hospital for a week or so (nothing serious), and am >> trying to find a book or two to read there. As I have not come across >> anything spectacular recently (except Python in a Nutshell), I would like >> to know what *you* consider to be the best book you have read in the last >> few years, about Python or IT in general. > >/The Mythical Man-Month/. When you're done with that, try Ed Yourdon's "Death March". From jwdillworth at yahoo.com Fri Sep 12 14:37:22 2003 From: jwdillworth at yahoo.com (Jeremy Dillworth) Date: Fri, 12 Sep 2003 11:37:22 -0700 (PDT) Subject: date formatting In-Reply-To: Message-ID: <20030912183722.65252.qmail@web41109.mail.yahoo.com> This works, with Python 2.3: from datetime import datetime datetime.fromtimestamp(os.stat('thefile').st_mtime).strftime('%y%d%m') It leaves out the call to localtime, but now you're constructing a datetime object, so it's really not more direct. Some may find it more readable, or at least I think it is, er... well slightly :) On Linux os.stat() returns an object of type posix.stat_result, I wonder if this type could be enhanced so that one could do this: os.stat('thefile').mdatetime.strftime('%y%d%m') (mdatetime returning a datetime object) Naturally we'd probably want os.stat('thefile').cdatetime and so on too... --- WmGill wrote: > I want to write a script that Among other things) renames a file based on > it's timestamp. > I can get the date info using > "strftime('%y%m%d',localtime(os.stat('thefile')[ST_MTIME])", but this seems > like a long way around the block. Is there a more direct way? > > Bill > > > -- > http://mail.python.org/mailman/listinfo/python-list From tzot at sil-tec.gr Mon Sep 29 19:03:30 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 02:03:30 +0300 Subject: build a static python executable on linux? References: Message-ID: On Mon, 29 Sep 2003 15:42:34 -0700, rumours say that Alexandre Gillet might have written: >I am trying to build a python interpreter that is static link. >My python interpreter was build on RedHat 8.0 using gcc 2.3 and GLIBC 2.3 >When running on other linux flavor that still have GLIBC 2.2, the >interpreter won't start. (error message: /lib/libc.so.6: version >`GLIBC_2.3' not found (required by /mgl/python/i86Linux2/bin/python2.3) I believe you should install the glibc-static-devel package and then find the approprate options for gcc (my noisy linux computer is turned off now so I can't man gcc, but IIRC is -static :) in order to build a static python. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From newsgroups at jhrothjr.com Sat Sep 20 20:13:22 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Sep 2003 20:13:22 -0400 Subject: What is the meaning of the astarisk in Python References: <3f6ce54f$0$10962$fa0fcedb@lovejoy.zen.co.uk> Message-ID: "John Dean" wrote in message news:3f6ce54f$0$10962$fa0fcedb at lovejoy.zen.co.uk... > Hi > Below is a line taken from Andy Dustman's MySQLdb module: > def Connect(*args, **kwargs): > > I would be grateful if somebody explain the meaning of the astarisks, since > I was under the impression that pointers are not used in Python and the > above look very must like pointers to me One asterisk creates a list of all positional arguements, two asterisks creates a dictionary of all keyword arguements. "All" means "not otherwise represented in the parameter list." John Roth > > -- > Best Regards > John From nitram2000 at videotron.ca Sun Sep 21 13:29:46 2003 From: nitram2000 at videotron.ca (Martin) Date: Sun, 21 Sep 2003 13:29:46 -0400 Subject: how to find a user in a xml document Message-ID: hi, I need to find a way to check in a XML document if a certain user exist, if not i want to add it in the document. I am able to add it in the xml doc, but I cant make sure he doesnt exist thanks Martin From aahz at pythoncraft.com Thu Sep 25 16:42:15 2003 From: aahz at pythoncraft.com (Aahz) Date: 25 Sep 2003 16:42:15 -0400 Subject: "for" with "else"? References: Message-ID: In article , Michael Geary wrote: > >The use case that Alex just posted gave me another way to think about it: > > for item in allitems: > if fraboozable(item): > print "first fraboozable item is", item > break > else: > print "Sorry, no item is fraboozable" > >If I think of the else statement as being related to the if statement >inside the loop, then it makes some sense--the else statement is >executed when the if statement never comes up true. (It's twisted >logic, I know, but at least it helps me keep track of what "else" does >here.) Maybe it's twisted logic, but it's the only time I've ever used for/else in real code. It helps if instead of thinking of the else as connected to the if, you think of the entire for loop as being an extended if statement. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From jdhunter at ace.bsd.uchicago.edu Mon Sep 22 16:35:22 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 22 Sep 2003 15:35:22 -0500 Subject: pyopengl / python2.3 / win32 Message-ID: Does anyone have a a windows installer for pyopengl built for python2.3 on win32 that they can send me, or a link? Thanks, John Hunter From paul at oz.net Tue Sep 23 18:55:22 2003 From: paul at oz.net (Paul) Date: 23 Sep 2003 22:55:22 GMT Subject: How to catch socket timeout? References: <3F6DD4D7.AF309B4@hotmail.com> Message-ID: What's the best way to do this under Python 2.1? I believe socket.timeout was a 2.3 feature. Wrap it in threads? I'd like to do something similar for the Gibraltar Linux firewall CD, but it only comes with Python 2.1. Many thanks in advance. -- Paul From ceiesa at excite.com Sat Sep 27 21:18:15 2003 From: ceiesa at excite.com (Bruce Dickey) Date: Sat, 27 Sep 2003 19:18:15 -0600 Subject: Meta programming question Message-ID: Hi, I've read a number of the meta progamming articles. I have not found what I am looking for. I want to override assignments to variables which are in the module namespace (not object members -- no classes involved). Can this be done? Thanks, Bruce From pythonguy at Hotpop.com Wed Sep 3 05:48:00 2003 From: pythonguy at Hotpop.com (Anand Pillai) Date: 3 Sep 2003 02:48:00 -0700 Subject: python + mplayer References: <9d302332.0309020740.29ee6613@posting.google.com> Message-ID: <84fc4588.0309030148.2e9078b7@posting.google.com> Reminds me of something I wanted to do for mplayer, i.e writing an ncurses interface for it. Python has a curses module which I am planning to use. I have not started working on this, but will start sometime soon. -Anand Jim Dabell wrote in message news:... > Mike Zupan wrote: > > > I'm wondering if anyone has a link or made a script to control mplayer > > via python. I'm aware that freevo does it but I don't wanna debug > > their code to figure it all out. I'm looking for something very simple > > that can get me started in controlling mplayer in a python app. I'd > > like to get a movie into a pygame app i'm doing. > > should have everything you need, > specifically . From dave at boost-consulting.com Fri Sep 26 12:44:41 2003 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 26 Sep 2003 12:44:41 -0400 Subject: PEPs link gone from the Python homepage? In-Reply-To: <16244.22946.446379.622160@montanaro.dyndns.org> (Skip Montanaro's message of "Fri, 26 Sep 2003 10:22:10 -0500") References: <16244.22946.446379.622160@montanaro.dyndns.org> Message-ID: Skip Montanaro writes: > David> Since a significant part of Python is only documented in PEPs, I > David> am disappointed to see that they can't be easily found. Where > David> are they? > > Dave, > > Try the left margin of the /dev/ page. Thanks. I was looking for /dev/, too, but I always forget to scan the top. Eventually I got there from the search page. > If you find stuff in PEPs you believe belongs in the standard > documentation set, please file a documentation bug report. Oof. MRO, descriptors, most of PEPs 252 and 253 last time I checked, just off the top of my head. Do I you really think it would make a difference to *formally* point out that many elements of the basic design of the object model aren't in the docs? And, this is not a rhetorical question: how many bug reports would be appropriate for all of this information? Some of these PEPs cover several topics. > While PEPs do contain a lot of valuable information, I don't think > that using them for end-user documentation was a goal. Sure, I knew that, but while the docs are still incomplete, you use what you can, and it would be nice to be sure that the information was readily accessible. -- Dave Abrahams Boost Consulting www.boost-consulting.com From usenet_spam at janc.invalid Fri Sep 12 09:25:06 2003 From: usenet_spam at janc.invalid (JanC) Date: Fri, 12 Sep 2003 13:25:06 GMT Subject: OT: Americans love their guns References: Message-ID: Arthur schreef: > This Septmeber 11. I vote for an amendment to Godwin's Law... "As a Usenet discussion grows longer, the probability of a comparison involving Nazis, Hitler OR SEPTEMBER 11 approaches one." -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From bmproj2003 at yahoo.com Mon Sep 29 03:30:22 2003 From: bmproj2003 at yahoo.com (drn) Date: 29 Sep 2003 07:30:22 GMT Subject: query Message-ID: <2003929-93022-80040@foorum.com> sir/madam, as we are going to develop a educational s/w for children at preprimary level we are facing some problems in deciding what platform to choose and what s/w to use. so please help. -we have more of graphics work. -we have two students working simutaneously on one system. -we will be having 4-5 systems in total in one classroom. -----shall we go for one system as a linux sever with somewhat higher configuration and rest as terminals (lower configuration)and each terminal connected to the server. what configuration do you suggest which is reasonable and sufficient. or -----shall we go for individual terminals with Linux 7.3, and with a minimum of around 600 MB of free space,Minimum requirement for RAM 32 MB. (Not less than this),Minimum requirement for Hard Disk 2.1GB,There will be no networking even among machines at one location. -----which lanuage do you suggest - c/c++ or any browser based software like php/python. please help and send your suggestions as soon as possible. my email id is bmproj2003 at yahoo.com thanks and regards DRN -- Ce message a ete poste via la plateforme Web club-Internet.fr This message has been posted by the Web platform club-Internet.fr http://forums.club-internet.fr/ From staschuk at telusplanet.net Mon Sep 1 01:04:28 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 31 Aug 2003 23:04:28 -0600 Subject: Python Documentation? In-Reply-To: ; from smory@ptdprolog.net on Mon, Sep 01, 2003 at 12:41:14AM -0400 References: Message-ID: <20030831230428.A2521@tibia.amotlpaa.bogus> Quoth Daniel R. Smorey Jr.: > I'm looking for a good place for Python documentation. I'm really lost > on why it's so hard to find anything when it comes to me looking up a > particular function in Python. My example would be the split() function > of the string module. [...trouble searching for it at python.org...] For full-text searches, try . For functions and whatnot, there's the index of the Library Reference, . [...] > Most of those hits are for the re module, not the string module (which > in my opinion should be part of python and not a module, but I digress). Indeed, in sufficiently recent Pythons (2.0+, I think), split() is a method of string objects: >>> 'foo bar'.split() ['foo', 'bar'] Likewise for many other functions in the string module. (This method is the second hit for "split" at pydoc.org, and is listed in the Library Reference index.) -- Steven Taschuk "The world will end if you get this wrong." staschuk at telusplanet.net -- "Typesetting Mathematics -- User's Guide", Brian Kernighan and Lorrinda Cherry From skip at pobox.com Thu Sep 4 17:52:49 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 4 Sep 2003 16:52:49 -0500 Subject: quick and smart way for parsing a CSV file? In-Reply-To: <731fc603.0309041328.4e83f8ab@posting.google.com> References: <731fc603.0309031242.4e5493ce@posting.google.com> <3F5656CA.519ABADF@easystreet.com> <731fc603.0309041328.4e83f8ab@posting.google.com> Message-ID: <16215.46129.135630.636460@montanaro.dyndns.org> >> where would i get this csv module from? does it come with python 2.2? >> thanks It comes with Python 2.3. If you grab the csv and _csv modules from the Python 2.3 CVS repository, they should build and run under 2.2.x. If that's not possible, poke around for Object Craft's csv module. Skip From gh at ghaering.de Tue Sep 9 05:21:54 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 09 Sep 2003 11:21:54 +0200 Subject: set built-in func_code? In-Reply-To: <3F5D9A9E.1000305@ghaering.de> References: <3F5D9A9E.1000305@ghaering.de> Message-ID: <3F5D9BB2.4020705@ghaering.de> Gerhard H?ring wrote: > Birgit Rahm wrote: >> I want to set the built-in func_code in my function, how can I does >> this in the correct way? > > I don't think that's possible for an existing function object. [...] Well, maybe I should try before I post: #v+ >>> def f(): print 5 ... >>> def g(): print 6 ... >>> f.func_code = g.func_code >>> f() 6 #v- This is an unnecessary hack, IMO. Hacks aren't bad, but unecessary ones are, IMO. Still, what are you trying to achieve? -- Gerhard From newsgroups at jhrothjr.com Mon Sep 15 11:57:28 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 15 Sep 2003 11:57:28 -0400 Subject: Multiple instances of modules References: Message-ID: "Daniel Pryde" wrote in message news:cf5c25e9.0309150733.4543eada at posting.google.com... > Hi there. > > I'm currently trying to learn Python, my aim being to create my final > year project at university using only Python instead of Java. I've run > into a problem though while trying to make multiple instances of > modules. > > For example, say I made a CD.py module which held details of an audio > compact dic (album name, track names, etc..), and wanted my Python > script to make a record collection using multiple CD's, I can't make > them seperately. I tried using the 'import module as name' format, but > any changes made to one instance affects the other. I assume this is > because Python is simply referencing the one instance of CD.py rather > than seperate ones. Is there a solution to this that doesn't involve > using cPython or Jython? Any help would be greatly appreciated. I suspect you're trying to store your data in the module itself. That's not going to work because Python only loads one copy of a module, by design. As Anton suggests, please tell us a bit more about what you're trying to do and the approach you're taking. John Roth From ruach at chpc.utah.edu Thu Sep 18 19:23:43 2003 From: ruach at chpc.utah.edu (Matthew) Date: 18 Sep 2003 16:23:43 -0700 Subject: problem with user confirmation Message-ID: I am have written a medium sized program and everything works fine except for one piece. At a certain point in the program I want to do a simple user confirmation, eg Are you sure ? y/n. The problem that I am having is that after the user enters an answer and presses enter, the program executes the rest of the code regardless of what the user response was. Heres my code: def confirmAction(self, msg): if not msg: msg = 'Are you sure y/[n]> ' print msg confirm = sys.stdin.readline()[:-1] print 'confirm = \'%s\'' %(confirm) if confirm == 'y' or 'Y' or 'Yes' or 'YES' or 'yes': return 1 return 0 if confirmAction('Are you sure you want to DEACTIVATE this port? y/[n]'): print 'Deactivating #Do some other stuff else: sys.exit(-1) At this point in the program I can enter nothing, or y, or sdfasd, and no matter what I do it prints 'Deactivating and executes the rest of my code. I can't figure it out to save my life. I am sure that the answer is very simple and that I have just been thinking to hard and have over looked it. Thanks for any help -matthew From skip at pobox.com Fri Sep 12 16:36:48 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 12 Sep 2003 15:36:48 -0500 Subject: formatting number in the CSV module In-Reply-To: <8dad5312.0309120319.13bc9062@posting.google.com> References: <8dad5312.0309120319.13bc9062@posting.google.com> Message-ID: <16226.11872.527476.467886@montanaro.dyndns.org> Sebastien> I need to output numbers to a csv file and use the new csv Sebastien> module in python2.3: Sebastien> " Sebastien> import csv Sebastien> data = [[ 0.321524523,0.5243523],[0.54635643,0.62776]] Sebastien> w = csv.writer(file("out.csv","w")) Sebastien> w.writerows(data) Sebastien> " Sebastien> However, I would like to format the number so that only the Sebastien> first 2 decimals are stored in the csv file. There's nothing built into the csv module. You can format the floats before passing them to the writer however: >>> import csv >>> data = [[ 0.321524523,0.5243523],[0.54635643,0.62776]] >>> w = csv.writer(file("out.csv","w")) >>> for row in data: ... row = ["%.2f"%f for f in row] ... w.writerow(row) ... >>> montanaro:tmp% cat out.csv 0.32,0.52 0.55,0.63 Skip From me at privacy.net Sat Sep 20 21:17:29 2003 From: me at privacy.net (Heather Coppersmith) Date: 20 Sep 2003 21:17:29 -0400 Subject: None??? References: Message-ID: On Sun, 21 Sep 2003 01:12:04 GMT, "News" wrote: > I just started using python a few weeks ago. This is my first > program. You input your income and what percent you want to save > then it tells you how much to put away. The the code works, but > it puts in the word "none" after it calls the function. Is the > call sytax incorrect? I'd appreciate any feedback you could > offer . [ ... ] > weekly_income = income/52 > def compute(income, percent): > result = income*percent/100 > print result Note that this function prints its result and then returns None. > print "Ok,",first_name + " " + last_name > print > print "This is how much you should put away a week:" > print "$",compute(weekly_income, percent) OTOH, it looks like this print statement expects the function to return its result. > print > print "If you stick to this you will go places!!! :-)" The simplest (and most general) solution would seem to be to define the function to return its result: define compute(income, percent): result = income * percent / 100 return result Then the print statement will work as written. Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From pcolsen at comcast.net Mon Sep 1 12:29:33 2003 From: pcolsen at comcast.net (Peter Olsen) Date: 1 Sep 2003 09:29:33 -0700 Subject: Advice to a Junior in High School? References: <3d6c6fc3.0308261246.32db39d5@posting.google.com> Message-ID: soundinmotiondj at yahoo.com (Stan Graves) wrote in message news:<3d6c6fc3.0308261246.32db39d5 at posting.google.com>... > "Howard Nease" wrote in message news:... Stan Graves and Howard Nease shared the following exchange. I'd like to add my two cents. > > I would be devastated were I to find the need to leave computer science. .... > > Does anyone have any advice for me and my future? ... > > What should I study in > > college? > > You should learn to think and to learn in college. ... > Study literature - I have yet to see a single computer scientist who > can manipulate symbols as well as Shakespeare. .... > > What languages do you suggest that I > > study (I'm already studying Python)? > > I'd suggest English. The ability to communicate effectively is > probably more important than any technical skill. > ... > --Stan Graves Howard, Stan has already given you some excellent advice. I'd like to add some more. I believe that all of education comes down to learning two languages: whatever you speak at the dinner table and mathematics. My dinner-table language is English; perhaps yours is as well. This is the language we use to talk about what makes us human: our hopes, our fears, our loves, our hates, and our passions. You will use this language to court your partner, lead your peers, and console your family and friends. Master it. Use it with precision. As Stan wrote, read Shakespeare. Read Churchill for his prose. Read poetry. (I like Robert Service, plain though he may be.) To work in a technical field you must write about technical things. Read Paul Halmos' and Gil Strang's books on mathematics. Read "The Structure and Interpretation of Computer Programs" by Hal Abelson and Gerald J. Sussman. (This is the best computer science book --- and perhaps the best technical book --- I have ever read.) Don't worry about mastering the details, concentrate on the elegance and precision of their description. Ideas lost your head are useless; ideas on paper, but not understood, are tragic. Buy the "Elements of Style" by Strunk and White. Keep it handy. Read it. (I keep a copy close to the bathroom.) Write simple sentences. Use short words. These things are harder than they seem. Improve your vocabulary. Excise abstruse words. Churchill wrote "Short words are best, and the old words, when short, are best of all." He was right. Just as your dinner-table language lets you describe the inside world that makes you human, mathematics lets you describe the outside world in which you live. Mathematics lets us reason with precision. Here I use the word "mathematics" to include almost any formal system for quantitative reasoning. I recommend that you learn all the traditional mathematics you can. Take what courses you can. Mathematics has helped me learn engineering, economics, and computer science. (It has also helped me write good English.) Still, you can learn your mathematics the other way around. Studying economics, physics, engineering, and computer science can teach you what you need. (I've found studying algorithms a particularly good way to do this.) One of my friends --- and also David Mertz of Python fame --- appear to have done it by studying philosophy. Over all, the purpose of education is not to get a job, but to understand the world and your place in it. A few of the best educated people I have known were barely High School graduates; a few of the worst have PhDs. And when you're done, stop. Peter Olsen, AeE., P.E. pcolsen at comcast.net "Engineering is the art of using a professional knowledge of mathematics and the physical sciences to improve the quality of life." From jepler at unpythonic.net Sun Sep 28 10:13:41 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 28 Sep 2003 09:13:41 -0500 Subject: Meta programming question In-Reply-To: References: Message-ID: <20030928141340.GA18261@unpythonic.net> The changes are not large, if I understand what the OP is asking for. However, they have a performance impact on the "common case". In Python, a dict subclass's __setitem__ is never invoked when evaluating bytecode. With a change to just a few opcodes (STORE_GLOBAL, STORE_NAME), this can be rectified, so that >>> exec "x = 3" in d will call d.__setitem__("x", 3), and you can do whatever you need to do on "assignment". The patch was never finished, and never added to the sf patch manager. You can visit the python-dev thread at http://mail.python.org/pipermail/python-dev/2002-October/029761.html Jeff From buzzard at urubu.freeserve.co.uk Fri Sep 5 15:11:37 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 5 Sep 2003 20:11:37 +0100 Subject: Selecting elements from a list References: <87y8x4w6ym.fsf@gvdnet.dk> <87brtzu5ak.fsf@gvdnet.dk> <87znhjw4r1.fsf@gvdnet.dk> Message-ID: "Martin Christensen" wrote in message news:87znhjw4r1.fsf at gvdnet.dk... > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > >>>>> "Duncan" == Duncan Smith writes: > Duncan> Computer Science at Aalborg I see. A Bayes net man perchance? > Duncan> I hope Uffe, Kristian et al are well. :-) > > Haha! If you're talking about the guys I'm thinking of, I just came > home from a lovely Friday afternoon beer with them. :-) And yes, I > happen to be doing a project involving Bayesian networks, but I'm > originally a database guy. To keep it relevant, I did my masters > thesis implementation stuff in Python and am very happy I did. > > Martin > Yes, messrs. Kjaerulff and Olesen. All my Bayes net stuff is in Python. I must tidy it up (and rewrite my Digraph class) so I can make it available. Duncan From max at alcyone.com Wed Sep 10 16:04:01 2003 From: max at alcyone.com (Erik Max Francis) Date: Wed, 10 Sep 2003 13:04:01 -0700 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> Message-ID: <3F5F83B1.48763F85@alcyone.com> Stephen Horne wrote: > Its not an issue of whether the same effect can be achieved in Python. > It's more an issue of whether the method used expresses the > programmers intentions properly. I agree. And with your suggestion, now every single function call can potentially change meaning. Given Python's dynamicism, you may not even know if this particular function call exhibits the behavior. Now Python's nice, predictable behavior is up for grabs. If you want to rebinding outside the function, a far better way of "expressing the programmer's intentions properly," in my opinion, is to make the behavior as explicit as possible: class Container: def __init__(self, x=None): self.x = x def get(self): return self.x def set(self, x): self.x = x def increment(self): self.x += 1 # for example def Inc(c): container.increment() container = Container(1) Inc(container) print container.get() -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Dead men have no victory. \__/ Euripides From jacek.generowicz at cern.ch Fri Sep 5 08:31:27 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Sep 2003 14:31:27 +0200 Subject: basic language question References: Message-ID: Stephan Diehl writes: > Stephan Diehl wrote: > > > Terry Reedy wrote: > > > >> 'Returners' could wrap no-return mutators with functions or > >> derived-class methods that do return the object, but I have never seen > >> anyone post a complete module that does so for, say, all list > >> mutators. > > > > That's actually a nice idea. I might just do that. > > o.k., the following short code would give you a list class, that returns > 'self' when invoking any of the mutating methods. OK, here's a variaton on the theme, just wraps the object in-place in a way which makes it return self. This way you can get the desired effect on any object you get, without pre-meditation, so you can still fit the call chain on one line (wasn't that the point?) > The solution involves a metaclass Mine avoids them altogether. > and I wouldn't consider this code more as an example than an > industrial strength solution Ditto. class returner: def __init__(self, object): self.object = object def __getattr__(self, name): def proxy(*args, **kwds): getattr(self.object, name)(*args, **kwds) return self.object return proxy lst = [1,2,3] print lst.append(4) # Here you get None print returner(lst).append(5) # Here you get the modified list. From llafba at gmx.net Fri Sep 12 12:34:22 2003 From: llafba at gmx.net (Tom) Date: Fri, 12 Sep 2003 18:34:22 +0200 Subject: read from file In-Reply-To: References: Message-ID: Hi Jeremy, that helps a lot! The data is being appended so your hints are very usefull to me! Thank you very much. Tom From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 24 02:21:02 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 24 Sep 2003 07:21:02 +0100 Subject: Pre-PEP: reverse iteration methods References: Message-ID: On Wed, 24 Sep 2003 02:13:48 GMT, "Andrew Dalke" wrote: >> Frankly, I prefer the notion of a method. > >While I don't. To me, the reason to use a method (or property) is simply that most types cannot be efficiently 'backwardised'. For instance, iterators in general would have to be buffered into a list an then the resulting list iterated backwards. That could be useful, but the overhead is sufficient that I think explicitly writing 'list (x).backward ()' rather than 'x.backward ()' would be a good thing. Having a method (or property) explicitly associates it with the object/class being handled. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From Mike at DeleteThis.Geary.com Tue Sep 9 00:52:59 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 8 Sep 2003 21:52:59 -0700 Subject: Ternary operator References: Message-ID: Timothy Delaney wrote: > FWIW, I definitely fall in the "would not oppose" group, and not > the "actively want" group. I prefer not to use a ternary operator > in any language. My bias may well be affecting my understanding. That certainly would make a difference. I'm in just the opposite camp, being someone who uses the ternary operator very frequently in C++. So I really miss it in Python. But I'd still take Python without the ternary operator over C++ with it! :-) -Mike From CousinStanley at hotmail.com Mon Sep 1 22:02:56 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Mon, 1 Sep 2003 19:02:56 -0700 Subject: TKinter is driving me crazy! References: <3285.208.224.10.29.1062445601.squirrel@webmail.iserv.net> Message-ID: | import Tkinter as tk | | class GuessWidget(tk.Frame): | def __init__(self, value, *args, **kw): | | tk.Frame.__init__(self, *args, **kw) | .... Jp .... Thanks for posting this example script .... How does one change the title of the sub-classed frame ???? -- Cousin Stanley Human Being Phoenix, Arizona From max at alcyone.com Tue Sep 9 04:07:41 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 09 Sep 2003 01:07:41 -0700 Subject: Jython class names References: Message-ID: <3F5D8A4D.DC5F1281@alcyone.com> Robin Becker wrote: > I recently came across a problem with porting to Jython > > basically the following is prints 1 in CPython, but not in Jython. > > class C: > pass > > red = C() > print red.__class__.__name__ is 'C' > > it seems that Jython doesn't intern names in the same way or instances > are not constructed in the same way. Is the above test robust or > should > I always be using == for testing class names? You should be testing string equality with ==. Whether two strings that are equal are actually the same string (is) is an implementation detail. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ I sidestep the either/.or choices of logic and choose both. \__/ Ken Feit From tomas.kukosa at siemens.com Thu Sep 18 09:35:19 2003 From: tomas.kukosa at siemens.com (Tomas Kukosa) Date: Thu, 18 Sep 2003 15:35:19 +0200 Subject: ASN.1 source reader Message-ID: <3F69B497.CEF764ED@siemens.com> Hello, does anybody know any way how to read ASN.1 source into Python? I can not find any ASN.1 parser. The next way can be ASN.1 -> XML -> Python but I did not find any ASN.1 -> XML convertor which keeps all ASN.1 information in XML. E.g. ASN2XSD tool from obj-sys.com loses information about extension mark position. Thanks, Tom From achrist at easystreet.com Tue Sep 9 12:52:13 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Tue, 09 Sep 2003 09:52:13 -0700 Subject: My future Python IDE article References: <3f5dec0d@news.comindico.com.au> Message-ID: <3F5E053D.743DA13A@easystreet.com> Tom Lee wrote: > > JEdit is fantastic. > I found it very good, too. I was using it for a large project in Python about 6 mos back, and despite the sluggish response on my 200 MHz machine, I had it open on my desktop continuously for a couple of weeks, with dozens of files open. But then it gave me a bad crash -- I don't recall exactly what -- maybe a BSOD or a JVM crash. That's not the kind of thing I enjoy, so I haven't used it since. Anyone else have trouble like that with jEdit? Al From tzot at sil-tec.gr Wed Sep 24 13:09:49 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 24 Sep 2003 20:09:49 +0300 Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> <3f71395d-46f08129-996a-495d-a5ee-05fb1caef6e9@news.szn.dk> Message-ID: On Wed, 24 Sep 2003 09:52:45 -0400, rumours say that Fran?ois Pinard might have written: >> This will yield a false positive and potential damage if the OS has >> spawned another process with the same pid, and running under your uid, >> as the task you wanted to supervise. > >Granted in theory, yet this does not seem to be considered a real >problem in practice. To generate another process with the same pid, the >system would need to generate so many intermediate processes that the >process counter would overflow and come back to its current value. The >`kill(pid, 0)' trick is still the way people seem to do it. > >Do you know anything reasonably simple, safer, and that does the job? Not that simple: a semaphore. Not that safe: the existence of a semaphore file. kill(pid,0) is ok; but a pipe and select would be useful too, safe and relatively simple (for old Unix programmers at least :). -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From achalk at XXXmagnacartasoftware.com Mon Sep 8 00:19:11 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Mon, 08 Sep 2003 04:19:11 GMT Subject: Ternery operator References: <3F5B6404.BD1A9709@engcorp.com> Message-ID: <3rT6b.553$HQ7.398@newssvr23.news.prodigy.com> Wow! bang on topic. Thanks! "Peter Hansen" wrote in message news:3F5B6404.BD1A9709 at engcorp.com... > Andrew Chalk wrote: > > > > Is there a python equivalent of the C ternery operator? > > See http://www.python.org/cgi-bin/faqw.py?query=4.16&req=search From joerg_k76 at ___gmx.at Wed Sep 10 11:01:18 2003 From: joerg_k76 at ___gmx.at (=?ISO-8859-1?Q?J=F6rg_Keller?=) Date: Wed, 10 Sep 2003 17:01:18 +0200 Subject: passing object via REQUEST-object Message-ID: hi this is a Zope-related python problem. I hope, this is not too OT! I use a html-form that calls a python script as it's action. The form contains " name="path"> In the script I can do stuff like my_path=context.REQUEST.form['path'] print my_path which returns - as expected - 'folder instance at xxxxxx' But when I try print my_path.id I get an AttributeError 'id' Any hints? Regards J?rg From llothar at web.de Fri Sep 19 09:41:18 2003 From: llothar at web.de (Lothar Scholz) Date: 19 Sep 2003 06:41:18 -0700 Subject: Python ISPs References: <924a9f9c.0309181224.374a5bef@posting.google.com> Message-ID: <6ee58e07.0309190541.691b842d@posting.google.com> "Ulrich Petri" wrote in message news:... > "Paradox" schrieb im Newsbeitrag > news:924a9f9c.0309181224.374a5bef at posting.google.com... > > Does anyone know of some ISPs that have Mod_Python installed. Most > > seem to allow Python CGI but not things like Mod_Python or Spyce. Is > > this a viable solution or should I just learn PHP. I would prefer to > > leverage my Python knowledge but I also would like a fast robust > > solution. > > You could go for one of those virtual servers all for yourself... > Most (all !?) of this virtual servers are the worst i've ever seen. Putting 100 customers on a 1 GB 2x2 GHz maschine is not a good thing if everyone must install there own MySQL,Apache etc. From jjl at pobox.com Thu Sep 4 12:44:07 2003 From: jjl at pobox.com (John J. Lee) Date: 04 Sep 2003 17:44:07 +0100 Subject: Where to post useful code References: <2e1f6497.0309040646.3dcce9fb@posting.google.com> <3f575667@usenet01.boi.hp.com> Message-ID: <87d6egijvs.fsf@pobox.com> djw writes: > RichB wrote: > > I've written a few scripts that might be very useful to small groups > > of people (i.e. extracting time stamps from pictures taken with Sony [...] > http://www.uselesspython.com/ The other place is the ActiveState Python Cookbook. John From skip at pobox.com Wed Sep 10 11:35:47 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 10 Sep 2003 10:35:47 -0500 Subject: Redesign of Python site In-Reply-To: <200309100540.h8A5epgD030889@localhost.localdomain> References: <3F5EB3C1.6020107@teksavvy.com> <200309100540.h8A5epgD030889@localhost.localdomain> Message-ID: <16223.17619.543739.675680@montanaro.dyndns.org> >> From the most recent stats, the top 20 entry pages: Anthony> Hits Visits URL Anthony> 1 252455 3.60% 164578 44.76% / Anthony> 2 169489 2.42% 20381 5.54% /pypi Anthony> 3 66001 0.94% 7997 2.18% /2.3/ Anthony> 4 47542 0.68% 7664 2.08% /doc/ Anthony> 5 25401 0.36% 7049 1.92% /doc/current/tut/tut.html Anthony> 6 39856 0.57% 5825 1.58% /download/ ... It's not too surprising that the home page is the most common entry point. It's probably the most widely advertised Python URL. I think the top URLs list is more telling: hits URL 1 2375287 33.91% Documentation 2 423653 6.05% CGI Scripts 3 257043 3.67% Python News (RDF) 4 252455 3.60% / 5 177496 2.53% PyPI ... While "Documentation" covers a lot of URL ground, it still suggests that's the most common use of the website by a long shot. I think Fred Drake deserves a raise! Skip From daniel.dittmar at sap.com Thu Sep 11 11:32:10 2003 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 11 Sep 2003 17:32:10 +0200 Subject: OT: Americans love their guns References: <16223.15950.299463.959577@montanaro.dyndns.org> <000b01c37824$c972de10$3a0ff10c@teaset> Message-ID: Skip Montanaro wrote: > Why is this on c.l.py anyway? Wasn't 'gun' just an allegory for using Perl? Daniel From jakle1 at hotmail.com Sat Sep 27 20:55:30 2003 From: jakle1 at hotmail.com (News) Date: Sun, 28 Sep 2003 00:55:30 GMT Subject: Tutor Message-ID: <6kqdb.146$Vb3.97520@news1.news.adelphia.net> Hello. I've just started learning Python a few weeks ago. I'm using the free "How to Think Like a Computer Scientist: Learning with Python". I'm half-way through chapter 5 and I've been stumbling on a few things. I've been teaching myself so far. I was wondering if anyone out there would be able to help me along with this. Maybe help explain some things and give me ideas for practice programs that go along with what I'm learning. And if you can't help directly, maybe someone out there can point me towards somewhere that I can get help. ok, I've talked enough. Thank you all in advance. From mal at lemburg.com Wed Sep 17 14:01:58 2003 From: mal at lemburg.com (M.-A. Lemburg) Date: Wed, 17 Sep 2003 20:01:58 +0200 Subject: [egenix-users] mx.DateTime bogus warning: "float where int expected" In-Reply-To: <3F68930A.CD2E4C63@noaa.gov> References: <33436.199.169.240.132.1063814659.squirrel@svr1.turboweb.net> <3F68930A.CD2E4C63@noaa.gov> Message-ID: <3F68A196.6010907@lemburg.com> Jim Vickroy wrote: > I do not have an explanation, but the statement: > > dt = self.firstdate + self.mm * int(i) > > appears to be the source of this warning. The warning only appears the first > time the statement is executed; thereafter, no warning is issued. Right, that's a Python feature. The cause of the problem seems to be that DateTime() constructor expects integers as argument and that the code in RelativeDateTime can generate floats as a result of refitting the values into proper ranges. Try adding this snippet in DateTime.py before line 585: # Refit into proper ranges: if month < 1 or month > 12: month = month - 1 yeardelta, monthdelta = divmod(month, 12) year = year + yeardelta month = monthdelta + 1 # Make sure we have integers year = int(year) month = int(month) day = int(day) if self.weekday is None: return DateTime(year, month, 1) + \ DateTimeDelta(day-1,hour,minute,second) > python at sarcastic-horse.com wrote: > > >>Hi- >> >>I'm getting a "DeprecationWarning: integer argument expected, got float" >>warning with mx.DateTime and I can't figure out why. Can anyone help me >>out? >> >>This code: >> >>import mx.DateTime >> >>class xLabeller: >> def __init__(self, firstdate,fmt='%B, %Y'): >> self.firstdate = firstdate >> self.fmt = fmt >> self.mm = mx.DateTime.RelativeDateTime(months=1) >> def __call__(self, i): >> dt = self.firstdate + self.mm * int(i) >> return dt.Format(self.fmt) >> >>nov99 = mx.DateTime.Date(int(1999), int(11)) >> >>xl = xLabeller(nov99) >>print "xl2:" >>print xl(int(3)) >> >>Produces this warning: >> >> >>>>>================================ RESTART =========== >>>>> >> >>xl2: >>C:\Python23\lib\site-packages\mx\DateTime\DateTime.py:585: >>DeprecationWarning: integer argument expected, got float >> return DateTime(year, month, 1) + \ >>February, 2000 >> >>What is the story? I've wrapped every number in my program with int(). I >>can't figure out what's triggering the warning. >> >>And, even stranger, the whole thing works fine at the python shell: >> >> >>>>>import mx.DateTime >>>>>mm = mx.DateTime.RelativeDateTime(months=1) >>>>>nov99 >> >> >> >>>>>dt = nov99 + mm * 3 >>>>>dt.Format('%b, %y') >> >>'Feb, 00' >> >>What am I doing wrong? >> >>Thanks for the help. >> >>_______________________________________________________________________ >>eGenix.com User Mailing List http://www.egenix.com/ >>http://lists.egenix.com/mailman/listinfo/egenix-users > > > > _______________________________________________________________________ > eGenix.com User Mailing List http://www.egenix.com/ > http://lists.egenix.com/mailman/listinfo/egenix-users -- Marc-Andre Lemburg eGenix.com Professional Python Software directly from the Source (#1, Sep 17 2003) >>> Python/Zope Products & Consulting ... http://www.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From mike at bindkey.com Thu Sep 4 20:59:42 2003 From: mike at bindkey.com (Mike Rovner) Date: 4 Sep 2003 17:59:42 -0700 Subject: sed with python References: Message-ID: <9e45094b.0309041659.2ceb0f2a@posting.google.com> "David Raleigh Arnold" wrote in message news:... > On Wed, 27 Aug 2003 19:26:36 +0200, U. N. Owen wrote: > > > > > David Raleigh Arnold enlightened us with: > >> How do I use python as a wrapper for sed and/or gawk scripts? > > > > You don't. Python can do anything sed and awk can, and much, much more. > > Is there an equivalent to "tac" already written as a > function in python? It's trivial easy in latest (2.3) Python. If your filesize is relatively small and you don't use fancy options, than: import sys for name in sys.argv[1:]: inpfile = name=='-' and sys.stdin or file(name) lines=inpfile.readlines() sys.stdout.writelines(lines[::-1]) HTH, Mike From tim at remove_if_not_spam.digitig.co.uk Fri Sep 19 20:05:51 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Sat, 20 Sep 2003 01:05:51 +0100 Subject: whitespace References: Message-ID: <216nmv893913qvp7bssvhia98pebt5e2p2@4ax.com> On Fri, 19 Sep 2003 19:35:54 -0400, "RR" wrote: >Is there an easy way in python to remove whitespace from a string? >From the ends or all of it? >From the ends, " hello ".strip() gives "hello" There are lstrip and rstrip if you only want to strip from one end. To get rid of all whitespace I'd probably do: import string string.join(" hello there world ".split(), "") which gives 'hellothereworld' Though there may be an easier way. From bokr at oz.net Mon Sep 29 20:48:56 2003 From: bokr at oz.net (Bengt Richter) Date: 30 Sep 2003 00:48:56 GMT Subject: isNumber? check References: Message-ID: On Mon, 29 Sep 2003 16:47:07 -0400, Rob Hunter wrote: > >On Monday, September 29, 2003, at 04:41 PM, Gerrit Holl wrote: > >> Rob Hunter wrote: >>> On Monday, September 29, 2003, at 10:20 AM, Gerrit Holl wrote: >>>> Rob Hunter wrote: >>>>> How do I check if a value is a number in Python? >>>>> >>>>> >>>>> >>>> >>>> Why do you want to do so? >>> >>> >>> I am writing an interpreter, and my parser has to decide if an >>> expression is a number or not. >> >> So you actually have a string... >> >> Maybe you could do something like this: >> >> if expr.strip("0123456789.e") == "": print "May be a number!" >> if expr.strip("0123456789") == "": print "Surely a number!" >> >> Gerrit. >> > >I don't like that solution for this particular project because, as you >say yourself, if it says yes to the second question, it only *may* be a >number. I want to know for sure. I think the type or instance checks >as the other posters mentioned are going to be fine for me. I guess you'll have to eval the string before type checking the result then, unless you are already tokenizing your input using the python tokenizer. Then you could check what it thinks, e.g., (of course you don't need all this fluff to do a check on a token t -- you don't have to retrieve the token name from token either, to check whether it is a number, e.g., >>> import tokenize, token, StringIO >>> s = '123' >>> t = tokenize.generate_tokens(StringIO.StringIO(s).readline).next() >>> t (2, '123', (1, 0), (1, 3), '123') >>> t[0]==tokenize.NUMBER True So you might want to look into letting python's tokenizer module do that part for your language, unless you have something pretty different... (obviously StringIO.StringIO(s).readline would be file('yoursource').readline and you would make more than one call to next ;-) ====< isnumtok.py >=========================================== # isnumtok.py -- check whether string is numeric token as tokenizer sees it import tokenize, token, StringIO def isnumtok(s): tnt = [(token.tok_name[t[0]],t[1]) for t in tokenize.generate_tokens(StringIO.StringIO(s).readline)] toknam, tokval = tnt.pop(0) if toknam=='NUMBER' and tokval==s: return True, ('"%s" is a number' % tokval) elif toknam=='NUMBER': return False, ('"%s" leads with the number "%s" but as a whole is not a number'% (s,tokval)) else: return False, ('"%s" is not a number, but leads with the %s "%s"'% (s, toknam, tokval)) if __name__ == '__main__': import sys for arg in sys.argv[1:]: print '%6s: %s' % isnumtok(arg) ============================================================== Some tests: [17:53] C:\pywk\clp>isnumtok.py 123 12.34 12.34e10 12.34e-10 123.456**-10 2.3j 2.3x xx +1 True: "123" is a number True: "12.34" is a number True: "12.34e10" is a number True: "12.34e-10" is a number False: "123.456**-10" leads with the number "123.456" but as a whole is not a number True: "2.3j" is a number False: "2.3x" leads with the number "2.3" but as a whole is not a number False: "xx" is not a number, but leads with the NAME "xx" False: "+1" is not a number, but leads with the OP "+" It's not really too clear what the context for your checking is. Perhaps you are analyzing expressions and bindings and trying to infer types for bindings of symbols that are NAME token in the source, but bound to objects that are NUMBER token literals in the source, etc.? Regards, Bengt Richter From duncan at NOSPAMrcp.co.uk Thu Sep 18 06:36:01 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 18 Sep 2003 10:36:01 +0000 (UTC) Subject: Multithreading and locking References: Message-ID: "Ivan Voras" wrote in news:bkbv5l$kgl$1 at bagan.srce.hr: > > Is it true what I heard (as a "rumour" of sorts), that in multithreaded > Python programs global variables are already automagically protected by > mutexes? Can someone clarify on that? > The Python interpreter holds a global mutex which is released by some methods that call the OS, and is also released sometimes between bytecode instructions. The effect of this is that any operation that takes a single bytecode instruction, and which does not call the OS, cannot be interrupted by another Python thread. It is left to the user to work out when this means a multithreaded operation will be safe. For example: x.extend(y) If x is a list, then this is safe in a multithreaded environment. If x is a user defined class and the extend method is coded in Python, then this probably isn't safe. x += y If x and y are lists, this appears superficially to be the same as the first example, however this code compiles to two bytecode instructions (an inplace add and a store), so it could be interrupted with unfortunate consequences. The bottom line is that with care you can use a list for multi-threaded queue operations, but with a Queue class already there and waiting it isn't usually worth the risk. -- 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 ville.spammehardvainio at spamtut.fi Fri Sep 26 12:30:06 2003 From: ville.spammehardvainio at spamtut.fi (Ville Vainio) Date: 26 Sep 2003 19:30:06 +0300 Subject: PyCon Announcement: Mitch Kapor is opening keynote speaker References: Message-ID: PyCon Chair writes: > and as a co-founder and the first chairman of the San Francisco-based > Electronic Freedom Foundation, and has been an active entrepreneur in It's Electronic *Frontier* Foundation, I think. -- Ville Vainio http://www.students.tut.fi/~vainio24 From randito at randito.com Thu Sep 11 17:57:55 2003 From: randito at randito.com (Randy) Date: 11 Sep 2003 14:57:55 -0700 Subject: Flash Remoting in Python? Message-ID: <7712111.0309111357.3be3b591@posting.google.com> Flash Remoting is a way for Flash applications to make "native" method calls in Action Script to a server side program, using the AMF binary format. Flash has commercial versions of a Flash Remoting servers. There are open-source alternatives for php, java, and perl. But alas, no Python. Does anyone have any interest in a project like this? It would be port for the most part; the AMF format is already well known. In addition, there is a lot of similarities between ActionScript objects and native Python objects; porting between the two data types would not be difficult. Here are some links for info. http://www.macromedia.com/software/flashremoting/ http://www.simonf.com/flap/ (perl) http://www.openamf.org/ (java) http://www.amfphp.org/ (php) http://www.actionscript.com/archives/00000485.html (discussion about python flash remoting) From newsgroups at jhrothjr.com Sat Sep 20 11:11:09 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 20 Sep 2003 11:11:09 -0400 Subject: python script as an emergency mailbox cleaner References: Message-ID: "Phil Weldon" wrote in message news:ZCZab.45450$Aq2.39773 at newsread1.news.atl.earthlink.net... > It's a worm. Worm.Automat.AGH. This is going to be a bad one. The worm > installs, among other things, an SMPT engine, searches an infected system > for email address, and sends two types of e-mail: the first is HTML and is > a fake "security patch" supposedly from Microsoft. It looks very official, > but the attachment, 104 KBytes long, is infectious. Norton Antivirus > definitions only began to identify it with the 18SEP03 manual definition > update. The worm also posts to usenet newsgroups. The other type of e-mail > is a fake notification of undeliverable e-mail. This one is a real bear. > There seem to be hundreds variations in the body content and thousands of > variations in the header. The infectious package is also about 104 KBytes. > I'm getting nearly 100 of the two types per hour. Norton Antivirus does not > detect the worm in usnet posts read by Outlook Express Newsreader or Outlook > Newsreader. Only when you attempt to open the attachment or save the > attachment to disk will Norton identify it. Norton will NOT detect the > virus in the newsgroup posts folder NOR will it detect the newsgroup folder > in a full system scan. It will not remove the infected file from the > newsgroup folder, but it will prevent execution of the vermal payload. > > Microsoft Outlook with the SP3 security update when used as your e-mail > reader protects against infection. Prior to 18SEP03 Norton did not. > > The worm is also retrieving additional variations, so you can expect the > payload size to begin changing soon. The HTML message is easy to identify; > it is always the same (so far), and includes the phrase 'Run attached file'. > The bogus 'Undeliverable e-mail' variations have no commonality but the > payload attachment (that purports to be your bounced e-mail.) This will > likley change soon. > > My guess is that the internet will not open on Monday. So far, I have seen no copies of the worm on usenet. This may be the result of my paying $$$ to a good usenet provider (Supernews.) Unfortunately, my e-mail provider got the stupid idea that "delete" meant "save a complete copy for 14 days just in case you want to see it." Most of the stuff is going into two mailboxes that I need to clean out manually every two or three hours (they're not my inbox, so the POP3 script won't do it.) It looks like two worms that just happened to hit at one time, doesn't it? John Roth From me at privacy.net Wed Sep 17 19:51:28 2003 From: me at privacy.net (Heather Coppersmith) Date: 17 Sep 2003 19:51:28 -0400 Subject: convert ints in a range to strings References: Message-ID: On Wed, 17 Sep 2003 19:02:40 -0400, hokieghal99 wrote: > Hi, > I'm trying to do this: > ------------------------------ > a="192." > b="168." > c="1." > r = range(256) > for r in r: > print a + b + c + r > ------------------------------ > But, I get this error: cannot concatenate 'str' and 'int' objects. So, I > need to convert the ints in the range to strs, but I do not know how to > do that. Could someone help me? Ultimately, I want to print out > something like this to a text file: > 192.168.1.0 > 192.168.1.1 > 192.168.1.2 > ... > 192.168.1.255 Try any or all of these: print a + b + c + str( r ) print a + b + c + "%d" % r print a + b + c + "%s" % r print "%s%s%s%d" % (a, b, c, r) Regards, Heather -- Heather Coppersmith That's not right; that's not even wrong. -- Wolfgang Pauli From rummanddan_nospam at hotmail.com Mon Sep 1 08:39:06 2003 From: rummanddan_nospam at hotmail.com (Dan Thrue) Date: Mon, 01 Sep 2003 14:39:06 +0200 Subject: Python Documentation? In-Reply-To: References: <3f530ea6$0$32489$edfadb0f@dread16.news.tele.dk> Message-ID: <3f533f3d$0$32467$edfadb0f@dread16.news.tele.dk> Cameron Laird wrote: > In article , > Larz wrote: > . > . > . > >>Dan and I are long time php programmers. One thing that is superb about >>php, is it's online documentation that everyone in the community can >>contribute to (not the actual documentation, just comments with >>examples). >> >>Every since I first started using python, I've truly missed a >>documentation source similar to that of PHP's. So Dan and I have started >>our little project to make a documentation site in the spirit of that >>documentation. > > . > . > . > PHP's documentation has indeed been a great success as a > collaborative adventure. > > Python already has a structure--and much content!--for > comparable collaboration in www.python.org/cgi-bin/moinmoin/ >. Moreover, as several > follow-ups have explained, Python developers have differ- > ent work practices than PHPers, and a different relation > to documentation. In particular, it's hard to overempha- > size how much working Python programmers depend on > interactive introspection: use of the interpreter's > built-in help, pydoc, and related facilities to discover > and confirm details that, in PHPonia, are regarded as > matters for online documentation. Hi Cameron, Thank for your feedback, i personally uses pydoc when im in need of documentation, but sometimes i have been in such situations where code snippets was necessary for me. The background for this project is to gain a great database public of snippets hooked in a structure that is easily for all to use, novice as well as expert. Maybe its the way i think, but i understand and learn a lot faster (better?) when the the theory is put into practice. At my daily work im a .net programmer, and the documentation im using there is also "practice based". Im not a theoretic person, and I think there is a lot like myself out there :) Best Regards Dan From robin at jessikat.fsnet.co.uk Mon Sep 29 08:35:34 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 29 Sep 2003 13:35:34 +0100 Subject: extension call backs and the GIL References: Message-ID: In article , Aahz writes >In article , >Robin Becker wrote: >> >>I'm trying to better my understanding of multithreading. I believe a >>thread that calls an extension must have the GIL. What happens if the >>extension then calls back into Python? Can a function or method somehow >>'belong' to a different thread? My understanding was that things should >>be OK provided the extension code doesn't mess with the GIL (which it >>doesn't). > >You need to reacquire the GIL prior to making the callback. So does calling an extension release the GIL? I believed the opposite for some reason. -- Robin Becker From dkuhlman at rexx.com Sat Sep 20 17:39:49 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 20 Sep 2003 14:39:49 -0700 Subject: spam killing with poplib References: Message-ID: Robin Becker wrote: [snip] >>Phil Weldon, pweldon at mindspring.com >> >>"Simon Burton" wrote in message >>news:pan.2003.09.20.06.52.21.266409 at webone.com.au... >>> >>> This was so easy :) >>> >>> Simon Burton. > .... you're right, I had to use patterns like Almost all the spam I'm receiving has an attachment whose file type is one of .exe, .bat, .com, .scr, .pif, and a few others. Is there a way for your Python script to check for that? How do you do that in Python. I'm guessing that you are not in the mood for receiving executable files right now. Here is a strange thing: I'm using procmail and junkfilter to dispose of these. I looked at procmail's log, and noticed that in many cases (but not all) I seem to be receiving exactly 2 spam emails from each From address. I suppose this worm does not want me to think I can do something so simple as send a request to one infected machine asking it to clean itself up. Dave [snip] -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From donn at u.washington.edu Wed Sep 24 17:43:41 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 24 Sep 2003 14:43:41 -0700 Subject: How to tell if a forked process is done? References: <879b6a51.0309231547.428214f7@posting.google.com> <3f71395d-46f08129-996a-495d-a5ee-05fb1caef6e9@news.szn.dk> Message-ID: In article , Thomas Bellman wrote: ... > There it least one Unix that reuse process ids immediately when > they are free. A vague memory says that it is AIX that does > this, but I'm not sure; it could be some of the BSD dialects too. Not AIX 4 or 5, and no BSD I've seen- cursory inspection suggests it is not the case with FreeBSD 5.1 nor MacOS X 10.2.6. > However, in this very case, *that* isn't a problem. The process > id won't be free to reuse until the parent has called wait(2) to > reap its child. On the other hand, that means that kill(pid, 0) > won't signal an error even after the child has died; the zombie > is still there... Good points. Donn Cave, donn at u.washington.edu From grey at despair.dmiyu.org Sun Sep 7 07:15:27 2003 From: grey at despair.dmiyu.org (Steve Lamb) Date: Sun, 07 Sep 2003 11:15:27 -0000 Subject: OT: Americans love their guns References: Message-ID: On 2003-09-07, Chad Netzer wrote: > On Sat, 2003-09-06 at 00:43, Steve Lamb wrote: >> If guns were such a overriding factor why is it the UK has as high >> if not higher rate of gun related violence than the US? > You still haven't responded to the rebuttals of this statement. On the > face of it, it appears made up. Can you explain? Because it was worded incorrectly and is, in essence, as worded, indefensible. Quite frankly I don't have the time or patience to discuss the issue further in a PYTHON newsgroup. -- Steve C. Lamb | I'm your priest, I'm your shrink, I'm your PGP Key: 8B6E99C5 | main connection to the switchboard of souls. -------------------------------+--------------------------------------------- From srijit at yahoo.com Tue Sep 16 05:01:18 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 16 Sep 2003 02:01:18 -0700 Subject: Duck Typing Message-ID: <221d8dbe.0309160101.4a09f2ad@posting.google.com> Hello All, I have been seeing this term "duck typing" for quite sometime now. It will be nice if one of us can give an example in Python demonstrating duck typing and/or link to some Python references. Regards, Srijit From tzot at sil-tec.gr Wed Sep 17 03:24:40 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 17 Sep 2003 10:24:40 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <0vQ9b.23$1l5.14@reader1.news.jippii.net> Message-ID: On Wed, 17 Sep 2003 06:29:36 +0300, rumours say that Harri Pesonen might have written: [snip discussion so far because I want to focus on this sentence] >Multiple threads are more efficient, they use less system resources, and >they allow fast shared memory access (in a way or another). "efficient": I asked you in another part of this thread: please define efficient. "resources": A program that forks itself on current operating systems does not consume *much* more memory than a multithreaded one; code is shared, many data pages won't be written so they will remain common. Whatever I may say, have you got numbers from your personal experience? "fast memory access": yes, accessing directly the data memory of the same process is faster than going through the shmem calls first, but how much do you believe this overhead is? Or do you believe that accessing mapped shared memory is slower than accessing the data memory of the process? The whole point is that you seem to be based on the words of others about "thread efficiency", without having experience of your own against other possible solutions. Do you have example applications you want to build? Did you post a description of the problems you encountered so that the people in c.l.py can help you? -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From will_woods2 at yahoo.co.uk Tue Sep 2 13:00:16 2003 From: will_woods2 at yahoo.co.uk (Will Woods) Date: 2 Sep 2003 10:00:16 -0700 Subject: Tkinter and readline key bindings Message-ID: Hi, I have installed readline on win32, and it works fine until I do: from Tkinter import * root = Tk() at which point the cursor keys stop working, and print strange characters. Any ideas? Thanks, Will From Huzzah! at Huzzah.com Wed Sep 17 21:06:07 2003 From: Huzzah! at Huzzah.com (Todd Stephens) Date: Thu, 18 Sep 2003 01:06:07 GMT Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> Message-ID: <3y7ab.1043$Od.78860@twister.tampabay.rr.com> Lothar Scholz wrote in article <6ee58e07.0309171548.314a046c at posting.google.com>: > i hope that there support for the program is better then the support > for their website. Everything in the last weeks doesn't look very > promising. TheKompany.com is somewhat notorious for not updating their website as they update the apps. They are heavily involved in embedded app development as well as much larger projects like BlackAdder, Kobol, and Aethera to name just a few. I guess sometimes updating the website falls through the cracks. I would go by what the person who actually tried the demo said. -- Todd Stephens ICQ# 3150790 "A witty saying proves nothing." -Voltaire From jdhunter at ace.bsd.uchicago.edu Tue Sep 23 16:25:13 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 23 Sep 2003 15:25:13 -0500 Subject: Pygtk, widget refreshing In-Reply-To: (Arne Schwabe's message of "23 Sep 2003 22:33:22 +0200") References: Message-ID: >>>>> "Arne" == Arne Schwabe writes: Arne> hi, I am using python and pygtk. In my program I want to Arne> realize a status thing with a DrawingArea. But my problem Arne> is that this area is not updated while my program is Arne> running. Is there a way I can force pygtk to refresh to Arne> widgets? Two good ways, one is to use a timer and the other an idle. A timer will call your function of choice every so many milliseconds, and an idle func will do it whenever the gtk event loop is idle For the timer def update_widget(*args): pass # do something here gtk.timeout_add(250, update_widget) # call update_widget every 250 ms For the idle func, you can pass an arg that will be passed to your idle func gtk.idle_add(update_widget) Here is how I update a status bar -- this may not be ideal, it's just what I came up with when I confronted it the first time Create the status bar self.statbar = gtk.Statusbar() self.statbar.show() self.statbarCID = self.statbar.get_context_id('my stat bar') self.vbox.pack_end(self.statbar) self.timeoutId = gtk.timeout_add(5000,self.update_status_bar) where update_status_bar looks like def update_status_bar(self, msg=None): if msg is None: # generate default message try: self.statbarCID, self.statbarMID except AttributeError: pass else: self.statbar.remove(self.statbarCID, self.statbarMID) self.statbarMID = self.statbar.push(self.statbarCID, msg) return gtk.TRUE and then later when the dialog is destroyed gtk.timeout_remove(self.timeoutId) Hope this helps, John Hunter From skip at pobox.com Tue Sep 30 14:42:52 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 30 Sep 2003 13:42:52 -0500 Subject: import _XXXXXX In-Reply-To: References: Message-ID: <16249.52908.578899.220845@montanaro.dyndns.org> Robert> When a Python program declares import _XXXX. What form is XXXX Robert> when the underbar is included (_XXX)? There's no special form. The leading underscore is there to alert people they should not normally import that module directly. For example, people should import bsddb, not _bsddb. Same goes for (the third part modules) MySQLdb and _mysql. In both cases, the former builds on the latter. Skip From __peter__ at web.de Mon Sep 29 13:13:17 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Sep 2003 19:13:17 +0200 Subject: Python os.popen in Linux References: Message-ID: Sami Viitanen wrote: > Hello, > > I was using os.popen function to get CVS command output to string from > script.. > > Same commands worked well with Windows, but Linux seems to have problem > with those. Whole CVS commands seem to froze or given commands aren't > executed right > at all. I had to replace os.popen commands with os.system. os.system > commands just > print additional information to screen that is not necessary at all. > > Any ideas what may cause this ? I think os.system() is the way to go. You should *not* suppress any error messages, but if you must, simply redirect to /dev/null. However, it would be worth the effort to search for some existing Python/CVS interface that performs some real error handling. def sfnFreezeFiles(sModFiles): lModFiles = sModFiles.split() sCurrentDir = os.getcwd() try: for path in lModFiles: sDir, sModFile = os.path.split(path) ColorPrint.fnPrintExecute('Freezing: %s %s' % (sDir, sModFile)) os.chdir(sDir) os.system('cvs update -A %s 2>/dev/null' % sModFile) os.system('cvs ci %s 2>/dev/null' % sModFile) finally: os.chdir(sCurrentDir) return len(lModFiles) Off topic: I suppose you were exposed to VB too long :-) I've taken time to clean up your function a bit, your comment style is obscuring the code rather than helping the reader. Peter From jack at performancedrivers.com Wed Sep 10 15:15:27 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 10 Sep 2003 15:15:27 -0400 Subject: How to instatiate a class of which the name is only known at runtime? In-Reply-To: <200309100215.38583.kosh@aesaeion.com>; from kosh@aesaeion.com on Wed, Sep 10, 2003 at 02:15:38AM -0600 References: <3F5ECDE2.40206@mxm.dk> <3F5ECEF7.9080409@mxm.dk> <200309100215.38583.kosh@aesaeion.com> Message-ID: <20030910151527.C7418@localhost.localdomain> On Wed, Sep 10, 2003 at 02:15:38AM -0600, kosh wrote: > On Wednesday 10 September 2003 01:12 am, Max M wrote: > > Max M wrote: > > > import class1, class2, class3 > > > > > > def Factory(class_type): > > > if class_type='class1': > > > return class1() > > > elif class_type='class2': > > > return class2() > > > elif class_type='class2': > > > return class3() > > > > > use > > def Factory(class_type): > factory = { > 'class1':class1, > 'class2':class2, > 'class3':class3} > try: > return factory[class_type]() > except KeyError: > pass > metaclasses are your friend, here is one I use frequently for factoires. class Register(type): """A tiny metaclass to help classes register themselves automagically""" def __init__(cls, name, bases, dict): if ('register' in dict): # initial dummy class setattr(cls, 'register', staticmethod(dict['register'])) elif (getattr(cls, 'DO_NOT_REGISTER', 0)): # we don't want to register this non-concrete class delattr(cls, 'DO_NOT_REGISTER') elif (object not in bases): cls.register(name, cls) return class Widget(object): __metaclass__ = Register all = {} def register(name, cls): Widget.all[name] = cls def factory(name): return Widget.all[name] factory = staticmethod(factory) # just use this class like a namespace class C1(Widget): pass class C2(Widget): pass class C3(Widget): pass # instantiate a C3 by name c3_instance = Widget.factory('C3')() Every class that inherits Widget and doesn't have a DO_NOT_REGISTER attribute will put it's name:class into the Widget.all dictionary. I typically use a short hierarchy to break up the code a bit class WidgetFacory(object): """this class only has static factory methods""" __metaclass__ = Register all = {} # register() and factory() as above class Widget(WidgetFactory): # we inherit 'WidgetFactory' to get the metaclass """This class is the base functionality of Widget classes, This is a virtual base class for Widgets that can't be instatiated by the WidgetFactory interface""" DO_NOT_REGISTER = 1 # tell the factory to forget we exist def __init__(self, *args, **opts): # your code here # now define the classes that can be instantiated from the WidgetFactory class Mallet(Widget): pass class Hoop(Widget): pass class Ball(Widget): pass hmm, the post is about to get longer. If you repeat the above pattern enough, write a func to do all the above for you, so your code might look like class Widget(object): pass # your real definition of the base Widget class # setup the factory, and rebind the name Widget to a class that inherits it (WidgetFactory, Widget) = make_factory(Widget) I use a slightly different technique in my unit tests, cut-n-pasted here it defines the class-tracker using Register and returns the base object. It also defines a main() method for the test suite. My test-coverage class is in here too, but that is extra. It just defines a TestCase that checks for test coverage versus implemented tests. Last things first, here is how it is used """ t_libUtil.py - test 'libUtil' module """ import test # defined below import libUtil (Test, main) = test.setup(libUtil) class SimpleSum(Test): we_test = [libUtil.simple_sum] def test_sum(self): f = libUtil.simple_sum x = [0,0] self.assertEqual([0,3], f(x,[1,3]) or x) if (__name__ == '__main__'): main() # module 'test.py' import unittest class Register(type): """A tiny metaclass that keeps track of all classess""" def __init__(cls, name, bases, dict): if ('register' in dict): # initial dummy class setattr(cls, 'register', staticmethod(dict['register'])) elif (object not in bases): cls.register(name, cls) return def setup(module): class Test(unittest.TestCase, object): # TestCase is an old-style class __metaclass__ = Register alltests = [] # all Test classes allfuncs = [] # list of all the functions they test def register(name, cls): Test.alltests.append(cls) Test.allfuncs += cls.we_test class TestCoverage(Test): """make sure we have tests for all the funcs and classes in the module""" we_test = [] def test_coverage(self): # find all functions and classes in the module need = [] for (name, val) in module.__dict__.items(): if (callable(val)): need.append(val) try: if (val.__class__.__name__ == name): # this finds classes defined in the module need.append(val) except: pass for (ob) in need: good = ob in Test.allfuncs if (not good): raise self.failureException("No Test coverage: %s" % (str(ob))) def main(): suite = unittest.TestSuite() test_classes = Test.alltests for cls in test_classes: suite.addTest(unittest.makeSuite(cls)) result = unittest.TestResult() suite(result) msg = [] if (result.errors): msg.append('Failure') if (result.errors): msg.append('Error') print "%s: %d %s" % (module.__name__, result.testsRun, " & ".join(msg) or 'Success') for (err) in result.errors: print "\n".join(map(str, err)) for (failure) in result.failures: print "\n".join(map(str, failure)) return return (Test, main) In places like unittest where we already do heavy introspection using metaclasses to do the introspecition is usually a big win. long-posted-ly, -jackdied From ryan at ryanswift.com Wed Sep 3 10:04:17 2003 From: ryan at ryanswift.com (Ryan Swift) Date: 3 Sep 2003 07:04:17 -0700 Subject: Extracting TIFF from emails Message-ID: Hi, I'm new to Python, so this may be an easy solution. I'm having trouble extracting TIFF files from incoming emails. Actually, I think the root of my problem is that I'm having trouble reading the email header. Does anyone have an easy solution? Thanks in advance. From mertz at gnosis.cx Sun Sep 7 00:06:17 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sun, 07 Sep 2003 00:06:17 -0400 Subject: Anyone ever overridden a builtin by accident? In-Reply-To: References: Message-ID: <56qW/kKkX4mY092yn@gnosis.cx> |I had overridden the __builtin__ function by mistake. I had a script or two that used 'dict' as a variable name... which was fine, until Python 2.2. Since then, I've used 'dct' for the same purpose. But possibly something old is still sitting around with the problem. Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From tim.parkin at pollenationinternet.com Wed Sep 10 04:43:45 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Wed, 10 Sep 2003 09:43:45 +0100 Subject: Redesign of Python site In-Reply-To: <200309100540.h8A5epgD030889@localhost.localdomain> Message-ID: <003301c37777$a9220b20$0a00a8c0@JASPER> > >>From the most recent stats, the top 20 entry pages: > > Hits Visits URL >1 252455 3.60% 164578 44.76% / >2 169489 2.42% 20381 5.54% /pypi >3 66001 0.94% 7997 2.18% /2.3/ >4 47542 0.68% 7664 2.08% /doc/ >5 25401 0.36% 7049 1.92% /doc/current/tut/tut.html >6 39856 0.57% 5825 1.58% /download/ >7 10903 0.16% 2826 0.77% /cgi-bin/faqw-mm.py >8 20848 0.30% 2678 0.73% /doc/current/lib/lib.html >9 10952 0.16% 2428 0.66% /doc/Newbies.html >10 8372 0.12% 2347 0.64% /doc/Intros.html >11 13328 0.19% 1971 0.54% /doc/current/ >12 7992 0.11% 1616 0.44% /2.3/highlights.html >13 2537 0.04% 1490 0.41% /~guido/ >14 67565 0.96% 1430 0.39% /doc/current/icons/ >15 4802 0.07% 1324 0.36% /doc/Comparisons.html >16 22751 0.32% 1251 0.34% /topics/learn/ >17 3631 0.05% 1199 0.33% /doc/FAQ.html >18 53884 0.77% 1198 0.33% /cgi-bin/faqw.py >19 7969 0.11% 1152 0.31% /doc/current/tut/node7.html >20 9290 0.13% 1144 0.31% /doc/current/tut/node6.html Although essential for working out a new information architecture / navigational network for a site, stats can be a very misleading way of working out what are the most used areas of the site. Problem #1 : A prominent, badly worded link will get many people clicking through to it but a large number of these may not find what they expect. This shows that logs record where people go and not where people want to end up. Solution #1: Take into account page visit duration, remove hits where another unrelated menu item is clicked in a reasonable amount of time, etc. Problem #2: There is little record of people who haven't found what they wanted, obviously an important sector to target. Solution #2: Look for people who have left the site without lingering on any page for a significant amount of time. Trace back there paths and try to work out why the links they have used 'could' be confusing. Problem #3: People who know what they are after go straight there and don't record significant numbers of hits. People who get lost or confused record a large number of hits. This skews the results away from your successes to your failures. Solution #3: Look for short paths within the logs to indicate that people have found what they want quickly, rank these separately from other rankings. There are a lot of other gotchas related to log analysis to bear in mind. An example of one of these on the current site layout may be the fact that the search engine sits on another domain so that when someone searches they leave the site and come back in on a deep link. This probably accounts for the high number of deep links recorded on the entry pages, a lot of these results aren't in fact entry pages at all. This could account for the high number of people leaving from the home page. Tim From grante at visi.com Fri Sep 5 10:50:37 2003 From: grante at visi.com (Grant Edwards) Date: 05 Sep 2003 14:50:37 GMT Subject: Why the 'self' argument? References: Message-ID: <3f58a2bd$0$156$a1866201@newsreader.visi.com> In article , John Roth wrote: > Technically, it would be possible to make "self" a reserved > word, and not have to put it in the method declaration. > However, there are a lot of people who use something other than > the word "self," so that would break existing code. It would also make the language more complex and irregular. -- Grant Edwards grante Yow! Could I have a drug at overdose? visi.com From gerrit at nl.linux.org Tue Sep 23 10:53:09 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 23 Sep 2003 16:53:09 +0200 Subject: a little OT: how to handle this email list? In-Reply-To: <51397.199.169.240.132.1064323325.squirrel@svr1.turboweb.net> References: <51397.199.169.240.132.1064323325.squirrel@svr1.turboweb.net> Message-ID: <20030923145309.GA3957@nl.linux.org> Matthew Wilson wrote: > I subscribe to the python mailing list with an IMAP mailbox. I use > squirrelmail to check my mail. This is a great list, but it is definitely > high volume. My python folder fills up with several hundred emails every > day. How do the rest of you handle all the traffic on this list? Do you > delete everything at the end of every day? > > All insights are welcomed. I use a python script :) This python script is called by procmail, a mail filtering program (Linux). The first argument is the file in which it should be redirected, the input is the e-mail message. It reads the e-mail, checks the DATE header and throws the e-mail into the mailbox for this week. Every week, I start a new mailbox. #!/usr/bin/env python """Appends email message from standard input to mailbox argv[1] in the correct date""" import os import sys import email import email.Utils import time MAILDIR = "/home/gerrit/email" def getdestfromdate(d): timetuple = email.Utils.parsedate(d) print d, "=>", timetuple timetuple = time.localtime(time.mktime(timetuple)) subfile = sys.argv[1] jaar = time.strftime("%Y", timetuple) week = time.strftime("%U", timetuple) dest = os.path.join(MAILDIR, jaar, week, subfile) return dest def main(): message = email.message_from_file(sys.stdin) dest = getdestfromdate(message["Date"]) print "Appending to", dest if not os.path.exists(os.path.dirname(dest)): print "creating dir for", dest os.makedirs(os.path.dirname(dest)) fp = open(dest, "a") fp.write(str(message)) fp.close() if __name__ == "__main__": main() Note that this may not run with Python prior to 2.3. Gerrit. -- 220. If he had opened a tumor with the operating knife, and put out his eye, he shall pay half his value. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From duncan-news at grisby.org Thu Sep 4 12:15:10 2003 From: duncan-news at grisby.org (Duncan Grisby) Date: Thu, 04 Sep 2003 16:15:10 +0000 Subject: Arguments of function as out References: Message-ID: <6e951$3f57650e$51604868$15609@nf1.news-service.com> In article , Birgit Rahm wrote: >I've already read this, but I hoped, there is a way to get these out >parameters beside this. Aside from all the help Alex has already given you, perhaps you should have read the very next part of the specification, after the bit Piet quoted. It says: """ Assuming the IDL definition interface I { oneway void stop(); bool more_data(); void get_data(out string name, out long age); }; a client could write names = {} while my_I.more_data(): name,age = my_I.get_data() names[name] = age my_I.stop() """ I don't think it can get much clearer than that. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From davidcfox at post.harvard.edu Thu Sep 18 09:13:29 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Thu, 18 Sep 2003 13:13:29 GMT Subject: Setting environment variables In-Reply-To: <3F6959B3.6A19FF3B@alcyone.com> References: <3F6959B3.6A19FF3B@alcyone.com> Message-ID: Erik Max Francis wrote: > Sami Viitanen wrote: > > >>Is there any other way to set variables than os.putenv(). >> >>Putenv doesn't actually put any values to actual system variables.. >> >>I'm trying to set CVSEDITOR variable automatically from script >>so that user wouldn't have to set that him/herself. CVS can't use >>variable >>set with putenv(). > > > Yep, and this is a feature, at least in Unix operating systems. > Subshells cannot directly affect the operating environment of parent > shells, and shouldn't try. (One can do such things indirectly, but they > require the cooperation of the parent shell, such as sourcing the output > of a program, which is not an uncommon approach to the problem.) I > don't know if there's any way for Windows applications to affect parent > environments, but I doubt it. > In [t]csh: alias cvsscript "setenv CVSEDITOR `python myscript.py`" cvsscript or miscellaneous variants in other shells. Of course, you can't use cvsscript from within another subshell, or it will only set the variable in that subshell. David From Alexandre.Fayolle at logilab.fr Fri Sep 26 12:43:43 2003 From: Alexandre.Fayolle at logilab.fr (Alexandre Fayolle) Date: Fri, 26 Sep 2003 18:43:43 +0200 Subject: [ANN] pygantt-0.9.3 Message-ID: <20030926164343.GQ28349@calvin> Logilab has released pygantt-0.9.3 What's new? ----------- This release fixes the way to find the PIL fonts. It also fixes a bug in the resource filter (many thanks to Mitry Samersoff for providing a patch) About Pygantt ------------- Pygantt is a project management tool, which can use XML files describing tasks and resources and generate Gantt diagrams for the project. It can use Logilab's constraint satisfaction solver to schedule the different tasks. URLs ---- Homepage: http://www.logilab.org/projects/pygantt/ Download: ftp://ftp.logilab.org/pub/pygantt/pygantt-0.9.3.tar.gz -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org D?veloppement logiciel avanc? - Intelligence Artificielle - Formations From afriere at yahoo.co.uk Thu Sep 18 00:35:58 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 17 Sep 2003 21:35:58 -0700 Subject: convert ints in a range to strings References: Message-ID: <38ec68a6.0309172035.23d1df4e@posting.google.com> hokieghal99 wrote in message news:... > Hi, > > I'm trying to do this: > > ------------------------------ > a="192." > b="168." > c="1." > r = range(256) > for r in r: > print a + b + c + r > ------------------------------ > > But, I get this error: cannot concatenate 'str' and 'int' objects. So, I > need to convert the ints in the range to strs, but I do not know how to > do that. Could someone help me? Ultimately, I want to print out > something like this to a text file: > > 192.168.1.0 > 192.168.1.1 > 192.168.1.2 > ... > 192.168.1.255 > > Thanks!!!! for x in r : print a + b + c + str(x) but why not use ints all the way along like this: a = 192 b = 168 c = 1 for n in range(256) : print "%d.%d.%d.%d" % (a, b, c, n) or simply don't use them at all: for n in range(256) : print "192.168.1.%d" % n From newsgroups at jhrothjr.com Mon Sep 15 12:04:48 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 15 Sep 2003 12:04:48 -0400 Subject: Datetime utility functions References: <182bcf76.0309150707.3a8c0482@posting.google.com> Message-ID: "Paul Moore" wrote in message news:182bcf76.0309150707.3a8c0482 at posting.google.com... > I was just writing some code which did date/time manipulations, and I > found that the Python 2.3 datetime module does not supply a number of > fairly basic functions. I understand the reasoning (the datetime > module provides a set of datatypes, and doesn't attempt to get into > the murky waters of date algorithms) but as these things can be quite > tricky to get right, I was wondering if anyone has already implemented > any date algorithms, or alternatively if I'd missed some easy way of > doing what I'm after. > > My specific requirements were: > > 1. Get the last day of the month contatining a given date(time). I > really was surprised to find this one missing, as it seems to me that > the datetime module must know what the last day for each month is, so > exposing it wouldn't have been hard. I'm kind of surprised to see that it's missing, too. > 2. Add a number of months to a date. This is messy, as there are > options (what is one month after 31st Jan). The trouble is that the > calculation, while simple, is tricky to get right (month is 1-based, > so off-by-1 errors are easy to make, and divmod isn't as useful as > you'd first think). That's application dependent. If a bond, for example, has interest payable on the 30th of the month, you probably want the 30th, except in February you want the last day of the month. However, the contract may specify something else. And in no case do you want the date to suddenly change to the 28th because you went through February. > Other "nice to have" functions which I didn't need for this program, > but which I have found useful in the past, are > > - Round a date(time) to a {year,month,day,quarter,week,...} Or > truncate. Or (occasionally) chop to the next higher boundary > (ceiling). > - Calculate the number of {years,months,days,...} between two dates. > (Which is more or less the equivalent of rounding a timedelta). > > These latter two aren't very well defined right now, because I have no > immediate use case. Most of these don't have well defined, globally useful use cases. It's heavily application dependent what you want out of these. > In the absence of anything else, I'll probably write a "date > utilities" module for myself at some point. But I'd hate to be > reinventing the wheel. There's a very well regarded date module out there in the Vaults of Parnassus. The name escapes me at the moment, but a bit of spelunking through the Vaults will turn up several date routines that may do what you want. John Roth > > Paul. From NO-MAIL at hotmail.com Fri Sep 19 18:20:30 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Fri, 19 Sep 2003 22:20:30 GMT Subject: file position *tell()* works different References: <13a533e8.0309190137.2df0cc60@posting.google.com> Message-ID: "Eric Brunel" wrote in message news:bkemib$bjr$1 at news-reader2.wanadoo.fr... > Sorry, but no you can't: the default is to open the file in text mode, and you > can change it with a 'b', but 't' has no meaning at all. BTW, 'b' also has no > meaning at all on all Unices: the so-called "binary" or "text" mode are the > same, i.e. what is read is what is in the file. Windows needs it only because of > its superfluous \r's at the end of each line. > <...> > HTH > -- > - Eric Brunel - > PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com The idea was to tell the humans that it's text. It won't hurt neither Unix nor Windows. I know that nobody cares, though. M-a-S From amonroejj at yahoo.com Tue Sep 23 22:37:45 2003 From: amonroejj at yahoo.com (R. Alan Monroe) Date: Wed, 24 Sep 2003 02:37:45 GMT Subject: Fastest way to get thousands of db records to client in 3 tier? Message-ID: Subject says it all... what's the fastest way to get many thousands of records to the client? I'm trying to sketch out a traditional 3 tier client-server system. Multiple clients would make requests to the server. The server should execute sql select commands against a server-side database, then return the results to the client. I tried the standard xmlrpclib and SimpleXMLRPCServer tools that came with Python. I liked the simplicity, but it was about 30-35 times slower than executing the sql directly from the client... I intend to write both client and server in Python, and my main goal in the first cut is speed. Suggestions? Alan From emile at fenx.com Mon Sep 29 18:26:57 2003 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Sep 2003 15:26:57 -0700 Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> Message-ID: "Lulu of the Lotus-Eaters" wrote in message > > Moving farther, even this gap structure is quite compressible. Most > gaps are quite a bit smaller than 65536, so the highbits are zeros. In > fact, I am pretty sure that almost all the gaps are less than 256. So > an immediate compression strategy (saving disk space, costing time to > recreate the transparent structure) is to store gaps as 8-bit values, > with a x00 byte escaping into a larger value (I guess in the next two > bytes). You can take this to 512 knowing that the gaps will always be an even interval. Emile From ian_maurer at yahoo.com Wed Sep 17 16:50:41 2003 From: ian_maurer at yahoo.com (Ian Maurer) Date: Wed, 17 Sep 2003 13:50:41 -0700 (PDT) Subject: needs help in how to translate ≾ In-Reply-To: <971323274247EB44B9A01D0A3B424C85FCEA27@FTWMLVEM02.e2k.ad.ge.com> Message-ID: <20030917205041.65837.qmail@web20207.mail.yahoo.com> This code accomplishes that goal... but it's not very reusable. At a minimum you need to put the (non-print) steps in a function. >>> text = "(('≾Hello World≾'),(''))" >>> tupl = eval(text) >>> print tupl ('≾Hello World≾', '') >>> s = tupl[0] >>> print s ≾Hello World≾ >>> final = s.replace("≾", '"') >>> print final "Hello World" >>> Good Luck! Ian Maurer --- "Raaijmakers, Vincent (IndSys, GE Interlogix)" wrote: > As a newbie in coding in encoding I need some help from the guru > here. > When I get information from a user database (mySQL) I get text that > looks like: > > (('≾Hello World≾'),('')) > > How can I create this info into a string that looks like: > "Hello World" > > Because what I know is that ≾ stands for the character " > > Must be veeeeerrrrryyyy simple, but how? > > Thanks, > Vincent > > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From achalk at XXXmagnacartasoftware.com Tue Sep 23 13:32:45 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Tue, 23 Sep 2003 17:32:45 GMT Subject: Executing a python script from an HTML link? References: Message-ID: <1t%bb.407$Q44.601209120@newssvr11.news.prodigy.com> Thanks. I want to run the script on the server. The problem is that I don't have an html page as an HREF. Viz: Fred What replaces Fred.htm to invoke a server-side script? Regards. "John Roth" wrote in message news:vn0tdkg96jlcc7 at news.supernews.com... > > "Andrew Chalk" wrote in message > news:tMYbb.382$zy3.566196578 at newssvr11.news.prodigy.com... > > Is this possible? In my CGI app. I display a web page with a link > (anchor). > > When the link is clicked I want to exectute a python script rather than go > > to an HTML page. > > Do you want to run the script on the server or the client? If you > want to run it on the client, you can use Python instead of Javascript > (or in addition to Javascript) in the web page. Look at the (with win32all or the ActiveState Python distribution) John From skip at pobox.com Sat Sep 13 11:09:05 2003 From: skip at pobox.com (Skip Montanaro) Date: Sat, 13 Sep 2003 10:09:05 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <6BB6268D-E5EC-11D7-A7C2-000393D443CE@earthlink.net> References: <16226.9487.204094.248590@montanaro.dyndns.org> <6BB6268D-E5EC-11D7-A7C2-000393D443CE@earthlink.net> Message-ID: <16227.13073.611762.21526@montanaro.dyndns.org> Mitch> Unlike Andrew I don't think the lack of maintenance for 1.4's Mitch> free threading packages is due to any perception that threading Mitch> performance is unimportant. It seems more likely that the Mitch> packages were not updated because they proved not to solve the Mitch> performance problems, and that no alternatives have emerged Mitch> because the problem is hard to solve. One reason (maybe the primary reason) it never went further than a patch to 1.4 was that it was slower in the (common) single-threaded case. Free threading is no magic bullet. There is a lot of overhead in maintaining all the fine-grained locks necessary to dispense with the GIL. Mitch> Having said all of that, it looks like this thread originated on Mitch> python-dev, rather than on c.l.py where I found it. So I'm Mitch> probably missing some reasons for what appears to be a dismissive Mitch> attitude toward Harri's efforts. I'll go read the python-dev Mitch> archives. Python-dev is the place to discuss concrete proposals. Python-list is the place to hash out ideas. Simple as that. You can read the few messages in python-dev in the archive for September: http://mail.python.org/pipermail/python-dev/2003-September/thread.html Search for "thread safe". Skip From !spamispeople!punga at great-atuin.net Sun Sep 7 16:03:41 2003 From: !spamispeople!punga at great-atuin.net (Eduardo Alvarez) Date: Sun, 7 Sep 2003 20:03:41 +0000 Subject: Redesign of Python site References: Message-ID: In article , Terry Reedy wrote: > > "rt lange" wrote in message > news:Xns93EEDC144D362whiteywidowyahoocom at 216.77.188.17... >> came across this page searching feedster. >> dont know whether this is the official resdesign or just a proposal; >> but the mockups look very nice. > > YUCK< YUCK< YUCK. > >> http://www.pollenation.net/journal/index.php?p=37&c=1 >> >> main page mockup: >> http://www.pollenation.net/assets/public/python-main.html > > The old site is very readable. Using IE6, I need a magnifying glass > to read this page. This is done in the arrogant style of 'we know > better than you what type size you should have'. Also known as the > 'control the user experience' school. Awful. For me, one of the > worse pages I have ever seen. Anti-Pythonic. > >> interior page: >> http://www.pollenation.net/assets/public/python-interior.html > > Only slightly better. The low contrast gray-on-gray comments page is > also barely readable. (Others reported the same.) For my > less-than-perfect 50+ year-old eyes, it is physically the WORST > comments page I have ever seen. It is a case study in > anti-accessibility design. The person responsible should not touch > our site. > > Terry J. Reedy > > > > Terry J. Reedy > > > only slightly better. > > mmmm...I only seem to see an image of the proposal. is it possible to see an actual HTML version of it? The easiest test in my opinion would be to run it by lynx, and see how readable it is then... -- Eduardo Alvarez http://www.great-atuin.net/~punga (offline, at the moment) "Stercus, stercus stercus, moriturus sum" -- Rincewind the Wizzard, "Interesting Times" From freddycooper01 at yahoo.com Fri Sep 26 11:51:37 2003 From: freddycooper01 at yahoo.com (Freddy) Date: 26 Sep 2003 08:51:37 -0700 Subject: Turning Strings into Functions References: <46610d4e.0309251516.45a8eb01@posting.google.com> Message-ID: <46610d4e.0309260751.7699bfb5@posting.google.com> I guess I could do that. Right now I'm creating the use cases dictionary in a totally separate module which knows nothing about my main module's functions. But I will try either moving the code into my current module, or including the testcases.py into my higher level module. Thanks for the suggestion. Freddy "Richard Brodie" wrote in message news:... > "Freddy" wrote in message > news:46610d4e.0309251516.45a8eb01 at posting.google.com... > > > How do you turn a string into a callable function? I'm writing a > > program which takes user input and then looks up the associated > > function to run from a shelved dictionary. > > I see you have an answer already, so I'll give you a question. > Is there any particular reason why you are storing the name > of the function in the dictionary rather than the function itself? > > i.e. myDict["Case1"] = {"desc":"This is Case1", "func1": Handler1} etc From mwh at python.net Wed Sep 24 12:28:25 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 24 Sep 2003 16:28:25 GMT Subject: 64-bit EPIC and some modules References: Message-ID: <7h3smmm2m0w.fsf@pc150.maths.bris.ac.uk> Christos "TZOTZIOY" Georgiou writes: > I got my hands on a Itanium2 machine[1], and gcc builds 64-bit > executables by default. (sys.maxint = 9223372036854775807). _tkinter, > audioop and imageop didn't compile at first, and I believe it's a > problem of configure. > > I changed Modules/Setup and removed the hashes from the relevant > modules, and a recompilation worked fine; so did running > test.test_audioop and test.test_imageop. > Things went well for the _tkinter extension too, after editing > Modules/Setup, with the pre-installed 8.3 versions of tcl and tk. > > The problem is that I am at a loss with the configure mechanism, and I > can't figure why audioop, imageop and _tkinter were not configured in > from the beginning (it's a linux system, after all; libraries and > includes are in the standard places, ie /usr/lib and /usr/include). I > am ATM browsing old posts in Google groups searching for pieces of a > 'python-configure-how-to', but any hints would be appreciated. I may be wrong, but I thought that audioop and imageop only work in a 32 bit environment. Cheers, mwh -- 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 skip at pobox.com Mon Sep 15 16:52:15 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 15 Sep 2003 15:52:15 -0500 Subject: _ssl.so build problems on Solaris 8 for 2.3 Message-ID: <16230.9855.525029.78461@montanaro.dyndns.org> I'm trying to build the released version of Python 2.3 on Solaris 8 for the first time. It has problems when building _ssl.so. The command generated is gcc -shared build/temp.solaris-2.8-sun4u-2.3/_ssl.o \ -L/usr/local/ssl/lib -L/usr/local/lib -lssl -lcrypto \ -o build/lib.solaris-2.8-sun4u-2.3/_ssl.so It generates an enormous table which begins with: Text relocation remains referenced against symbol offset in file 0x4 /usr/local/ssl/lib/libssl.a(ssl_ciph.o) 0x2c /usr/local/ssl/lib/libssl.a(ssl_ciph.o) 0x54 /usr/local/ssl/lib/libssl.a(ssl_ciph.o) 0x7c /usr/local/ssl/lib/libssl.a(ssl_ciph.o) 0xa4 /usr/local/ssl/lib/libssl.a(ssl_ciph.o) ... That goes on and on and on (it must print several hundred lines), finally finishing up with ... v2i_GENERAL_NAME 0xa1c /usr/local/ssl/lib/libcrypto.a(v3_alt.o) v2i_GENERAL_NAME 0x15c /usr/local/ssl/lib/libcrypto.a(v3_crld.o) v2i_GENERAL_NAME 0x2e8 /usr/local/ssl/lib/libcrypto.a(v3_info.o) ld: fatal: relocations remain against allocatable but non-writable sections collect2: ld returned 1 exit status Is distutils missing some libraries or have I hosed the OpenSSL installation somehow? 2.3b2 installed fine back in early July (including _ssl.so), though the OpenSSL install has been updated since then (end of July). Googling for "python solaris ssl" and checking the top-level README for "ssl" didn't turn up anything promising. Thanks, Skip From a.neudecker at uni-bonn.de Fri Sep 26 08:29:14 2003 From: a.neudecker at uni-bonn.de (Andreas Neudecker) Date: Fri, 26 Sep 2003 14:29:14 +0200 Subject: Where to import modules? Message-ID: Hi. I have a "style" question: Sometimes, modules will only be used in a particular, optional, part of a program (function, class), that will not always be used when the application is run. So I think it is better to import them only there, not on the top of the file (together with the other imports). Is that okay, or are there good reasons for not doing so? Regards Andreas From tim.one at comcast.net Sun Sep 21 18:42:19 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 21 Sep 2003 18:42:19 -0400 Subject: math.exp(complex) In-Reply-To: Message-ID: [Tim] >> Math libraries in general can return a better result for exp(x) than >> e**x, though, since the latter form uses a machine approximation to e >> as the base. [David Eppstein] > Doesn't look especially different to me, for the numbers I'm currently > interested in applying this to (small pure imaginary): > > >>> from cmath import * > >>> exp(1j*pi) > (-1+1.2246467991473532e-16j) > >>> e**(1j*pi) > (-1+1.2246467991473532e-16j) There are few shortcuts in numerical analysis. If you want to understand, and estimate how bad it *might* get over various input ranges, you'll have to do careful analysis of the implementations. You'll probably find that very hard, because the Python implementations build on the platform C's sin(), cos(), exp(), atan2(), pow() and hypot(), and few C vendors document the accuracy of their implementations -- you don't have the raw material then to estimate the accuracy and vulnerable areas of Python's implementations. For that reason, I can't tell you anything that's generally true across implementations. But you need only glance at c_exp in cmathmodule.c, and c_pow in compleobject.c, to convince yourself that c_exp() has far fewer places it can get into numerical trouble (it's a much simpler algorithm). From bgailer at alum.rpi.edu Sat Sep 20 14:16:23 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 20 Sep 2003 12:16:23 -0600 Subject: Visual Basic Procedure Names In-Reply-To: <3394230.1064059154@dbforums.com> References: <3394230.1064059154@dbforums.com> Message-ID: <6.0.0.22.0.20030920121602.028f38e0@66.28.54.253> At 05:59 AM 9/20/2003, nvm1980_in wrote: >I am writting an error hander module which should log Calling >Subroutine/Function which caused Subroutine or raised an error. I would >aso like to store Error Source, Description and Number. > >can any one help me for this. Not with that amount of explanation. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From sheu at bu.edu Tue Sep 30 14:31:23 2003 From: sheu at bu.edu (Shu-Hsien Sheu) Date: Tue, 30 Sep 2003 14:31:23 -0400 Subject: printing to files in python In-Reply-To: <35005.199.169.240.132.1064945924.squirrel@svr1.turboweb.net> References: <35005.199.169.240.132.1064945924.squirrel@svr1.turboweb.net> Message-ID: <3F79CBFB.7020907@bu.edu> An HTML attachment was scrubbed... URL: From davidcfox at post.harvard.edu Tue Sep 9 13:55:38 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Tue, 09 Sep 2003 17:55:38 GMT Subject: A couple of OOPython questions In-Reply-To: <3915d531.0309090812.6a4db47e@posting.google.com> References: <3915d531.0309090812.6a4db47e@posting.google.com> Message-ID: Alexy Khrabrov wrote: > OK, now I go to my python prompt and I want to inspect my objects as > returned by the CORBA server. One of them represents an atom site. I > merrily type just its name to see the great unknown unwrap before my > eyes. Here: > > >>>>a > > > > Hmm. That's not what I hoped for. Some fragments of code I saw run > through my mind and I type in, > > >>>>dir(a) > > ['_NP_RepositoryId', '__doc__', '__init__', '__module__', 'beg_auth', > 'beg_label', 'conf_type', 'details', 'end_auth', 'end_label', 'id'] > > Good, we're getting somewhere. I also googled out vars(a), which > seems to be the same as a.__dict__ (are they?... why is __dict__ not > shown above then? 2.2...) > > Printing out gazillion fields by hand for each class is silly, they > only wrap strings and numbers and other objects of that nature. I am > ready to dive in a recursive descent. No such luck -- whoever created > CORBA bindings for python didn't make those objects dictionary-like! > I can't get members by name, although they _are_ in some __dict__, > useless apparently, until I supply __getitem__! > > Is there an easy way to write something _once_, general enough, to > print out a hierarchy of nested objects which just don't have > __getitem__, although every field is either a string or a number or > another object? I'm not sure exactly what you are looking for, but here's a first attempt. Save the following to a Python file called recursive_repr, import recursive_repr, and try print recursive_repr.pr(x). import types def type_or_class(x): """returns the type of a variable x, or its class when the latter is more specific, so that the types of two variables can be compared """ t = type(x) if t is types.InstanceType: # for old-style classes, __class__ is more specific return x.__class__ # for built-in types and new-style classes return t def name_of_class(x): t = type_or_class(x) return "%s.%s" % (t.__module__, t.__name__) def pr(x): if hasattr(x, '__dict__'): # return "class %s: %s" % (name_of_class(x), pr(x.__dict__)) return {'class %s' % name_of_class(x) : pr(x.__dict__)} elif type(x) is type({}): d = {} for key, value in x.items(): d[key] = pr(value) # return repr(d) return d return x > > Cheers, > Alexy Khrabrov From llafba_NOSPAM_ at gmx.net Mon Sep 29 16:04:33 2003 From: llafba_NOSPAM_ at gmx.net (Tom) Date: Mon, 29 Sep 2003 22:04:33 +0200 Subject: write to log file Message-ID: Hi, I have a log file and of course I want to add the new information to the end of that log file. Unfortunately I always delete the old information and only append the current info. Right now I do it like this: I call a module which consists of a class and a function. It actually doesn't matter, but I just included it for the sake of completeness. The module looks like this: class log_C: def errorlog(self, filename, Data, d): LogFile = file(filename, 'w') ErrorInfo = Data[d+1] LogFile.write(ErrorInfo) LogFile.close() How can I add the new info without deleting the old info? I tried the modes 'a' and 'a+' but they both didn't work. Actually the data was totally unreadable! It was kind of messed up. I don't know why. Thanks for your help. Regards, Tom From jerf at jerf.org Tue Sep 2 22:33:49 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 03 Sep 2003 02:33:49 GMT Subject: Advice to a Junior in High School? References: <3d6c6fc3.0308261246.32db39d5@posting.google.com> <3d6c6fc3.0309020814.544db215@posting.google.com> Message-ID: On Tue, 02 Sep 2003 09:14:41 -0700, Stan Graves wrote: > Yes. I have had the mis-fortune of being a maintenance programmer for > far too much of my life. I have read reams of documentation, and > hundreds of thousands of lines of code. I have attempted to make > sense of code written to do one thing, but extended and tortured into > doing another. For what it's worth, you're reading the slush pile and judging the whole discipline with it, if that statement is accurate. To be fair, you need to be comparing the *best* of computer science against Shakespeare, not whatever happens to cross your desk. You can't judge English Novels by Danielle Steele, either. The whole "Turing Machine" bit (including the Halting Problem, incomputability, the whole "there are problems we can't solve, provably") has personally moved me a lot more then Shakespeare. Knuth has a piercing clarity. There are others. (Python itself is surprisingly larger then the sum of its parts, to stay on topic, and I'm not just saying that; I mean it.) (Actually, I'm not a fan of Shakespeare; he's good with words but I think he is worshipped because he was first; the first guys to be decent at something are held up as geniuses later, but I think the exact same work, done thirty years later after somebody *else* had been first, would be merely a historical footnote. So I'll take the larger point and extrapolate to "English masterpiece".) (On the later point, I'm agreeing to disagree.) From achalk at XXXmagnacartasoftware.com Wed Sep 24 04:45:54 2003 From: achalk at XXXmagnacartasoftware.com (Andrew Chalk) Date: Wed, 24 Sep 2003 08:45:54 GMT Subject: CGI Redirect to another page References: <4n9cb.1447$RW4.791@newsread4.news.pas.earthlink.net> Message-ID: <6Rccb.585$IN4.800663601@newssvr11.news.prodigy.com> Thanks, good web search! I couldn't get "Location:URL" to work but META did. Regards. "Andrew Dalke" wrote in message news:4n9cb.1447$RW4.791 at newsread4.news.pas.earthlink.net... > Andrew Chalk: > > Assume that I have a static HTML page that I want > > displayed (e.g. index.htm). Other than 'print ...' is there any way to > > redirect to this URL (for example, like Response.Redirect() in ASP)? > > The Response.Redirect likely works by putting something in > the header. The HTML page you have doesn't have access to > the header. However, you can use the meta tag to tell the > browser to look elsewhere. But that won't work for tools which > don't parse the HTML. > > It's an easy web search (once you know the right keywords :) - > "header redirect meta" and I found > http://vancouver-webpages.com/META/FAQ.html#redirect > "How can I redirect the user to another page ?" > with three different answers > > Andrew > dalke at dalkescientific.com > > > From secun at yahoo.com Thu Sep 25 08:18:17 2003 From: secun at yahoo.com (SectorUnknown) Date: Thu, 25 Sep 2003 12:18:17 GMT Subject: Windows dialog box removal Message-ID: I've written a Python script that runs a MS Windows program using popen. However, at the end of the Windows program, a dialog box appears and asks for the user to click on OK. Is there a way to have Python set focus on the dialog box and click OK so my script can continue? Does anyone have an example? From john at rygannon.com Mon Sep 15 04:59:42 2003 From: john at rygannon.com (John Dean) Date: Mon, 15 Sep 2003 08:59:42 GMT Subject: Could somebody please explain what is happening .... Message-ID: <3f657f95$0$10968$fa0fcedb@lovejoy.zen.co.uk> Hi I have been reading quite a lot of Python source code recently and I have come across a particular construct which I don't understand. I would be grateful if somebody could explain the reason for including the following lines of code. I have seen it only at the beginning of a module:- global sys import sys global os import os .... .... I know what global means and I know what import means but what is the reason for making an imported module global? -- Best Regards John From davecook at nowhere.net Mon Sep 8 17:56:11 2003 From: davecook at nowhere.net (David M. Cook) Date: Mon, 08 Sep 2003 21:56:11 GMT Subject: enum in Python References: Message-ID: <%V67b.653$NW3.617@news1.central.cox.net> In article , Andrew Chalk wrote: > As a rank Python beginner I've used a dictionary, but presumably there is a > better way. I've seen idioms like FOO, BAR, BAZ = range(3) used. Dave Cook From newsgroups at jhrothjr.com Fri Sep 5 10:35:42 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 10:35:42 -0400 Subject: in Ram database? References: Message-ID: "John D." wrote in message news:mailman.1062728122.8678.python-list at python.org... > Does anyone know if there is an "in-ram" dictionary based database > for Python. > > I can see some applications where this can really be powerful in > applications requiring 10,000 records or less. > > Is such a database available? If so, who is working on it, > or where is it? > > I've heard that Python supports a stand-alone database. I looked > for it in the Docs, and see the "dbm" module. I haven't found > any examples of code, so don't know how to use them. I'm one > of those guys that learn through examples, and have very little > luck in figuring out how to use anything unless I can see examples > of their use. > > My idea is that ALL datums would be Python Dictionary objects, so > not only can you store data, but python objects as well. > > Storage to disk would be through pickled files, or through CSV > format, allowing easy import and export from other databases. > > I'm sure something like this exists, I just haven't found it yet, > and if not, then I'm well on my way of implementing one myself. > > I kinda like the idea of being able to define smaller tables as > "in-memory" types, and the really large massive ones in other forms > managed by mySQL, PostGres, or bsddb3 databases. > > Any leads you guys??? Look at Prevalyar. While it's a Java project, it might give you some ideas about what's possible if you forget "data base" and simply think "persistance." John Roth > > JD > > > From peter at engcorp.com Thu Sep 11 17:16:53 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 11 Sep 2003 17:16:53 -0400 Subject: why is this failing? References: <9x58b.139$u07.2@newsread1.news.atl.earthlink.net> Message-ID: <3F60E645.2501B9EE@engcorp.com> Chris Curvey wrote: > > I've looked at this so long that I must be looking right past it. This > code: > > class Page: > ########################################################## > def write(self, value, row=None, col=None, len=None): > print isinstance(value, str) > > # error occurs on this line > print len(value) > > ######################################################## > if __name__ == "__main__": > p = Page() > > p.write("banana") > > is throwing this error: > > True > Traceback (most recent call last): > File "P2.py", line 13, in ? > p.write("banana") > File "P2.py", line 7, in write > print len(value) > TypeError: 'NoneType' object is not callable Reading the error more closely, and examining the line that is failing, you can see that the only call being made is to len(), but the error is telling you that the name "len" is actually bound to None! How could that happen? Check your list of arguments to the write() method... Don't use names of builtins and your life will be easier. :-) -Peter From tjreedy at udel.edu Mon Sep 8 15:03:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 8 Sep 2003 15:03:23 -0400 Subject: "Python Redesign" (fwd) References: Message-ID: "Tim Parkin" wrote in message news:mailman.1063031798.22437.python-list at python.org... > >What we were directed to was *not* a mockup (model), but an image of a > >mockup. That mislabeling was a source of misunderstanding which > >generated part of the criticism. Please let us keep the useful > >distinction between a thing and an image of the thing. > >Terry J. Reedy > > From the Shorter Oxford English Dictionary - Eight Edition > "Mock Up - An experimental model or replica of a proposed structure" Right, and I contend that an image is definitely not 'an experimental model' (that one can experiment with) nor, in this context, a 'replica' of the proposed structure. > Tim - 'only posting to defend my right to use dictionary english' Ditto, tho with different interpretation thereof. I repeat my request to not try to eliminate the useful distinction between things and images thereof. I think Rene 'Ceci n'est Pas une Pipe' Magritte had it right. Terry J. Reedy From jjl at pobox.com Thu Sep 11 13:27:38 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Sep 2003 18:27:38 +0100 Subject: safari References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <51809ae4.0309040634.7999e400@posting.google.com> <51809ae4.0309110734.1e5d28be@posting.google.com> Message-ID: <87y8wvfd6d.fsf@pobox.com> lefevrol at yahoo.com (Olivier Lefevre) writes: > > It's got over 1,000 books -- I doubt they can ALL be best-sellers, > > can they? > > What I mean is that it seems to have only language or API how-to kind > of books, i.e., those that appeal to working programmers, the largest > audience. A contrario look under Computer Science, AI or Functional > Programming: it's pitiful. Yet the CS book market is also large, [...] Isn't that just because that's the kind of stuff O'Reilly publishes? Addison-Wesley, Wiley &c. tend to do the books that are more on the software engineering and CS side. Or does Pearson Education have something to do with it -- I noticed their site mentioning a 'Safari' a while back, and at the time assumed that was a copy, but I think Alex mentioned them in this thread. Are Pearson and O'Reilly owned by a single company, or something? I have a vague recollection that Pearson owns some other companies... John From jepler at unpythonic.net Mon Sep 15 17:10:39 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 15 Sep 2003 16:10:39 -0500 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: References: <5.1.1.6.0.20030911162016.02027750@telecommunity.com> <3F632226.2010607@earthlink.net> Message-ID: <20030915211033.GO32270@unpythonic.net> Harri, I don't understand how your suggested changes, even once carried out, will let me use threads to increase the speed of a CPU-intensive Python program. For instance, consider the following code: solutions = [] def is_solution(l): # CPU-intensive code here. Let's say it runs for 1 second per call def consider_solution(l): if is_solution(l): solutions.append(l) def problem_space(l): # A generator of items in the problem space # pretty fast! ... yield l def all_solutions(): for l in problem_space: consider_solution(l) I could thread it, so that N threads each run is_solution on a different candidate: def all_solutions(): queue = worker_tasks(consider_solution, N) for l in problem_space: queue.add(l) queue.shutdown() But with your proposed changes, it sounds like each thread becomes an island, with no access to common objects (like the list "solutions" or the queue connecting the main thread with the worker threads). If threading truly worked, then I'd be able to run efficiently on n*1 CPUs, where n is the ratio of the speed of one iteration of is_solution compared to one iteration of problem_space. On the other hand, I can make the above work quickly today by using processes and pipes. I can do this only because I've identified the parts that need to be shared (the queue of candidate solutions, and the list of confirmed solutions). I think that's the same level of effort required under the "thread is an island" approach you're suggesting, but the processes&pipes code will likely be easier to write. Jeff From mynews44 at yahoo.com Fri Sep 19 01:43:51 2003 From: mynews44 at yahoo.com (google account) Date: 18 Sep 2003 22:43:51 -0700 Subject: string objects... Message-ID: I know that string.letters and string.digits are all the letters and numbers, is there a string.???? that is a subset of all the ascii characters that are available on a US English Keyboard without going to special characters (like ? or ?) I couldnt see anything that was explaining this stuff on the python.org site. I think what I want is soemthing like string.printable - string.whitespace but that doesn't seem to work like string.letters + string.numbers... TIA Googleboy From geoff at gerrietts.net Fri Sep 12 11:42:22 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 12 Sep 2003 08:42:22 -0700 Subject: safari (was Re: Writing solid code book) In-Reply-To: <3f617389.593042620@news.blueyonder.co.uk> References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <3f617389.593042620@news.blueyonder.co.uk> Message-ID: <20030912154222.GA4211@thoth.homegain.com> Quoting Alan Gauld (alan.gauld at btinternet.com): > On Thu, 11 Sep 2003 19:14:05 -0600, Jules Dubois > wrote: > > However, seeing for the first time Python's syntax in _Nutshell_ was enough > > to scare me away. > > Really? Can I ask why? I'd have thought seing Pythons syntax > would be a breath of frsh air to most programmers, it certainly > was for me. Why did you think it was scary? I know I resisted the idea of significant whitespace for something like six months, despite evangelical friends, before I turned away from the dark side. Perhaps not coincidentally, I began reconsidering my opinion at approximately the same time I became responsible for extension of a Perl script written by a fellow who was just coming to understand use of references in Perl. --G. -- Geoff Gerrietts "There is no fate that cannot be surmounted by scorn." --Albert Camus From theller at python.net Thu Sep 25 11:39:45 2003 From: theller at python.net (Thomas Heller) Date: Thu, 25 Sep 2003 17:39:45 +0200 Subject: Windows dialog box removal References: Message-ID: Dave Brueck writes: > On Thursday 25 September 2003 06:18 am, SectorUnknown wrote: >> I've written a Python script that runs a MS Windows program using popen. >> However, at the end of the Windows program, a dialog box appears and >> asks for the user to click on OK. >> >> Is there a way to have Python set focus on the dialog box and click OK >> so my script can continue? >> >> Does anyone have an example? > > I wouldn't be surprised if there's an easier or more correct way to do this, > but if you can reliably know the title of the window then the code below > should work (assuming you have ctypes installed): [example snipped] I've added this example to the ctypes wiki, so it will not be lost. Hope that's ok ;-) Thomas From christophe.delord at free.fr Wed Sep 17 16:14:50 2003 From: christophe.delord at free.fr (Christophe Delord) Date: Wed, 17 Sep 2003 22:14:50 +0200 Subject: replace %(word) in a string References: Message-ID: <20030917221450.1647ef73.christophe.delord@free.fr> On 17 Sep 2003 16:30:08 GMT, Fred Pacquier wrote: > Mirko Zeibig said : > > > Especially useful together with the locals() function, which returns > > a dictionary of locally defined variables: > > > > def foo(): > > a = "Hello" > > b = "World" > > print "%(a)s %(b)s" % locals() > > Yes, that's a wonderful feature. Recently though, I've wondered a > couple of times : is there an easy way to substitute with both local > AND global variables ?... > You can substitute local and global variables. But you can do much more. You can write a python expression in %(...)s if the object on the right side of % looks like a dictionnary and can evaluate its argument. For example I often this piece of code: class I: def __getitem__(self, item): frame = sys._getframe(1) return eval(item, frame.f_globals, frame.f_locals) As I only need one instance of I, I use: I = I() Then I can write thing like that: word1 = "python" word2 = "lovers" print "Hello, %(word1)s %(word2)s !"%I And even: print "1 + 1 = %(1+1)s"%I But you must keep in mind that the use of eval may not be safe. Christophe. -- (o_ Christophe Delord __o //\ http://christophe.delord.free.fr/ _`\<,_ V_/_ mailto:christophe.delord at free.fr (_)/ (_) From gerrit at nl.linux.org Mon Sep 8 10:00:06 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 8 Sep 2003 16:00:06 +0200 Subject: Giving the FAQ a more prominent place (UTB: Re: Comments on Python Redesign) In-Reply-To: <3F5B8C51.6462BC38@alcyone.com> References: <3F5B8C51.6462BC38@alcyone.com> Message-ID: <20030908140006.GB5991@nl.linux.org> Erik Max Francis wrote: > Tim Parkin wrote: > > Perhaps the people who have commented on the site should realise it's > > a proposal and a work in progress. > > Could someone remind me what need there is for a redesign in the first > place? Of all the Python-related efforts that one could put time into, > this seems like one of the least useful. What I *do* think, is that it would be useful to put the FAQ more prominently on the site. Maybe posting the FAQ to c.l.py weekly, in a separate post, also helps. I don't really mind seeing questions answered in the FAQ, but it will help because the FAQ is not very easy to find. (The FAQ actually _is_ linked from the front page of www.python.org, but there are exactly 114 links on the front page: not exactly easy to find the FAQ between them, especially if you're new) Gerrit. -- 107. If the merchant cheat the agent, in that as the latter has returned to him all that had been given him, but the merchant denies the receipt of what had been returned to him, then shall this agent convict the merchant before God and the judges, and if he still deny receiving what the agent had given him shall pay six times the sum to the agent. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From eniac at sdf-eu.org Tue Sep 2 17:08:38 2003 From: eniac at sdf-eu.org (Geiregat Jonas) Date: Tue, 02 Sep 2003 21:08:38 +0000 Subject: cli arguments Message-ID: <3f5506d5$0$8546$ba620e4c@reader0.news.skynet.be> What is the module called that's made to dael with cli argument's like --foo-bar -c -blabla ? From niemeyer at conectiva.com Tue Sep 16 13:06:27 2003 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Tue, 16 Sep 2003 14:06:27 -0300 Subject: Datetime utility functions In-Reply-To: <16E1010E4581B049ABC51D4975CEDB8803060C81@UKDCX001.uk.int.atosorigin.com> References: <16E1010E4581B049ABC51D4975CEDB8803060C81@UKDCX001.uk.int.atosorigin.com> Message-ID: <20030916170627.GA4026@ibook.distro.conectiva> > > Have a look at this: > > I like that. I'm not entirely happy with the name of the class, but as > I can't come up with a better suggestion, I shouldn't criticise... The name explains it pretty well. It's like timedelta, but it's a "relative" delta, since how much it will advance will depend on the date you apply it to. [...] > Sorry, I didn't explain that very well. Imagine an application to report > stats over a period. The user can specify a date, and the report will be > for a calendar month, containing the user's required date. So my code > will be something like > > start = user_date.replace(day=1) # Start of the month > end = "Last day of the month" Oh! Ok.. I understand now. [...] > With your "relativedelta" I could do this pretty easily, by > > end = start + relativedelta(months=+1, days=-1) Hummm.. no. Look: >>> date.today()+relativedelta(months=+1, days=-1) datetime.date(2003, 10, 15) Instead, it should be done by: >>> date.today()+relativedelta(months=+1, day=31) Notice that it works also for other months: >>> date.today()+relativedelta(month=2, day=31) datetime.date(2003, 2, 28) This is described in step 4 of the documentation I pasted in the mail. > but I still feel that I'd need to have an explanatory comment. The > datetime module *knows* the number of days in the month - I'd just > like it to tell *me*. Have you noticed that this is also offered by the calendar module? >>> import calendar >>> calendar.monthrange(2003, 9) (0, 30) -- Gustavo Niemeyer http://niemeyer.net From edreamleo at charter.net Wed Sep 3 09:14:14 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 3 Sep 2003 08:14:14 -0500 Subject: Hunting a memory leak References: <7h3oey84qho.fsf@pc150.maths.bris.ac.uk> Message-ID: > Yeah... using this approach I was finally able to hunt the leak!!!. ... > Anyway, thanks very much for the advices and encouragement! You are welcome. IMO, if you can track down memory problems in C you can debug just about anything, with the notable exception of numeric programs. Debugging numeric calculations is hard, and will always remain so. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From rob at cs.brown.edu Mon Sep 29 16:47:07 2003 From: rob at cs.brown.edu (Rob Hunter) Date: Mon, 29 Sep 2003 16:47:07 -0400 Subject: isNumber? check In-Reply-To: <20030929204143.GA8765@nl.linux.org> Message-ID: <16E3AA52-F2BE-11D7-9145-003065F081D2@cs.brown.edu> On Monday, September 29, 2003, at 04:41 PM, Gerrit Holl wrote: > Rob Hunter wrote: >> On Monday, September 29, 2003, at 10:20 AM, Gerrit Holl wrote: >>> Rob Hunter wrote: >>>> How do I check if a value is a number in Python? >>>> >>>> >>>> >>> >>> Why do you want to do so? >> >> >> I am writing an interpreter, and my parser has to decide if an >> expression is a number or not. > > So you actually have a string... > > Maybe you could do something like this: > > if expr.strip("0123456789.e") == "": print "May be a number!" > if expr.strip("0123456789") == "": print "Surely a number!" > > Gerrit. > I don't like that solution for this particular project because, as you say yourself, if it says yes to the second question, it only *may* be a number. I want to know for sure. I think the type or instance checks as the other posters mentioned are going to be fine for me. OTOH, thanks for the suggestion! That's a cool little hack that I'm sure will come in handy to me in the future. Rob From eppstein at ics.uci.edu Tue Sep 16 16:43:11 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 16 Sep 2003 13:43:11 -0700 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> Message-ID: In article <95b4b9ac.0309161015.6a0567a7 at posting.google.com>, hildegarde_roth at yahoo.de (Hilde Roth) wrote: > This may have been asked before but I can't find it. If I have > a rectangular list of lists, say, l = [[1,10],[2,20],[3,30]], is > there a handy syntax for retrieving the ith item of every sublist? > I know about [i[0] for i in l] but I was hoping for something more > like l[;0]. >>> l = [[1,10],[2,20],[3,30]] >>> zip(*l)[0] (1, 2, 3) -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From dave at boost-consulting.com Tue Sep 30 19:03:36 2003 From: dave at boost-consulting.com (David Abrahams) Date: Tue, 30 Sep 2003 19:03:36 -0400 Subject: python, vtk, C++ References: <87d6dicwt0.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > "Yi-Yu Chou" writes: > >> I want to use python as my GUI to load a 3D volume (vtkImageData), >> and use a pointer to pass this 3D image to my own C++ class. >> My question is I don't know how to communicate between python and C++. >> Any suggestion would be appreciated. > > Google. I think I can be a little more helpful than that: http://www.boost.org/libs/python http://www.swig.org HTH, -- Dave Abrahams Boost Consulting www.boost-consulting.com From JoeyTaj at netzero.com Tue Sep 30 16:04:52 2003 From: JoeyTaj at netzero.com (Paradox) Date: 30 Sep 2003 13:04:52 -0700 Subject: can i implement virtual functions in python ? References: Message-ID: <924a9f9c.0309301204.42025a5e@posting.google.com> I think you can do something like this. class Virtual: def myFunc(self, x): pass class Implement(Virtual): def myFunc(self, x): return x * x From davidcfox at post.harvard.edu Thu Sep 18 14:25:19 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Thu, 18 Sep 2003 18:25:19 GMT Subject: Indexing list of lists In-Reply-To: <95b4b9ac.0309180950.30b44d89@posting.google.com> References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <95b4b9ac.0309171233.21f4c07@posting.google.com> <95b4b9ac.0309180950.30b44d89@posting.google.com> Message-ID: Hilde Roth wrote: >>Like it or not, there are no "different dimensions", just lists of lists >>of lists... > > > You are being too litteral. A list of list is like a 2D array from an > indexing point of view, a list of lists of lists like a 3D array etc. > E.g., (((1,10),(2,20),(3,30)),((-1,'A'),(-2,'B'),(-3,'C'))) is a > 2 x 3 x 2 rectangular data structure and has 3 dimensions. Hence, > e.g., l[0;2;1] ~ l[0][2][1] = 30 Only if all the sublists are of the same length, which is guaranteed for a multi-dimensional array, but not for a list of lists. What do you expect a[;1] to return if a = [[], [1, 2, 3], [4], 5]? That's why Numeric has a specific type for multi-dimensional arrays. David From indigomoonBLINDERS at bonbon.net Sat Sep 20 03:48:57 2003 From: indigomoonBLINDERS at bonbon.net (Indigo Moon Man) Date: Sat, 20 Sep 2003 01:48:57 -0600 Subject: py2exe web site References: Message-ID: Michael Geary spake thusly: > > Starship has been having DNS trouble--again! You can get there with the IP > address: > > http://217.160.219.194/ > or > http://217.160.219.194/crew/theller/py2exe/ > Hey, great. Thank you for the info! -- Remove BLINDERS to email me. Audio Bible Online: http://www.audio-bible.com/ From aleax at aleax.it Sat Sep 27 04:49:00 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 27 Sep 2003 08:49:00 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> Message-ID: <0acdb.128801$hE5.4391247@news1.tin.it> David Abrahams wrote: ... >> I always assumed that these were considered inconsistent with normal >> use of tuples (which certainly I rarely need to get 'index' or >> 'count'-like results from). > > I don't see why not. The party line (not saying I necessarily agree, mind you -- just relating it) is that tuples are meant as semantically heterogeneous containers (semantically in that the items may happen to be the same type, but their _meaning_ is disparate: e.g., consider the tuples used in modules time or stat). So it doesn't really make sense to iterate on them, either; it just happens to be possible because their items are accessed with [] with progressive naturals, and they have a len(). Associating _names_ to the indices makes more sense and indeed such pseudo-tuples are starting to be supplied by the standard library (though not a general mechanism for making your own, yet). Much like you can't iterate in C++ on a std::pair<>, thus you "shouldn't" be able to iterate on a tuple. "Frozen" versions of lists and dicts might make more sense -- and lose only the MUTATING methods. I've seen Ruby experts claim that the idea of freezing an object looks cool but in practice you end up almost never using it -- they're speaking from experience, I guess, since in Ruby they've had the possibility of freezing any object for ages. However, my intuition (not supported by that much specific experience) makes me yearn for such a feature... Alex From theller at python.net Thu Sep 25 04:52:32 2003 From: theller at python.net (Thomas Heller) Date: Thu, 25 Sep 2003 10:52:32 +0200 Subject: RELEASED Python 2.3.1 References: Message-ID: "Cousin Stanley" writes: > | There's a checkbox which you can uncheck > | to disable installing the htmlhelp file. > | > | Then you can download the HTML archive > | and install it manually. > > Thomas .... > > Thanks for the reply .... > > It's good to know that an alternative > for the individual HTML doc files will remain .... > > Would it be feasible to eliminate the Python Docs > from the standard distribution and always download > separately if desired ???? > > This would eliminate downloading the docs twice > if the user wants the separate doc files and provide > a leaner download for non-programming Python users > that will never develop anything in Python themselves > but who want a run-time environment only .... Of course it would be possible, but it would certainly add confusion if there were several downloads to select from. Thomas From geoff at gerrietts.net Fri Sep 19 19:48:18 2003 From: geoff at gerrietts.net (Geoff Gerrietts) Date: Fri, 19 Sep 2003 16:48:18 -0700 Subject: whitespace In-Reply-To: References: Message-ID: <20030919234817.GC2478@thoth.homegain.com> Quoting RR (rr84 at cornell.edu): > Is there an easy way in python to remove whitespace from a string? Depending on what you mean by "remove whitespace": >>> mystring = " a b c d e f g " >>> mystring.strip() 'a b c d e f g' >>> import re >>> re.sub("\s+", "", mystring) 'abcdefg' > -- > http://mail.python.org/mailman/listinfo/python-list -- Geoff Gerrietts "Whenever people agree with me I always feel I must be wrong." --Oscar Wilde From fredrik at pythonware.com Tue Sep 9 10:57:44 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 Sep 2003 16:57:44 +0200 Subject: Unicode Newbie References: <20030909162009.0247ce9d.sylphaleya@hta.fhz.ch> Message-ID: Manuel Huesser wrote: > The unicode function implies that you only can use 2 ** 16 chars > (unichr supports only this range) but with a given encoding e.g. > unicode(",,,", "utf-8") i should be able to encode > up to 2** 31 chars. Nope. Read on. > "\xfc\x12\x12\x12\x12\x12\x12" is an example for a 7 > byte utf-8 string. But on encoding i get the following > error: > > UTF-8 decoding error: unsupported Unicode code range Unicode supports ~2**20 code points (17*64k), not 2**31 characters. Your example is not a valid UTF-8 string. > Is there any possibility to do the job? Not if you're using a conforming Unicode implementation. From christoph at mmc-startup.com Wed Sep 24 10:26:10 2003 From: christoph at mmc-startup.com (Christoph Becker-Freyseng) Date: Wed, 24 Sep 2003 16:26:10 +0200 Subject: Pre-PEP: reverse iteration methods In-Reply-To: References: Message-ID: <3F71A982.6050006@mmc-startup.com> I like the idea of having some iterator.backwards, backwards(iterator) etc. However especially reading Andrew Dalke's postings and replies (and having thought about using internally len() and so on --- but then thinking of iterator maybe having *no* __len__) I now think that reverse iteration is not well defined when __len__ can't be defined (and sometimes even if it is). This is not the case for list-like objects as they have a predictable fixed length (even if the __len__-method isn't actually implemented). Let me give an example: class NaturalNumbers: def __init__(self): self.n= 0 def __iter__(self): return self def next(self): self.n+=1 return self.n This is surely ordered but defining the reverse-order is difficult. Maybe it should always return infty then. Or think about a "Tape-Iterator". An object that reads data from e.g. a file forwards/next and backwards/iter_backwards. What would you expect to get if tape is at position x and you say tape.backwards()? Should it be the last byte of the file or maybe that on position x-1 ? This shows that we can get into trouble when we have already iterated "in the right direction" and then start to do "backwards". While reverse-iteration is a sound idea we need a clear definition of what is meant! I thought of the following (I give multiple possibilies named a,b,c, ... finally only one may be used): 1. If iterator has fixed/determined length (so it could be converted into a regular list): a) iterator.iter_backwards() creates an independent reverse-iterator: 1.1) l2= list(iterator) l1= list(iterator.iter_backwards()) l2.reverse() l1 and l2 have to be equal 1.2) l1= list(iterator.iter_backwards()) l2= list(iterator) l2.reverse() l1 and l2 have to be equal (next cases as examples for simplicity) 1.3) it= range(4) it.next() l1= list(it.iter_backwards()) l2= list(it) -> l1 == [3,2,1] l2 == [1,2,3] 1.4) it= range(4) itBack= it.iter_backwards() l1= [itBack.next(), itBack.next(), itBack.next()] l2= [it.next(), it.next(), it.next()] -> l1= [3,2,1] l2= [0,1,2] b) iterator.iter_backwards() creates a dependent reverse-iterator: 1.1) 1.2) like in a) (next cases as examples for simplicity) 1.3) it= range(4) it.next() l1= list(it.iter_backwards()) l2= list(it) -> l1 == [0,] l2 == [0,1,2,3] 1.4) it= range(4) itBack= it.iter_backwards() l1= [itBack.next(), itBack.next(), itBack.next()] l2= [it.next(), it.next(), it.next()] -> l1= [3,2,1] l2= [1,2,3] 2. Infinite/non-determined iterators: They should implement reverse-iteration in a way that iterator.next() iterator.iter_backwards().next() is a nop and iterator.iter_backwards().next() iterator.next() is a nop, too. Or if there are more backward than forward-steps should raise some StopBackwardIterator I'm sure there are a lot more and probably better definitions, so I hope we will find a useful one. Christoph Becker-Freyseng From jjl at pobox.com Thu Sep 18 08:47:13 2003 From: jjl at pobox.com (John J. Lee) Date: 18 Sep 2003 13:47:13 +0100 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <95b4b9ac.0309171233.21f4c07@posting.google.com> <877k46e0sz.fsf@pobox.com> Message-ID: <87vfrq6z72.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: [...] > (no special syntax, but lots of useful functions and 'ufuncs'). [...] Oops, wrong. See my other post. John From simonb at webone.com.au Wed Sep 10 18:42:48 2003 From: simonb at webone.com.au (Simon Burton) Date: Thu, 11 Sep 2003 08:42:48 +1000 Subject: TTF fonts rendered in Python References: Message-ID: One idea: pygame can render with TTF fonts, it can also save surfaces in tga format. Then use PIL to convert to gif. The only question is, can pygame do this without displaying a window etc. Simon Burton. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Sep 29 14:52:42 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Mon, 29 Sep 2003 19:52:42 +0100 Subject: A startup puzzle References: <7h365jb1lzo.fsf@pc150.maths.bris.ac.uk> Message-ID: On Mon, 29 Sep 2003 18:40:47 GMT, Michael Hudson wrote: >Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: > >> On Mon, 29 Sep 2003 11:31:05 -0500, "Edward K. Ream" >> wrote: >> >> >Any ideas for a clean solution? Thanks. >> >> I am not sure that I understand what you are saying, but I'll make a >> quick suggestion... >> >> Perhaps 'app' can be a global variable within 'leoGlobals', but >> assigned the value 'None' when the module is imported. Your >> initialisation code can then reassign the variable at the appropriate >> time. > >This wont work. > >--- a.py --- >a = None >--- b.py --- >import a >a.a = 1 >--- c.py --- >from a import a >import b >print a > >running c.py will print "None". Names, objects and bindings, remember >:-) Oops - I didn't realise import worked like that. Thanks. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From juneaftn at REMOVETHIShanmail.net Thu Sep 4 20:16:50 2003 From: juneaftn at REMOVETHIShanmail.net (Changjune Kim) Date: Fri, 5 Sep 2003 09:16:50 +0900 Subject: best book in years References: Message-ID: "Patrick Useldinger" wrote in message news:opruzmelopdd8opo at news.vo.lu... > Hi All, > > I am going to stay in hospital for a week or so (nothing serious), and am > trying to find a book or two to read there. As I have not come across > anything spectacular recently (except Python in a Nutshell), I would like > to know what *you* consider to be the best book you have read in the last > few years, about Python or IT in general. > > -Patrick The Nature of Order series (currently No. 1 is out). It is a magnum opus. It will change your concept of "(Alexandrian) patterns". "... Book 2 alone is likely to change the whole field of Computer Science ... " --Richard Gabriel, Department of Computer Science, Stanford University. (Richard's Patterns of Software, which has been openned on the internet for free a few weeks ago, is also recommended) With best regards, June From aleax at aleax.it Tue Sep 30 03:58:27 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 30 Sep 2003 07:58:27 GMT Subject: append special chars with "\" References: <3f793544$0$64721@hades.is.co.za> Message-ID: tertius wrote: > Is there a better way to append certain chars in a string with a > backslash that the example below? > > chr = "#$%^&_{}" # special chars to look out for > str = "123 45^ & 00 0_" # string to convert > n = "" # init new string > for i in str: > if i in chr: # if special character in str > n+='\\' # append it with a backslash > n+=i > print "old:",str > print "new:",n If you can afford some a priori preparation, make a dictionary once and for all that maps each character (that isn't to be represented by itself) to the string that represents it. E.g., if you inevitably start with a chr string as above, you can make the dictionary as follows: charmap = {} for c in chr: charmap[c] = c+'\\' You can also write out the dict literal directly, and in any case you only need to prepare this charmap once and can then use it to prepare any number of translations. Once you have this charmap, you can use its get method to get the translations -- and prepare a *LIST OF STRINGS* to be joined up at the end, that's MUCH, *MUCH* faster than a loop using += on a string: pieces = [charmap.get(c,c) for c in str] and finally: n = ''.join(pieces) Alex From tzot at sil-tec.gr Tue Sep 16 17:17:55 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 17 Sep 2003 00:17:55 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: Message-ID: On Tue, 16 Sep 2003 20:06:00 +0300, rumours say that Harri Pesonen might have written: >There is no object-level locking in my proposal. Just independent >free-threaded interpreters, which don't see the objects of other >interpreters at all. What's the point in using threads then? Threading implies easy access to shared data. >There could be an extra global interpreter state for shared-memory >object access. Accessing this would always be synchronized, but only >this. Python would automatically copy data from this state to >thread-local state and back when needed. This would require a special >syntax for variables in global state: >synchronize a = "asdf" In *this* case, POSH (or similar shared memory mechanisms) and multiple processes should be a simpler solution. UNIX systems have managed for decades to work very well without any threading mechanisms. pipe() and fork() are quite older than threads and queues! :) I do know the usefulness of threads, and I do use them [1]. But, re-read what you wrote above, and please explain: what in your opinion is the advantage of multiple threads over multiple processes in this case? [1] For example, I have a script that collects data over XML-RPC from other machines in my company's network, does a little processing on the data (mostly calculating md5 sums) and reads and writes local files; when running on a 2x500MHz P3 Linux, I've seen it reach up to 134% (command 'top' shows full utilisation of *one* CPU as 100%); running on a 2x1GHz P3 W2k machine, task manager shows up to 74% (with a lower averaging interval, peaks are easier to spot). Think I would do better without the GIL? In the few cases where I would love to have "free" threading in Python (eg an image comparison script of mine), I have already implemented the heavy calculations in C, allowing python threads in the meanwhile. Threads are most useful when doing mostly CPU-intensive calculations; Python is not created for these, but it is an excellent glue language. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From __peter__ at web.de Mon Sep 15 03:18:45 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 Sep 2003 09:18:45 +0200 Subject: Finally found a use for lambda! References: Message-ID: Roy Smith wrote: > My apologies for a somewhat silly posting, but after 6 years of hacking > Python, I finally found a use for lambda! I wanted to write a unit test > to prove that a given dictionary does not have a given key. Since > assertRaises requires its second argument to be something callable, > instead of writing: > > self.assertRaises (KeyError, foo['bar']) > > I had to write: > > self.assertRaises (KeyError, lambda: foo['bar']) > > Of course, now that I think about it, I could have also written: > > self.assertEqual (foo.has_key ('bar')), 0) This is not strictly equivalent, i. e. for a custom dictionary you should perform both tests. If assertEqual() is sufficient, then how about self.failIf("bar" in foo) which seems as explicit as you can get without using plain english. > so I guess I didn't really need the lambda after all :-) Same goes for me since I converted from map() to list comprehensions. Peter From __peter__ at web.de Wed Sep 17 13:22:14 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Sep 2003 19:22:14 +0200 Subject: fast way to filter a set? References: Message-ID: Fortepianissimo wrote: > I know I can do things like > > s=Set(range(1,11)) > s=Set(filter(lambda x:x%2==0,s)) > > But this seems a bit slow since filter returns a list which then must > be converted back to a set. Any tips? Thanks! The Set constructor accepts any iterable, so you can do it all with iterators instead of temporary lists: from sets import Set from itertools import ifilter s = Set(range(1, 11)) print Set(ifilter(lambda x: x % 2 == 0, s)) Peter From peter at engcorp.com Mon Sep 22 14:20:22 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Sep 2003 14:20:22 -0400 Subject: Memory allocation References: Message-ID: <3F6F3D66.6EFF21B6@engcorp.com> "Batista, Facundo" wrote: > > How could I know how much memory uses an object? > > Something like: > > >> a = [66] > >> memused(a) > n Can you provide more background on the specific problem you need to solve, or are you looking for a very general solution? In other words, do you just need to know how much memory a list, or an integer uses up, or do you think you need a general-purpose function which works with any object of any type. And in the above example, would you be interested in the memory used by the integer 66, or the memory used by the list that contains a reference to that integer, or the combined total? -Peter From newsgroups at jhrothjr.com Sun Sep 14 18:41:43 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 14 Sep 2003 18:41:43 -0400 Subject: No "side effect" assignment! References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> Message-ID: "Tobiah" wrote in message news:0fbc28ebd2ba4810db3efef3a29f990a at news.teranews.com... > Ok, > > I miss the idiom that my other languages use, > something like: > > > while( foo = getmore()){ > process(foo); > } > > > I can't seem to do this in python without gagging: > > foo = getmore() > while foo: > process(foo) > foo = getmore() > > > Is that what ppl do? The manual sez that this is > so that newbs won't do: > > if foo = bar: > process() > > thinking that they are checking for equality. > I feel that in a few ways python suffers by catering > to the uninitiated. Usually however, there are > great workarounds (or even plain better ways to do the job), > which I am hopeful will be yielded by the list, as has > been it's record thus far to do. While one of Guido's reasons for not including assignment as an expression was to avoid errors (and that's not always a novice error,) Python provides similar functionality in the 'for' statement. In C, C++ and Java, 'for' is basically syntactic sugar around a loop, in Python, it actually does an assignment of the next element of a sequence. Your example could be: for foo in getmore: process(foo) as long as getmore is either a sequence or implements the iterator protocol. This isn't a total replacement for assignment as an expression, but it does cover the overwhelming majority of use cases. John Roth > > Thanks, > > Tobiah > From simonb at webone.com.au Sat Sep 20 02:52:23 2003 From: simonb at webone.com.au (Simon Burton) Date: Sat, 20 Sep 2003 16:52:23 +1000 Subject: spam killing with poplib Message-ID: This was so easy :) Simon Burton. #!/usr/bin/env python import sys from time import sleep from poplib import * canit = """Newest Internet Critical Pack New Internet Upgrade Message: User unknown Last Net Critical Patch last pack error notice Failure Advice failure message Bug Message Newest Internet Critical Pack Advice last net security pack Latest Microsoft Security Upgrade Latest Upgrade Last Network Critical Update Current Net Security Pack new net pack Last Network Security Pack Security Pack Security Update Critical Upgrade Undelivered Message Security Upgrade Net Update security pack Bug Letter Network Pack New Net Update """.split("\n")[:-1] #print canit #sys.exit(0) def doit(): mbox = POP3( "pop.webone.com.au" ) mbox.user( "XXX" ) mbox.pass_( "XXX" ) stat = mbox.stat() print "stat",stat ilist = mbox.list() olist = [] for info in ilist[1]: info = str.split( info ) i, sz = int(info[0]), int(info[1]) spam = 0 print "msg #%.3d\t%d"%( i, sz ) header = mbox.top( i, 0 )[1] subject = "" sender = "" for line in header: #print "\t",line if line.startswith( "From:" ): sender = line if line.startswith( "Subject:" ): subject = line if line.startswith( "SUBJECT:" ): subject = line if line.startswith( "X-Spam-Level" ): spam = line.count( "*" ) if subject: print " "+subject if sender: print " ", sender print " spam", spam sz_chk = 140000 2: # life is harsh print " dele" #mbox.dele( i ) # uncomment when you are ready print "quit" mbox.quit() while 1: print doit() sleep(90) From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Tue Sep 30 13:21:45 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Tue, 30 Sep 2003 19:21:45 +0200 Subject: RELEASED Python 2.3.2, release candidate 1 In-Reply-To: References: Message-ID: <3f79bba8$0$58712$e4fe514c@news.xs4all.nl> Anthony Baxter wrote: > On behalf of the Python development team and the Python community, I'm > happy to announce the release of Python 2.3.2 (release candidate 1). Thankfully it appears that there's not too much wrong with 2.3.1, is there? I just upgraded :-) Anyway, the docs (on windows) read "Release 2.4a0"... has this been addressed in the docs packaged with 2.3.2? Not that this is a big issue-- but it is a bit confusing. --Irmen de Jong From aleax at aleax.it Fri Sep 5 06:39:37 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 10:39:37 GMT Subject: Output in color References: Message-ID: Bradford Powers wrote: > I'm curious how I can make Python print text in color. That depends strictly on your printer. With my hp LaserJet 1200, no way -- not even Python's power can overcome the hardware's limitations in this regard... it's a black-and-white printer and that's all there is to it! If I did have a color printer, then I would have Python produce the appropriate postscript code, or "escape-sequences" in whatever printer-specific language a given printer requires to have it output color text (or, depending on my operating system, printer driver, filters, etc, I might have to send appropriate "escape-sequences" or whatever to the DRIVER in order to convince it to drive the printer appropriately). Much the same holds if you're using "printing" in the vague sense in which Python itself uses it in the keyword "print" (which I detest and consider a wart, albeit shared by such diverse languages as Python, Perl, C, Fortran, etc): it all depends on what device (physical hardware one, or one in some part simulated by software) you're outputting to. For example, print '\033[1;31mciao!' will set all text emitted henceforward to red _IF_ the terminal (or emulator thereof) on which the text is being written is ANSI compliant. Alex From zefram at wolverine.lohacker.invalid Fri Sep 12 10:30:41 2003 From: zefram at wolverine.lohacker.invalid (Emmanuele Bassi) Date: Fri, 12 Sep 2003 14:30:41 GMT Subject: pygtk clist usage References: Message-ID: * Ted Holden [2003-09-12 14:28]: >> BTW, CList is deprecated (meaning it will go away in the next major gtk >> release). ListStore/TreeView can be a bit hard to make the transition to, >> though, as the documentation is rather scattered and fragmentary. Best >> sources of info are... > > I've been trying to take a look at the TreeView/ListStore model. I mean, > you've gotta be kidding. Who do you expect to want to try to figure that > out in order to use a simple listbox? I did, and I do. In C, Python and (yuk) Perl. The basics of the MVC (model/viewer/controller) paradigm are fully graspable in less than 15 minutes (at least, that's how much I had to spend learning them - and I did not know anything about MVC). The power of a MVC system, with customisable models and renderers outweights the underlying complexity. Alas, the TreeView/TreeModel pair isn't quite as fast as CTree/CList, so you need some tricks when dealing with large models, but for simple listboxes, I've never seen any performance problem whatsoever. Creating a simple listbox takes no more than 20 lines of code, callbacks not included. You could create a class that covers everything you might want, and reuse it (or submit it to the pygtk mailing list) thoughout a project or in multiple projects. > Other than that, I'm seeing a conceptual problem with the pygtk > documentation is that it appears to all be oriented towards coding gtk > objects by hand. I do my coding exactely like this. I prefer this way, since Glade it's not flexible enough for me. > The idea of coding guis by hand is probably unacceptable to most people at > this point. Having a(nother) library to depend on when distributing an application, and an XML file sitting around in order to create the UI, may be unacceptable to many people. Your point is? Bye, Emmanuele. -- Emmanuele Bassi | [ http://digilander.libero.it/ebassi/ ] emmanuele.bassi(at)iol.it | Linux User #170621, http://counter.li.org GnuPG Key fingerprint = 4DD0 C90D 4070 F071 5738 08BD 8ECC DB8F A432 0FF4 From __peter__ at web.de Thu Sep 25 10:50:17 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2003 16:50:17 +0200 Subject: newbie script References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> <3f719ed5$0$14824$79c14f64@nan-newsreader-03.noos.net> <3f72eb7c$0$29964$79c14f64@nan-newsreader-02.noos.net> Message-ID: ataraxia2500 wrote: > I get that weird error when I tried to run the little loop, this is what > it says: > > sys:1: DeprecationWarning: Non-ASCII character '\xa0' in file myloop.py on > line 3, but no encoding declared; see http://www.python.org/peps > pep-0263.html for details > File "myloop", line 3 > os.system('/home/joe/src/myprog/myprog') > ^ > SyntaxError: invalid syntax > > does it mean anything to you? The whitespace before os.system() consists of '\xa0' characters, no idea why. However, I have noticed that when I copy and paste from KNode 7.2 using Strg+C/Strg+V instead of the middle mouse button, all '\xa0' are magically converted back to old '\x20' space characters. Peter From bwglitch at hotpop.com Sat Sep 27 15:19:09 2003 From: bwglitch at hotpop.com (BW Glitch) Date: 27 Sep 2003 12:19:09 -0700 Subject: Microbiology and/or image analysis tools Message-ID: <45bbfad.0309271119.386ded65@posting.google.com> Hello all, I've been searching on the web for microbiology and or image analysis tools in any language (but I would prefer to be in Python ;), but I haven't found anything useful. Almost every library I've found is commercial. The only one I've seen open source is OpenEV ( http://openev.sourceforge.net/ ). Is there any library open source available in these areas? Thank you very much, Andres Rosado From sheila at spamcop.net Sun Sep 7 13:17:32 2003 From: sheila at spamcop.net (Sheila King) Date: Sun, 07 Sep 2003 17:17:32 GMT Subject: Comments on Python Redesign References: Message-ID: On Sun, 7 Sep 2003 12:42:19 +0100, "Tim Parkin" wrote in comp.lang.python in article : > Perhaps the people who have commented on the site should realise it's a > proposal and a work in progress. As constructive comments go the only > feedback I have gathered is that the fonts are too small and the > contrast is > a little low. I've adjusted contrast on key elements and also increased > the > font size. These pages are here : > > http://pollenation.net/assets/public/python-main-2.html > http://pollenation.net/assets/public/python-interior-2.html > > also bearing in mind that the html page will be accessible and hence > allow > text resizing here is a sample of +1 text size. > > http://pollenation.net/assets/public/python-main-2larger.html > http://pollenation.net/assets/public/python-interior-2larger.html My suggestions: Go with the +1 font size as the default. The tinier font is nice for fitting lots of data into a page, but not so good for readability. Also, on the content pages put more white space between lines (i.e. the vertical number of pixels between the bottom of one line and the top of the next). -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From jacek.generowicz at cern.ch Mon Sep 1 05:14:53 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 01 Sep 2003 11:14:53 +0200 Subject: Advice to a Junior in High School? References: <7h3k78x66jt.fsf@pc150.maths.bris.ac.uk> Message-ID: Michael Hudson writes: > I'm sure there are people who learnt ML during the CS program at > Cambridge more than five years ago... Indeed, they were definitely teaching ML as the first language 15 years ago, and it wasn't a new policy at the time. From ulysses_dm at yahoo.com.cn Thu Sep 4 06:11:30 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 4 Sep 2003 03:11:30 -0700 Subject: How to accelerate python application GUI speed References: <43e3984e.0309030532.3fe88bbc@posting.google.com> Message-ID: <43e3984e.0309040211.2bfaeea2@posting.google.com> Thanks to all. To:John J.Lee I download 'venster' and test a small samples. I think it's good idea for python GUI. I has use MFC, but I don't like MFC framework. but I like VENSTER's way. I only need make GUI by VC. and write code in python . that code very clear and obvious. I'll test for complete project. anyone has make project to do it? thank you. To: Mark Roach I has read this article. It's same as my idea. But the code sample is make a foo button in wxWindows ,use swig link to wxpython. I don't know if I make a frame in wxWindows. Can I use it in wxPython. Who test it? thank you. To:Jim Dabell I download pyQt ,But I hasn't test it. QT is C++ GUI framework. It's very cool too. To:Brian Kelley sorry about my poor english. I say 'slow'. It's mean wxPython application start up very slow and use big memory. core python code very quick. I use thread. Because Bit-torrent is a P2P program. it's have many intercurrent internet connection for download and upload. >>I'll assume that your bit-torrent code has a pretty simple interface, >>such as "download this file to here", "I'm X percent done" and "cancel >>the download" ~~~~~ you are right. I only need get these information from bit-torrent . It's use a function to communicate with GUI and core program. If you should post you code . I very thank you. I like study with you. thank you. To:Harobed I didn't test pyGTK. thank you. Ulysses From johnp at reportlab.com Wed Sep 24 06:54:26 2003 From: johnp at reportlab.com (John Precedo) Date: Wed, 24 Sep 2003 11:54:26 +0100 Subject: Barcode generator for Python? Message-ID: jennyw said in a recent posting to the python list: > Does anyone know of a barcode generator for Python? I'm looking to do > this on Windows. It would be nice to find something free, but that's not > necessary (so long as it's reasonable). It doesn't have to be > Python-specific, either, so long as I can call it from Python. I'd love > to hear any suggestions. The reportlab open source toolkit has a very nice barcode widget. It's capable of creating the following I2of5 MSI Codabar Code 11 Code 39 Extended Code 39 Code93 Extended Code93 Code 128 USPS FIM USPS POSTNET This isn't actually included in the standard distribution. It is a third party extension package written by Tyler C. Sarna - you can download it from http://www.reportlab.com/extensions.html. By default, the open source toolkit creates PDF files, but if you use the graphics subpackage you can create bitmaps (GIF, Jpegs, PNG etc) using the renderPM renderer. If all you want is some barcodes done as images, this may be overkill (by quite a large amount). However, if you need to create PDF files, or need to create other graphics and charts as bitmap images as well as barcodes then it may be the exact solution you are looking for. Hope this helps. Regards, John -- John Precedo (johnp at reportlab.com) Developer Reportlab Europe Ltd (http://www.reportlab.com) From woodsplitter at rocketmail.com Tue Sep 2 16:07:19 2003 From: woodsplitter at rocketmail.com (David Rushby) Date: Tue, 2 Sep 2003 16:07:19 -0400 Subject: win32com problems with Visible property References: Message-ID: "Rebecca Taylor" wrote in message news:f431a335.0309020839.486b6f92 at posting.google.com... > I have been working with win32com on python for 2 years now. I > recently tried to modify an older script I had made which creates and > excel workbook, fills it with data and then graphs the data. > > Nothing is working! > When I try to run it I get this error: > > "Property '%s.%s' can not be set." % (self._username_, attr) > AttributeError: Property 'Excel.Application.visible' can not be set." > > Does anyone know why this is happening? I can't figure out if windows > has changed or if win32all or the new python distribution is the > problem. Worse yet, I reinstalled my old versions of python and > win32all and that isn't working either! The property is named 'Visible', not 'visible'. When makepy is run, COM identifiers become case-sensitive. Perhaps your old installation of win32com hadn't been makepy-ified, but the new one has? See: http://groups.google.com/groups?q=excel+case+sensitive+group:comp.lang.python.*+group:comp.lang.python.*+group:comp.lang.python.*+group:comp.lang.python.*+group:comp.lang.python.*+group:comp.lang.python.*+group:comp.lang.python.*+group:comp.lang.python.*+group:comp.lang.python.*+group:comp.lang.python.*&hl=en&lr=&ie=UTF-8&group=comp.lang.python.*&safe=off&sa=G http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&safe=off&frame=right&th=6eaef82c8c0d9548&seekm=1c057c8e.0307171643.486e9678%40posting.google.com#link 13 From mn-nospam at cs.york.ac.uk Thu Sep 11 06:38:06 2003 From: mn-nospam at cs.york.ac.uk (Mark Nelson) Date: Thu, 11 Sep 2003 11:38:06 +0100 Subject: Building Imaging-1.1.4 on Solaris 9 Message-ID: Hi I'm trying to build Imaging 1.1.4 in Solaris 9, I get passwd the first step i.e the building of libImging. However when I execute a python setup.py build I get the following error - gcc -shared build/temp.solaris-2.9-sun4u-2.2/_imaging.o build/temp.solaris-2.9-s un4u-2.2/decode.o build/temp.solaris-2.9-sun4u-2.2/encode.o build/temp.solaris-2 .9-sun4u-2.2/map.o build/temp.solaris-2.9-sun4u-2.2/display.o build/temp.solaris -2.9-sun4u-2.2/outline.o build/temp.solaris-2.9-sun4u-2.2/path.o -LlibImaging -l Imaging -ljpeg -lz -o build/lib.solaris-2.9-sun4u-2.2/_imaging.so Text relocation remains referenced against symbol offset in file 0x14c libImaging/libImaging.a(Unpack.o ) 0x150 libImaging/libImaging.a(Unpack.o ) 0x154 libImaging/libImaging.a(Unpack.o ) 0x158 libImaging/libImaging.a(Unpack.o ) 0x15c libImaging/libImaging.a(Unpack.o ) 0x160 libImaging/libImaging.a(Unpack.o ) I have used the additional installation instructions as layed out in the README, I'm using gcc-3.2.2 and python 2.2.2 Any Ideas? Mark. -- -------------------------------------------------------- Mark Nelson - White Rose Grid, Department of Computer Science, University of York Heslington, York, YO10 5DD From dave at boost-consulting.com Fri Sep 26 10:48:44 2003 From: dave at boost-consulting.com (David Abrahams) Date: Fri, 26 Sep 2003 10:48:44 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> Message-ID: Alex Martelli writes: > Raymond Hettinger wrote: > >>> And I still think you don't need it often enough to put it in the >>> builtin namespace, so the function should go in the itertools module. >> >> If you have a magic method, __riter__, then the corresponding >> function needs to be a builtin. They go hand in hand. The >> core parts of the language need to be usable without having >> to know about itertools. > > I have already seen module copy presented as a counter-example to > your assertion, and I'd like to add module pickle as a second, and > I hope decisive, counter-example. It is, to put it simply, utterly > false that functions corresponding to magic methods "need to be > builtins": it's *perfectly* all right for such functions to live > in standard library modules. Oh, and let's not forget module sets: > the __as_immutable__ and __as_temporarily_immutable__ magic methods, > that are used when making a set of sets, or checking for a set's > membership in another set, can be seen as yet another example (and > in this case there is no wiggling out of it by claiming that the > magicmethod/NON-builtin correspondence is a historical/legacy thing, > as the BDFL approved module sets.py, with just this usage, so very > recently). > > I second the motion that function riter, with check for __riter__ > and all, should live in module itertools. Reverse iteration is a > RARE need -- far rarer than copying or even pickling -- and there > is no real reason to burden __builtins__ with a function for it. Is there any concern about the fact that a sequence of direction changes requires building a new iterator object each time under this proposal? I was going to implement my own bidirectional iteration protocol by using a prev() method and use an adaptor object to swap the meaning of next() and prev(). Python iterators (and GoF iterators) seem poorly suited as pure sequence position indicators because you can't reposition them without also accessing elements, so maybe this is not such a serious issue... but my instincts tell me that the identity of a bidirectional iterator object could be useful if we allow the same one to be used in both directions. FWIW, burdening builtins aside I consider the proposed syntax for i in xrange(n).iter_backwards(): much uglier than for i in reverse_view(xrange(n)): but far superior to for i in reverse(xrange(n)): which implies in-place modification of the sequence. Also, the idea of denying tuples the ability to reverse iterate seems arbitrary and capricious. Cheers, -- Dave Abrahams Boost Consulting www.boost-consulting.com From lutz at rmi.net Mon Sep 22 17:56:59 2003 From: lutz at rmi.net (Mark Lutz) Date: 22 Sep 2003 14:56:59 -0700 Subject: Python training in Colorado, Oct 7-9 Message-ID: I am holding another 3-day Python class in Longmont, Colorado, on October 7-9. This is a public class, open to individual enrollments, and covers the same topics as the on-site classes I teach. For more details, please see this page: http://www.rmi.net/~lutz/oct03-longmont-class.html Thanks for your interest. --Mark Lutz (http://www.rmi.net/~lutz) From buzzard at urubu.freeserve.co.uk Mon Sep 1 15:16:24 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 1 Sep 2003 20:16:24 +0100 Subject: artificial intelligence References: Message-ID: "Dennis Lee Bieber" wrote in message news:hrdc21-ce3.ln1 at beastie.ix.netcom.com... > Duncan Smith fed this fish to the penguins on Monday 01 September 2003 > 07:06 am: > > > > > > It can do, and I've no doubt some of it does. Spam filtering is a > > classification problem and can be handled in a variety of ways. It's > > generally easy to come up with an overly complex set of rules / model > > that > > will correctly classify sample data. But (as you know) the idea's to > > come up with a set of rules / model that will correctly (as far as > > possible) > > classify future data. As many spam filters use Bayesian methods, I > > would guess that they might be fitted using Bayesian methods; in which > > case overly complex models can be (at least partially) avoided through > > the choice of prior, rather than significance testing. > > > > What do Amazon use? My guess (unless it's something really naive) > > would be association rules. > > > If I may insert an off-the-cuff comment... > > The goal of spam filtering is normally to reduce the amount of traffic > permitted through to the client. > > However, Amazon's goal would seem to be to increase the potential > sales. Hence, I'd suspect their algorithm is rigged on a quite > optimisitic mode (Hey, out of set A and set B, we have an overlap of > x... maybe we can increase x by suggesting that set A would like the > stuff from set B...) > Absolutely. I'd be interested to know exactly how they try going about this (although I don't suppose they'd make it public). I'd guess that for 'very low' and 'very high' values of x the increase in sales would be less than for 'middling' values of x. Duncan From koen_van_herck at yahoo.com Mon Sep 22 04:54:18 2003 From: koen_van_herck at yahoo.com (Koen Van Herck) Date: 22 Sep 2003 01:54:18 -0700 Subject: Retrieve class name of caller References: <6512ed42.0309190035.303ba9f1@posting.google.com> Message-ID: <6512ed42.0309220054.6bea1fc2@posting.google.com> Bertrand Geston wrote in message news:... > Koen Van Herck wrote: > > For debugging/logging purposes, I have a function > > > > def Log(msg): > > print '%s.%s: %s' % (cls, method, msg) > > > > I call this function from a class method, and I would like to retrieve > > the name of the caller method and its class. I already came up with > > > > method = sys._getframe(1).f_code.co_name > > cls = sys._getframe(1).f_locals['self'].__class__ > > > > I wonder if there are better ways to retrieve this info. In > > particular, my implementation assumes that the instance parameter of > > the method is called 'self', which it usually is, of course. > > > > Regards, > > Koen. > > Take look to the inspect module. Could be what you need (and even more). OK. But if I have the frame or code object, how can I get the method or function object? For example, for a method m I have code object c: c = m.im_func.func_code How can I find m from c ? From rune.hansen at viventus.no Sat Sep 27 20:33:23 2003 From: rune.hansen at viventus.no (Rune Hansen) Date: Sun, 28 Sep 2003 02:33:23 +0200 Subject: unicode 3 digit decimal conversion In-Reply-To: References: Message-ID: Hi Martin, you raise a very interesting question(at least for me it is :-). The, otherwise, excelent support people at Stalker (it's a CommuniGate pro server I'm speaking to) has me totally confused. What I tried to do was to send a quoteattr(u'string') (using quoteattr from sax). The server was very happy with this, showing the accented characters, when viewed in a telnet session, as human readable text. This, it became apparent, was obviously wrong. The data was garbled when viewing it in the web interface. Stalker told me to send the letter "?" as \248 or as xf8 (notice the missing "\"). At this point I'm sending quoteattr(unicode('string',"iso-8859-1).encode("utf-8")) which is neither of the above.(..?). Anyway, the server is still happy, and the data views correctly in the web interface. Stalker provides a perl and java API for the telnet server. I don't read perl code very well, and the java API is distributed as .class files(nothing new there, it's java after all) so I really don't know how Stalker is handling it. regards /rune Martin v. L?wis wrote: > Peter Otten <__peter__ at web.de> writes: > > >>I see your problem is already solved > > > I'm quite uncertain as to what the solution is, though - or perhaps > what the problem is. The OP said that the telnet server expects > backslash characters in the data stream (atleast I interpreted his > message that way), but then he was happy with an approach that did not > send backslash characters. > > Perhaps the telnet server really expects latin-1, in which case > encoding the Unicode string in that encoding, or in iso-8859-15, > would work fine most of the time. > > Regards, > Martin From anton at vredegoor.doge.nl Fri Sep 5 11:11:59 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 05 Sep 2003 17:11:59 +0200 Subject: Open Source leader? (was Re: Celebrity advice) References: <23891c90.0308280317.ac68b38@posting.google.com> Message-ID: Jacek Generowicz wrote: >anton at vredegoor.doge.nl (Anton Vredegoor) writes: > >> -If microsoft hadn't stalled progress in software development by >> hiding the algorithms used for their software we would *now* be >> there where we will be in twenty years. > >I think that Microsoft has stalled progress, not by hiding any >worderful technology that they might have, but by making the vast >majority of users accept sub-mediocrity as the norm. Maybe the average computer user doesn't care how software programs are written and will accept mediocre software. However if sourcecode is available some portion of the users will repair bugs or fork into a better branch. >They have run a hugely successful advertising campaign for the whole >concept of sub-mediocrity; the desire for quality is what has >suffered. By doing so, they have greatly influenced the direction of >progress and of the meaning of "better". In the Microsoft mindset >"better" means that the bouncy paperclip moves more smoothly, and can >now do the cha-cha as well as the samba ... while it remains perfectly >acceptable to have to reboot the computer each time you want to >install a new piece of software. Since you're humoring me and accept "what if" scenarios I don't feel like criticizing. However we should not be ungrateful to Microsoft since one way or the other they have provided us with at least one possible branch of software development. As wrong as it is to contemplate Microsofts accomplishments and compare it with the "no software at all" scenario, it is also wrong to assume it was the best possible path taken. As insight into these matters matures we now know with the benefit of hindsight that proprietary standards and closed source suck. We should keep the option open for Microsoft to better their ways however far they have strayed from the path and even if they are prone to reverting to the embrace and extend pitfall. This *does* imply to be wary though if they're turning around and come back. Anton From mwh at python.net Tue Sep 16 12:32:32 2003 From: mwh at python.net (Michael Hudson) Date: Tue, 16 Sep 2003 16:32:32 GMT Subject: Internal Debugger Question References: <6ee58e07.0309120604.3a1f4985@posting.google.com> Message-ID: <7h3r82gem0k.fsf@pc150.maths.bris.ac.uk> llothar at web.de (Lothar Scholz) writes: > i'm currently writing a debugger for python and found that some > modules store an absolute file path in "co_filename" of there > methods/functions and some store a relative file path. Because the > relative file path can never be expanded to an absolute file path > later (the sys.path may have changed) it is impossible to find the > source code location. > > Is there anything i have missed or is this simply a bug. I would > highly recommend to fix this bug ! I belive this is one of the oldest open bug reports on SF... I spent a few minutes looking at it, before deciding I didn't care enough to fix it. Your point of view may be different: http://python.org/sf/415492 Be warned, the import code is some of the most frightening (to me, anyway) code in Python. Cheers, mwh -- 48. The best book on programming for the layman is "Alice in Wonderland"; but that's because it's the best book on anything for the layman. -- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html From tjreedy at udel.edu Mon Sep 29 10:56:06 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2003 10:56:06 -0400 Subject: Wavelet package available? References: <2ceb70f8.0309290136.118a856d@posting.google.com> Message-ID: "Gez" wrote in message news:2ceb70f8.0309290136.118a856d at posting.google.com... > Does anyone know if there is a wavelet package available for Python? > This package should at least have the Daubechy wavelet. Before posting a question like this and waiting hours for a reply, one should try a search engine like Google. In this case, "Python wavelets" If this fails, then post question and note what you tried without success. This tells responders both that you made an effort and also what they should not waste time on in trying to help you. Teaching-you-to-fish-ly yours, Terry J. Reedy From franke at ableton.com Tue Sep 16 13:36:49 2003 From: franke at ableton.com (Stefan Franke) Date: Tue, 16 Sep 2003 19:36:49 +0200 Subject: Variable lookup in calling context Message-ID: To access a calling function's locals I can use sys._getframe(1).f_locals. But how do I perform a full variable lookup in the context of the caller as if it happened there - including all surrounding scopes? (BTW: Is inspect.currentframe preferable over sys._getframe?) Stefan From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Sat Sep 27 12:32:35 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Sat, 27 Sep 2003 20:32:35 +0400 Subject: Saving Numeric arrays to file? In-Reply-To: References: Message-ID: Duncan Smith wrote: > I am having problems saving arrays to file. e.g. [snipped] > Maybe you'd better use pickle or cPickle modules? anton. From lupan at zamek.gda.pl Thu Sep 18 04:26:00 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Thu, 18 Sep 2003 10:26:00 +0200 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> <95b4b9ac.0309170544.77e0d12a@posting.google.com> <95b4b9ac.0309171233.21f4c07@posting.google.com> Message-ID: <87llsma4fb.fsf@psi.lupan.zamek.gda.pl> hildegarde_roth at yahoo.de (Hilde Roth) writes: > While we are at it, I also don't understand why sequences can't be > used as indices. Why not, say, l[[2,3]] or l[(2, 3)]? Why a special > slice concept? To me, it's not just the step argument in the slice > that is overkill... 1. It will be more typing and harder to visually parse l[:3] would be l[(0, 3)] l[3:] would be l[(3,-1)] 2. Slicing two dimensional object will not be possible as the notion you proposed is used just for that (ex. l[1,2] which is equivallent to l[(1,2)] see below), and Numeric and numarray use it. See what happens with an object which on indexing just returns the index >>> class C: ... def __getitem__(self, i): return i ... >>> c = C() >>> c[3] 3 >>> c[:3] slice(0, 3, None) >>> # multi dimensional indexing >>> c[1,3] (1, 3) >>> c[1:3,3:5] (slice(1, 3, None), slice(3, 5, None)) -- =*= Lukasz Pankowski =*= From eltronic at juno.com Sun Sep 21 11:44:08 2003 From: eltronic at juno.com (eltronic at juno.com) Date: Sun, 21 Sep 2003 11:44:08 -0400 Subject: Anyone has "pyuploader.zip" from Parnassus ? Message-ID: <20030921.114410.-518819.1.eltronic@juno.com> On 19 Sep 2003 11:42:59 GMT Fred Pacquier writes: > Hi, > > For my education I'd like to take a peek at "CGI Uploader", an old > script > that can be found on Vaults Of Parnassus ( > http://py.vaults.ca/apyllo.py?find=uploader ). > > Unfortunately that is hosted on Parnassus itself : > http://www.vex.net/~x/python_stuff.html > > I can access the page itself, but no file linked > there will actually download. last archive around feb/2003 yeh wayback! they don't always archive archives, maybe only if they are small enough. its the first place to look if you need to look at some page that no longer exists, or to see what an earlier version of the page looks like. when persistence is futile use the wayback machine. e please forward all spam to "me" is it time yet to mangle all emails as the signup page claims this mailing list will do? ________________________________________________________________ The best thing to hit the internet in years - Juno SpeedBand! Surf the web up to FIVE TIMES FASTER! Only $14.95/ month - visit www.juno.com to sign up today! From ajsiegel at optonline.net Thu Sep 18 21:09:04 2003 From: ajsiegel at optonline.net (Arthur) Date: Thu, 18 Sep 2003 21:09:04 -0400 Subject: Computer Programming for Everybody, a Newbie Project Message-ID: <000701c37e4a$9ea15a00$0c02a8c0@Arts> Ron writes - >But the CP4E slogan is using hyperbole to make a memorable >point...that programming can be usefully extended to a far greater >audience. You're a tough man to disagree with. I had a long response prepared (we actually seem to have a lot in common), but in the end it really is just a matter of one's taste for slogans, and more specifically for hyperbole in slogans. Probably nothing much more to it than that. Nietzische meant exactly what he said and said exactly what he meant. Having read a line, once. Or that was the effort, at least. When we approach the field of edcuation, and when we approach it specifically advocating more and better programming education, I think we should approach it saying what we mean and meaning what we say. Would be a style with which I, personally, am more comfortable, anyway. Art From martin at v.loewis.de Tue Sep 30 17:32:48 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Sep 2003 23:32:48 +0200 Subject: 64-bit EPIC and some modules References: Message-ID: Christos "TZOTZIOY" Georgiou writes: > >_tkinter built fine for me, with Python 2.3.1, on a Debian/ia64 > >system. If it was not built for you, most likely, you forgot to > >install the header files. > > The header files were there (/usr/lib/tcl) Why are the header files in /usr/lib/tcl???? Which header files specifically? If the header files where installed properly, they would live in /usr/include, somewhere, either /usr/include/tcl.h, or /usr/include/tcl84/tcl.h. setup.py would never look for header files in /usr/lib. Regards, Martin From herrn at gmx.net Wed Sep 10 15:32:02 2003 From: herrn at gmx.net (Marco Herrn) Date: Wed, 10 Sep 2003 21:32:02 +0200 Subject: How to instatiate a class of which the name is only known at runtime? In-Reply-To: <1063139737.1862.5.camel@adsl-209.204.179.133.sonic.net> References: <20030909194508.GV16821@incise.org> <1063139737.1862.5.camel@adsl-209.204.179.133.sonic.net> Message-ID: <20030910193202.GA2136@darkstar.localdomain.fake> Hi, On Tue, Sep 09, 2003 at 01:35:37PM -0700, Chad Netzer wrote: > On Tue, 2003-09-09 at 12:45, Nick Welch wrote: > > Although this all seems really dirty to me. Maybe there are better ways > > to do it. > > The first form, using getattr, is perfectly idiomatic, and that is what > I use. > > Also, regarding the earlier import question, there is the builtin > __import__ function: Yes! That is exactly what I was searching for. That helps a lot to me. Thanks. I already searched for everything that has anything to do with modules, but I never ran across __import__(). It seems that I am searching not effectively enough. I am not very familiar with python, so can you give some tips on how to search for functions or modules to use, when I have a specific problem to solve? What I mean is, you have helped me, but without this list, I would have never found this solution. At what places should one look, when he is searching for existing functions or language features or the "python way" doing some things, aside from this list of course. ;-) Marco -- The years of peak mental activity are undoubtedly between the ages of four and eighteen. At four we know all the questions, at eighteen all the answers. -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From __peter__ at web.de Mon Sep 29 15:05:12 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Sep 2003 21:05:12 +0200 Subject: A startup puzzle References: Message-ID: Peter Otten wrote: Oops! My consideration does not work with from leoGlobals import * as the rebinding is not propagated. The following seems to work although I do not know if this is approved Python: leoGlobals.py, second try: from leoApp import Application class Dummy(object): pass app = Dummy() def createApp(): app.__class__ = Application app.__dict__ = Application().__dict__ Peter From vze4rx4y at verizon.net Wed Sep 24 05:57:18 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 24 Sep 2003 09:57:18 GMT Subject: Pre-PEP: reverse iteration methods References: Message-ID: <2Udcb.1997$541.708@nwrdny02.gnilink.net> [Raymond Hettinger] > > for elem in seqn.iter_backwards(): > > print elem [Stephen Horne] > That is a pretty long name. Can we use the convention from itertools > where an 'i' prefix is sufficient to suggest an iterator, giving > 'ibackwards' or 'ireverse' or similar. That sounds reasonable to me. I'll add that alternative to the PEP. If the discussion on enumerate() is any indication, then the naming discussion will be much more lively than on the idea itself. Perhaps, Alex will once again be able to suggest a musically perfect, beautiful Italian name. BTW, if you think iter_backwards is long, then take a look at some of the method names in the sets module. > Second, I'm not quite ready to drop my property idea ;-) > > An advantage is that the object returned by the property can sensibly > support more than just iteration - e.g. slicing (as touched on in the > PEP284 thread). So for instance... > > >>> x = range(10) > >>> list(x.backward) > [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] I'm not clear on the details of what you're proposing. What is type(x.backward)? Please show what a pure python version would look like (taking UserList as an example). > >* Should file objects be included? Implementing reverse iteration may not > > be easy though it would be useful on occasion. > > IMO no - doing this essentially needs the whole file to be read into > memory, in which case you may as well read the whole file into a list > and then iterate the list backwards. Oh, it could be done using seeks and whatnot; however, the code might be grotesque. > >* Should enumerate() be included? It would only provide reverse iteration > > whenever the underlying sequence supported it. > > Why not... > > for i, j in enumerate (listname.iter_backwards ()) : > > in other words, as enumerate can handle the already-reversed > sequence/iteration, I don't see the point. The point is that enumerate will starting numbering from zero for the last item: >>> mystr = 'abc' >>> list(enumerate(mystr.iter_backwards())) [(0, 'c'), (1, 'b'), (2, 'a')] If you want the indices to match their original position, then you would need something like: >>> list(enumerate(mystr).iter_backwards()) [(2, 'c'), (1, 'b'), (0, 'a')] The implementation would need to access both mystr.iterbackwards() and mystr.__len__(). At first glance, this is a can of worms, a pandora's box, a gordian knot, or some unnamed code smell unsuitable for this mixed metaphor. Raymond Hettinger From rebel at removethis.rebel.com.au Sat Sep 6 01:27:19 2003 From: rebel at removethis.rebel.com.au (Chris) Date: Sat, 06 Sep 2003 05:27:19 GMT Subject: Embedded Perl or Python (XPost) References: Message-ID: <78e5340818d8ad47fde9693b0d79bed8@news.teranews.com> Hi Cameron Thanks for the interest. when I say smallest footprint its because to me size does matter :) I like my apps to be as small as possible for easy delivery. So for example if PERL "requires" the whole package to be present then it would be too bloated I would like just a small as possible DLL or possibly statically link the interpreter into my app with minimum external files so my concerns are can it be done which will do it better which will be faster. (some of the scripts will be called many times so compounding speed is an issue) can I precompile to decrease load times ? which will be the smallest in size? Chris claird at lairds.com (Cameron Laird) wrote in news:vlgkb4dtchna9e at corp.supernews.com: > In article , > Chris wrote: > . > . > . >>I am developing a software project where a major portion of it is to >>enable script access to c++ classes >> >>The idea is to extend the basic functionality of the program by >>allowing third parties to write add ons that are called by my c++ >>classes as virtual functions. > . > . > . >>Given the above which interpreter is most likely to fit my bill with >>the smallest footprint ? > . > . > . > Let's be clear on what we're discussing. When you write, > "smallest footprint", do you seriously mean, "creates the > smallest differential in the size of the resulting exe- > cutable image"? Frankly, that would surprise me; your > project sounded interesting and useful up until those > last two words. I don't mean to be harsh; unless there's > something you're not telling us, though, the size of > executables-as-file-images is quite unlikely to be even > the tenth most important aspect of your target. > > I'll anticipate a bit more, and observe that Python is > likely to be the better choice, because it remains easier > for a newcomer to extend-or-embed (it's not clear that > you've decided between these alternatives), at least until > Perl 6 meets all its goals. From simonb at webone.com.au Wed Sep 10 21:50:59 2003 From: simonb at webone.com.au (Simon Burton) Date: Thu, 11 Sep 2003 11:50:59 +1000 Subject: metaclasses for type comparison Message-ID: In today's experiment, I was wondering if I could make the comparison operators (<,<=,>=,>) work on classes (types) according to inheritance. The idea is, for example, classes lower in the class hierarchy would be less than (more specialized) than classes they inherit from. class A(object): pass class B(A): pass B < A # should be True In my first attempt I tried putting __lt__ into the class definition for A and then assigning it as a staticmethod. This doesn't work, but something was happening; <,<=,>=,> are still valid as applied to classes. Because class is to instance as metaclass is to class, I found that the place to put these methods is in the class' metaclass. class MetaCMP(type): def __lt__(cls,other): for base in cls.__bases__: if type(base) != cls.__class__: continue if base <= other: return 1 return 0 def __le__(cls,other): if cls == other: return 1 for base in cls.__bases__: if type(base) != cls.__class__: continue if base <= other: return 1 return 0 def __gt__(cls,other): for base in other.__bases__: if type(base) != cls.__class__: continue if cls >= base: return 1 return 0 def __ge__(cls,other): if cls == other: return 1 for base in other.__bases__: if type(base) != cls.__class__: continue if cls >= base: return 1 return 0 __metaclass__ = MetaCMP Now, with the above code, we can replace a call to isinstance. type( B() ) <= A # True It seems natural enough to my math trained eye. But now we have non-comparible objects, which confuses the sorting issue. class C: pass C < A # False A < C # False For example, if we wanted a "total" order ( always either X<=Y or Y<=X ) we could remove __ge__ and __gt__ from MetaCMP. It's not clear to me exactly which comparison methods "list.sort" uses. (The ideal sort here is the topological sort.) I also thought about extending this order so that "B() <= A" would behave the same way. It would be rather more strange. Is it so natural that an instance is "smaller" than it's type? Perhaps; the instance can have attributes that override it's type, which is reminiscent of some kinds of inheritance. Finally, the feature request. If "type" implemented these semantics for comparison would it break existing code? Does anyone rely on "1" always True) ? Another quandry is that one could just as naturally argue for the reverse ordering. Comments sought (can you guess what + might do to classes?). Simon Burton. From pweldon at mindspring.com Sat Sep 20 10:37:45 2003 From: pweldon at mindspring.com (Phil Weldon) Date: Sat, 20 Sep 2003 14:37:45 GMT Subject: python script as an emergency mailbox cleaner References: Message-ID: It's a worm. Worm.Automat.AGH. This is going to be a bad one. The worm installs, among other things, an SMPT engine, searches an infected system for email address, and sends two types of e-mail: the first is HTML and is a fake "security patch" supposedly from Microsoft. It looks very official, but the attachment, 104 KBytes long, is infectious. Norton Antivirus definitions only began to identify it with the 18SEP03 manual definition update. The worm also posts to usenet newsgroups. The other type of e-mail is a fake notification of undeliverable e-mail. This one is a real bear. There seem to be hundreds variations in the body content and thousands of variations in the header. The infectious package is also about 104 KBytes. I'm getting nearly 100 of the two types per hour. Norton Antivirus does not detect the worm in usnet posts read by Outlook Express Newsreader or Outlook Newsreader. Only when you attempt to open the attachment or save the attachment to disk will Norton identify it. Norton will NOT detect the virus in the newsgroup posts folder NOR will it detect the newsgroup folder in a full system scan. It will not remove the infected file from the newsgroup folder, but it will prevent execution of the vermal payload. Microsoft Outlook with the SP3 security update when used as your e-mail reader protects against infection. Prior to 18SEP03 Norton did not. The worm is also retrieving additional variations, so you can expect the payload size to begin changing soon. The HTML message is easy to identify; it is always the same (so far), and includes the phrase 'Run attached file'. The bogus 'Undeliverable e-mail' variations have no commonality but the payload attachment (that purports to be your bounced e-mail.) This will likley change soon. My guess is that the internet will not open on Monday. Phil Weldon, pweldon at mindspring.com "Alex Martelli" wrote in message news:G6Zab.127313$R32.3854946 at news2.tin.it... > All my mailboxes have been filling up with files of about 130k to 150k, no > doubt copies of some immensely popular virus. So, I've no doubt lost lots > of real mail because of "mailbox full" conditions (the proliferating fake > bounce messages more or less ensure nobody knows their mail to me has > bounced, either). > > As an emergency response I and Anna developed, over the last half hour, a > small Python script to be run from cron every few minutes and automatically > scrub any POP3 mailbox from files in the target size range. I'm saving them > to a local file for potential later perusal, but that's obviously easy to > comment out if needed. Here's the tiny script in question...: > > import poplib > import time > > print 'Start at', time.asctime() > > host = 'pop.mail.yahoo.com' > port = 110 > user = 'aleaxit' > pasw = 'secret' > > logfilename = 'bigjunk' > minsize = 130000 > maxsize = 180000 > fromtag = 'From aleaxit at yahoo.com %s\n' > > ps = poplib.POP3(host, port) > ps.user(user) > ps.pass_(pasw) > > messages = ps.list() > print '%d messages, %d bytes' % (len(messages[1]), messages[-1]) > > logfile = open(logfilename, 'a') > > for sms in messages[1]: > sid, ssize = sms.split() > if minsize <= int(ssize) < maxsize: > message = ps.retr(sid) > print 'retrieving and deleting msg#%s, %d bytes, %d lines' % ( > sid, message[-1], len(message[1])) > logfile.write(fromtag % time.asctime()) > for line in message[1]: > logfile.write(line) > logfile.write("\n") > logfile.write('\n') > ps.dele(sid) > > ps.quit() > > print 'Done at', time.asctime() > print > > > Hope it can come in useful to somebody...!!! > > Alex & Anna > From amonroejj at yahoo.com Wed Sep 24 07:11:03 2003 From: amonroejj at yahoo.com (R. Alan Monroe) Date: Wed, 24 Sep 2003 11:11:03 GMT Subject: Fastest way to get thousands of db records to client in 3 tier? References: <3f71361f$0$97182$edfadb0f@dread12.news.tele.dk> Message-ID: In article <3f71361f$0$97182$edfadb0f at dread12.news.tele.dk>, Max M wrote: >> I intend to write both client and server in Python, and my main goal >> in the first cut is speed. Suggestions? >Why do you need thousand of rows at the client? Normally you would get >the results in batches, so that you only transfer at most a few hundred >at a time to the client. Those types of tests will be done in my second cut. >Why not let the client ask directly if it is faster? I thought that defeats the purpose of having 3 tiers. You'd have to update the client if/every time business rules changed. Unless I'm missing something. Links to tutorials welcome. Alan From mark at hahnca.com Tue Sep 30 19:20:27 2003 From: mark at hahnca.com (Mark Hahn) Date: Tue, 30 Sep 2003 16:20:27 -0700 Subject: distutils (packaging) newbie questions please.... References: Message-ID: <2doeb.4608$hp5.1571@fed1read04> I just went through this with a python shareware app (http://EzPicMailer.com) and after a bit of wandering around lost, I came up with a packaging combination that worked great for me. I can highly recommend using: 1) McMillan utility instead of distutils http://www.mcmillan-inc.com/install1.html 2) Inno setup for actual installer http://www.jrsoftware.org/isinfo.php After setting up a few .bat files, I can now release in a matter of a minute or so. Oh, and I didn't have to set up any __init__.py files or anything like that. "Christian Seberino" wrote in message news:bf23f78f.0309301511.376225b0 at posting.google.com... > I really want to learn distutils to professionally package some open > source software. > > I had some distutils questions after reading python.org distutil docs > on packaging code > if you don't mind. I would really appreciate some help..... > > > 0. I'm confused about use of the word "package" in setup.py. > packages = ["", "", ...] > Does package here just mean "a new directory of source code to > consider"??? > > 1. What exactly goes into the __init__.py files? I know what to put in > setup.py > and I know __init__.py is used for packages but I don't know what > to put IN this file. > > 2. About the data_files option for setup.py.... > > data_files = [ "", [ "", > "", ...] ] > > Is there a way to AVOID having to type EVERY single data file?? Can > I specify > just the directory or use wild cards?? > > 3. python setup.py sdist will make a package of SOURCE code and > using "bdist" will put BINARIES in package. What does this > mean??? > Will bdist packages unpack to pyc (bytecode) files and sdist will > unpack > py (noncompiled) files???? What if I wanted py and pyc files > installed > from the package?? (i.e. source and compiled versions) > > Thanks! > > Chris From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Thu Sep 18 05:11:40 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Thu, 18 Sep 2003 13:11:40 +0400 Subject: Help with regular expression In-Reply-To: References: Message-ID: Stephen Boulet wrote: > I'm trying to write an RE to match a string that might or might not be > ther and everything past it up to another string that might or might not > be there and everything past it to a third string that might or might > not be there and everything past it. > > Say my strings are "STRING1", "STRING2", and "String3". > > Would the re be: > > r'((STRING1.*)(STRING2.*)(STRING3.*))' > > The goal is to separate the groups by newlines, but I only want the > first group to match up to the second group and the second to match up > to the third. > > Normally I would achieve this by typing: > > pat = re.compile(r'((STRING1.*)(STRING2.*)(STRING3.*))') > m = pat.findall(s) > s = '\n\n'.join(m[0]) > > but the first group would seem to match everything. > > How can I get it to do what I want? > > -- Stephen > Try non-greedy wildcards: r'((STRING1.*?)(STRING2.*?)(STRING3.*?))' - - - should do the trick. hth, anton. From matthew at barnes.net Mon Sep 8 11:45:51 2003 From: matthew at barnes.net (Matthew Barnes) Date: 8 Sep 2003 08:45:51 -0700 Subject: Detecting interactive mode reliably Message-ID: <3a8e83d2.0309080745.1a1a6bea@posting.google.com> Surely this has been asked before, but I've not yet found the answer on Google Groups or the Python FAQ. Is there a method for reliably detecting whether the interpreter is running in interactive mode? The best solution I've come up with so far is to check sys.argv[0] for an empty string or '-c', but I'm not sure whether that works for all the various Python IDEs out there. Reason for the question is that I'd like a module I'm writing to run some extra initialization steps when the module is imported from an interactive interpreter. So something like: if some_reliable_interactive_mode_test(): initialize_for_interactive_use() Matthew Barnes From eppstein at ics.uci.edu Tue Sep 16 20:25:20 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 16 Sep 2003 17:25:20 -0700 Subject: When passing functions as args, how to pass extra args for passed function? References: Message-ID: In article , "Sean Ross" wrote: > Here's one way: > > formatted = map(lambda f: pretty_format(f, fmt='%4.5f'), unformatted_list) > > > And, here's another (requires itertools, available in Python 2.3 [*]): > > from itertools import repeat > formatted = map(pretty_format, unformated_list, repeat('%4.5f')) > > > [*] > # or you can roll your own, > # credit: http://www.python.org/dev/doc/devel/lib/itertools-functions.html > def repeat(object, times=None): > if times is None: > while True: > yield object > else: > for i in xrange(times): > yield object > > # may need 'from __future__ import generators' at top of file def curry(f, **kwargs): return lambda *largs: f(*largs,**kwargs) map(curry(pretty_format, fmt='%4.5f'), unformatted_list) -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From bokr at oz.net Sun Sep 7 13:14:00 2003 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2003 17:14:00 GMT Subject: Any tools to print source code call hierarchy References: <6ee58e07.0309061534.5f8cf00f@posting.google.com> <6ee58e07.0309070221.61734da4@posting.google.com> Message-ID: On 7 Sep 2003 03:21:25 -0700, llothar at web.de (Lothar Scholz) wrote: >Simon Burton wrote in message news:... >> hmmm... I think (some) static analysis may be possible. The main >> thing to exclude is eval/exec but even then, yes you're right, some >> programs would just have to be run to find out what they do. >> > >Whats with code like: > >if foo: > def myfunc(): > ... do something >else: > def myfunc(): > ... calling your_func() > > >A Language where the program calling hierarchie depends on runtime >calculations is not able to provide good refactoring tools or static >flow analysis. This is the huge difference to a language like >Smalltalk where we live in an image. > >And if you say that this is a hack, then you are making a big mistake, >look at currently used code and you will find so much uses of this >style (or even worse styles) that it seems to be a common paradigm. Which only begins to hint at what is possible with metaclasses ;-) Regards, Bengt Richter From davidcfox at post.harvard.edu Wed Sep 10 23:03:02 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Thu, 11 Sep 2003 03:03:02 GMT Subject: metaclasses for type comparison In-Reply-To: References: Message-ID: Simon Burton wrote: > In today's experiment, I was wondering if I could make the comparison > operators (<,<=,>=,>) work on classes (types) according to inheritance. > > The idea is, for example, classes lower in the class hierarchy would be > less than (more specialized) than classes they inherit from. > > class A(object): > pass > > class B(A): > pass > > B < A # should be True Is this an exercise to help you learn about metaclasses, or do you actually want to be able to check whether B is a subclass of A. If the latter, then try issubclass(B, A). Otherwise, ignore this comment David From alienoid at is.lg.ua Thu Sep 4 07:20:06 2003 From: alienoid at is.lg.ua (Ruslan Spivak) Date: Thu, 04 Sep 2003 14:20:06 +0300 Subject: pyOpenSSL + windows Message-ID: <3F571FE6.8070309@is.lg.ua> Hello, pythonistas! Does anybody have pyOpenSSL windows binaries for python2.2? Thanks a lot in advance Best regards, Ruslan From timr at probo.com Fri Sep 19 02:33:04 2003 From: timr at probo.com (Tim Roberts) Date: Thu, 18 Sep 2003 23:33:04 -0700 Subject: smtplib question References: <2003091716471063831625@k2.sage.att.com> Message-ID: Garry Hodgson wrote: > >how do i use smtplib to send mail to someone with "cc" to someone else? >if i just include the "to" addressees in the call to smtplib.sendmail(), and >put the others in the "Cc" header fields, only the "To" recipients get the mail, >thought the mail headers look right. The e-mail headers (To:, Cc:, Subject:, etc.) are not part of SMTP. They are ignored by sendmail and play no part at all in the e-mail delivery. The only thing sendmail cares about is the list of addresses in the SMTP protocol, which comes from the first parameter to smtplib.sendmail. So, the short answer is that the address list (first parameter to smtplib.sendmail) must include EVERYONE that should receive the message -- To, Cc, or Bcc -- in one big list. You can put whatever you want in the headers in the body of the message; it won't matter. For large lists, it is common for the header to say, for example: To: recipient list suppressed Perfectly legal. >please respond off-list. i had to give up following comp.lang.python for lack >of time. But yet, you expect us to take OUR time to answer your questions for free? That doesn't seem right. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ben at transversal.com Tue Sep 9 06:59:14 2003 From: ben at transversal.com (ben at transversal.com) Date: 9 Sep 2003 03:59:14 -0700 Subject: Slight metaclass confusion Message-ID: I am slightly confused about the way metaclasses work, having read "Metaclass Programming In Python, Parts 1 and 2" I get the fact that the instance of a metaclass is a class, but in this case I fail to see why the following does'nt work: >>> class Meta(type): ... def __str__(cls): ... print "I am " + repr(cls) ... >>> >>> Class = Meta("Fish", (), {}) >>> Class.__str__() Traceback (most recent call last): File "", line 1, in ? TypeError: descriptor '__str__' of 'object' object needs an argument Whereas this does: >>> class Simple(object): ... def __str__(self): ... return "I am " + repr(self) ... >>> obj = Simple() >>> obj.__str__() I am <__main__.Simple object at 0x402f676c> The tutorial does mention this (slightly), but doesn't make it clear why this is happening. I am probably missing something obvious though! Thanks for the help, Ben --- From brucedickey at micron.com Mon Sep 29 13:21:11 2003 From: brucedickey at micron.com (Bruce Dickey) Date: Mon, 29 Sep 2003 11:21:11 -0600 Subject: [joke] Any tool to translate PHP to Python? References: <3f75f5b8$0$20650$626a54ce@news.free.fr> <3f775d15$0$20178$626a54ce@news.free.fr> Message-ID: "Bruno Desthuilliers" wrote in message news:3f775d15$0$20178$626a54ce at news.free.fr... > Bruce Dickey wrote: > > Bruno Desthuilliers wrote: > > > >> Bruce Dickey wrote: > >> > >>> Hi, > >>> > >>> I have some PHP scripts I'm moving from my web server to the local > >>> PC. They just do file manipulation. > >>> > >>> Anybody know of a tool for translating PHP to Python? > >> > >> > >> > >> Er... What about a programmer ?-) > >> > >> (sorry, could not resist) > >> Bruno > >> > > > > Heh heh. Point taken. I actually *was* assuming I would be the tool -- > > I've been around Python long enough to have seen most of the resources > > for desktop apps. > > > > But Python web scripting I have not gotten into or read much about. It > > appears to me that Python is increasing in popularity, not only on the > > desktop, but also on the web server. > > > > It seems to me that for folks migrating from PHP to Python, a translator > > would be a handy tool. Especially if they have a large site to convert. > > May be, but to which of the numerous Python-based dynamic web page > generation / web framework / web application server would you convert > your php source ? > > Bruno > I don't know... maybe never will. In my case, I only have a few small scripts and will translate by hand. Bruce From paul at boddie.net Thu Sep 4 10:48:45 2003 From: paul at boddie.net (Paul Boddie) Date: 4 Sep 2003 07:48:45 -0700 Subject: Using python RPM on SuSE 8.1 : No libpython.a or libpython.so present. Why? References: Message-ID: <23891c90.0309040648.10abd74@posting.google.com> turner at mmedia.is (Douglass Turner) wrote in message news:... > Hello, > > I'm trying to install a statistics package called RSPython that > requires a python shared library to be present on my SuSE 8.1 linux > box. My python is provide as an RPM package and as far as I can tell > there is no libpython.a or libpython.so. What gives? What does "locate libpython" give you? I'd expect those libraries to be under /usr/lib on most modern (GNU/)Linux distributions, but possibly not with exactly those names. The presence of a shared library is a comparatively recent luxury, and I wouldn't expect that to be there for releases of Python earlier than 2.3. > How do I get these libraries on my machine? The chances are that they do exist, but with more specific names, as the following path illustrates: /usr/lib/python2.2/config/libpython2.2.a Paul From list-python at ccraig.org Wed Sep 17 10:08:05 2003 From: list-python at ccraig.org (Christopher A. Craig) Date: 17 Sep 2003 10:08:05 -0400 Subject: [Python-Dev] Making python C-API thread safe (try 2) References: <3F632226.2010607@earthlink.net> <5CH9b.81$2k.16@reader1.news.jippii.net> <20030916211148.GD29089@unpythonic.net> <3F67D36B.80709@sci.fi> Message-ID: Harri Pesonen writes: > But wouldn't it be better if Python had real multitasking? Comments > like the above mean that you accept Python as it is, fine. But > usually people want to make things better when they see that > something can be improved. If my roof is leaking, I have two > choices: fix it or accept it. If I am able to fix it, then I'll > probably do it. This is awfully dramatic. Python does have real multitasking, take a look at os.fork(). Your proposal would require a great deal of work [1] to achieve a very limited result: Situations where people wanted to share Python objects between multiple, independent interpreters in a single process. I don't think that happens very often. Note that the average threaded Python user is probably using a single interpreter and so will see no noticeable speedup from this. If you really want to do this, I'd rather see some sort of shared memory manager that lets you share Python objects between independent processes. That gives nearly all the benefits without having to break a bunch of C modules. 1) You say it's easy, but I'll believe it when I see a patch. -- Christopher A. Craig I develop for Linux for a living, I used to develop for DOS. Going from DOS to Linux is like trading a glider for an F117. - Lawrence Foard From tim.parkin at pollenationinternet.com Mon Sep 8 15:27:41 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Mon, 8 Sep 2003 20:27:41 +0100 Subject: What is marketing? In-Reply-To: Message-ID: <003301c3763f$4b5896a0$0a00a8c0@JASPER> David Mertz >Alex Martelli wrote previously: >|Many techies think of "marketing" as a dirty word because it's so often >|misused as an inappropriate synonym for "selling". > > marketing > 1. The act or process of buying and selling in a market. > 2. The commercial functions involved in transferring goods from > producer to consumer. > -------------------- > The American Heritage (r) Concise Dictionary of the English Language, > Third Edition. Copyright (c) 1992 Houghton Mifflin Company. > >In other words, 'marketing' is a synonym for 'selling' (commercially). > >The neutral word that Alex is looking for is 'promotion', which has a >subtle but important difference from the dirty word. This is totally misconstrued pedantry Sell - 7 a Advertise or publish the merits of. b give (a person) information on the value of something. inspire with a desire to buy or acquire or agree to something. Tim From Vincent.Raaijmakers at ge.com Mon Sep 1 15:37:21 2003 From: Vincent.Raaijmakers at ge.com (Raaijmakers, Vincent (IndSys, GE Interlogix)) Date: Mon, 1 Sep 2003 14:37:21 -0500 Subject: Structured writing to console, such as a table Message-ID: <971323274247EB44B9A01D0A3B424C8541FC0B@FTWMLVEM02.e2k.ad.ge.com> Ok, perhaps a question on a newbie level. I try to create a simple 'write to a console application' where all the items in a string do have a variable size: items = ["a", "bbbbbbbbb", "cc"] Well, actually, I need to print a table as simple text, nice lined up in a console. So: Item: Value: Another Value: ----------+----------+------------------ a | 1 | 2 bbbbbbbbb | 2 | 17 cc | 3 | 5 My hope was that somewhere in python land an existing module was waiting for me. A module that also prints lines, headers.... Unfortunately, I can't find it. Books, Google... Before I reinvent this wheel... please give me some tips, references, examples... Thanks, Vincent From nav+posts at bandersnatch.org Mon Sep 8 10:58:36 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 08 Sep 2003 10:58:36 -0400 Subject: Comments on Python Redesign References: Message-ID: mertz at gnosis.cx (David Mertz) writes: > Just email for details on payment/shipping. > The first order may take an extra week for setup time (it might take a > couple days for me to talk to my local copy-shop about printing the box > and so on). [only *wink*ing inasmuch as I question the market, for even > one $299 sale, I really would create something quite nice looking] How much of this $299 would go to the PSF? And how much would go to the David-needs-a-yacht fund? I could probably get my boss to order 4 or 5 such boxed distributions... No-*winking*-at-all, Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From mcfletch at rogers.com Sat Sep 6 16:10:13 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 06 Sep 2003 16:10:13 -0400 Subject: [2.3] object does not appear to be a reserved word In-Reply-To: References: Message-ID: <3F5A3F25.7040208@rogers.com> John Roth wrote: >"Daniel Klein" wrote in message >news:v89klvsupdoe39e6trqbbqvmhfgecnoum8 at 4ax.com... > > >>Is it potentially dangerous to use the variable 'object' in code? >> >> > >"object" is, I believe, a built-in type in the builtins namespace. >As such, you can shadow it so it's inacessable. However, >the only place were that could cause problems is if you >use it as an identifier at the module level. I think. > > Another place: errors in (copied) code which get silently ignored because of the presence of the "object" type. For instance, if you cut-and-past a few lines of (older, particularly pre-2.2) code which uses the variable "object" into a new situation which uses "item" (or whatever), the older code will often seem to be functioning properly because it uses the type "object" as an instance, instead of raising a NameError. Tends to result in subtle bugs, but not likely enough to warrant breaking all the old code that used "object" as an identifier by making it a keyword. To answer the original question, yes, it's somewhat dangerous to use "object" as an identifier in code. It's approximately equally dangerous to use "str", "list", or "tuple" as an identifier. It's just that the temptation to use "object" is greater when you're doing a lot of polymorphic programming, and you'll find older code (pre 2.2) using it without any concern whatsoever (because there was no object type back then to cause a problem). Each new built-in causes the same problem, it's just that "object" is so fundamental an idea (both as a built-in and an identifer) that it's probably the most likely source of such low-level conflicts going forward. (e.g. enumerate, or zip are used in code once in a while, but compared to "object" are fairly uncommon choices for an identifier). Enjoy, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From vze4rx4y at verizon.net Thu Sep 25 14:38:17 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 25 Sep 2003 18:38:17 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> Message-ID: "sebastien" wrote in message > So, I'd expect to have a riter() function which would call the > __riter__ special method. . . . > And I still think you don't need it often enough to put it in the > builtin namespace, so the function should go in the itertools module. If you make a magic method, then the function calling it needs to be a builtin. They go hand in hand. Raymond From martin.schneider at illusion-factory.de Tue Sep 9 06:53:20 2003 From: martin.schneider at illusion-factory.de (Martin Schneider) Date: Tue, 9 Sep 2003 12:53:20 +0200 Subject: Python / C: small runtime difference? References: Message-ID: One step ahead: My test program sorted a two-dimensional array containing pairs of a string and a long integer, and the strcpy routine seems pretty slow. After reducing the problem to numerical sort only, I could improve the relation to 1:50. Is this a normal ratio? Martin > The Python Bubblesort runs 103 seconds, the C extension Bubblesort runs 28 > seconds, this is about 1:4, which is far worse than I expected (assumed > about 100:1 or alike). From owner-mutt-announce at mutt.org Wed Sep 3 03:01:08 2003 From: owner-mutt-announce at mutt.org (owner-mutt-announce at mutt.org) Date: 3 Sep 2003 07:01:08 -0000 Subject: mutt-announce@mutt.org: Non-member submission from Message-ID: <20030903070108.28220.qmail@agent57.gbnet.net> Your submission to the list has been forwarded to the list owner for approval because you do not seem to be on that list. If you want to join the list, send email to , with "subscribe mutt-announce" in the message text (not the subject). From richie at entrian.com Fri Sep 12 08:36:36 2003 From: richie at entrian.com (Richie Hindle) Date: Fri, 12 Sep 2003 13:36:36 +0100 Subject: asyncore question In-Reply-To: References: Message-ID: <60f3mv8t6ebgsgskg50inqt6rihqtu5tlv@4ax.com> [St?phane] > what happens if dispatcher is created with non global map > but with no socket, like: > > d=dispatcher(self,sock=None,map=some_map) > > then create_socket called: > > d.create_socket() > > This dispatcher will be added to the global map. > But probably user will call asyncore.loop(map=some_map), > as d was buillt with this map. > > Is there not something wrong here, or am I just missing something ? I believe it's an oversight in asyncore. Either create_socket should take a map parameter, or __init__ should store the initial map and create_socket should use it. One workaround is to create the socket yourself and call set_socket(sock, some_map). -- Richie Hindle richie at entrian.com From mcfletch at rogers.com Wed Sep 10 17:42:31 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 10 Sep 2003 17:42:31 -0400 Subject: Opposite of yield? In-Reply-To: <3F5F95B9.A8CB5786@easystreet.com> References: <3F5F7E35.B5DA4669@easystreet.com> <3F5F8742.C1C66903@engcorp.com> <3F5F95B9.A8CB5786@easystreet.com> Message-ID: <3F5F9AC7.3060609@rogers.com> achrist at easystreet.com wrote: >Peter Hansen wrote: > > >>Queue.Queue.get() ... >> >> >> > >That looks good. But that needs a thread to block, right? >A generator manages to run without being a thread (at least >overtly). If we have the suck() statement, we also need >something that's the opposite of a generator (a Sucker?) >and something that's the opposite of an iterator (a Suckee?). >I'm starting to get an idea why this is completely not all >there. > > You're probably looking for "watcher" or "dispatcher" patterns (using "pattern" loosely), i.e. something which is registered to respond to a particular type of "event" and process the results only when the event occurs. See Patrick 's pydispatcher project for a fairly good framework on which to build such things. http://pydispatcher.sourceforge.net/ In a more general sense, this is asynchronous programming, so at the high-end you could check out Twisted Matrix, which is a network-oriented asynchronous event system (pydispatcher is primarily an in-process system). >The main question this raises is "How lightweight are threads?" >Can I program with dozens or hundreds of python threads in a >program (for example under Windows) and not notice that this is >an inefficient or inept coding style? > > Large numbers of threads tend to cause problems eventually unless you're using micro-threads under Stackless Python. Since AFAIK, micro-threads haven't been re-implemented in Stackless 3.0, massively-threading approaches aren't likely to be a great approach just yet. As an aside, micro-threading, particularly when combined with continuations, allows for programming some of the most beautiful ways to deal with asynchronous events I've ever seen. That said, a few dozen, or even hundred threads may run quite nicely under Windows. Tim could likely give a better estimate, but I seem to recall him saying (way back when Stackless was 1.0) that Win95 could handle a far higher thread-load than Linux (possibly a few thousand threads?) I really wouldn't try running a few thousand threads on most boxes, however, the OSes just aren't designed to handle it well. HTH, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From syver at inout.no Mon Sep 15 08:13:38 2003 From: syver at inout.no (Syver Enstad) Date: 15 Sep 2003 14:13:38 +0200 Subject: caching the sql queries References: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> Message-ID: Gerhard H?ring writes: > In my opinion, this sort of caching should really be done in the > application layer, not in the database access layer. I didn't know that PHP programmers used layers at all :-) On a more serious note, Why do you think caching should be implemented in the application layer (is this the same as the domain/business layer) rather than the database access layer? From tim.parkin at pollenationinternet.com Sun Sep 7 07:42:19 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Sun, 7 Sep 2003 12:42:19 +0100 Subject: Comments on Python Redesign In-Reply-To: Message-ID: <001a01c37535$1e75a9d0$0a00a8c0@JASPER> Terry Ready said: > YUCK< YUCK< YUCK. > > The pollenation site is one of the worst I have seen. The mockup page > has teeny type that IE will not enlarge. > > I care that the site remain physically readable and that it remain a > vehicle for information rather than childish egos. > > Using IE6, I need a magnifying glass > to read this page. This is done in the arrogant style of 'we know > better than you what type size you should have'. Also known as the > 'control the user experience' school. Awful. For me, one of the > worse pages I have ever seen. Anti-Pythonic. > > > interior page: > Only slightly better. The low contrast gray-on-gray comments page is > also barely readable. (Others reported the same.) For my > less-than-perfect 50+ year-old eyes, it is physically the WORST > comments page I have ever seen. It is a case study in > anti-accessibility design. The person responsible should not touch > our site. Perhaps the people who have commented on the site should realise it's a proposal and a work in progress. As constructive comments go the only feedback I have gathered is that the fonts are too small and the contrast is a little low. I've adjusted contrast on key elements and also increased the font size. These pages are here : http://pollenation.net/assets/public/python-main-2.html http://pollenation.net/assets/public/python-interior-2.html also bearing in mind that the html page will be accessible and hence allow text resizing here is a sample of +1 text size. http://pollenation.net/assets/public/python-main-2larger.html http://pollenation.net/assets/public/python-interior-2larger.html Also, Terry, the design was an 'image', a 'mockup', a 'png' to be specific, it did not dictate font size. As far as accessibility is concerned, the only problem was the contrast and the font size both of which I've changed as I agree they were too low and too small respectively. Although I agree that the font size should be bigger, the current site is not an exemplar of accessibility. The following example taken from the interior page I have shown.The first is in comparison with my original design, the second show a comparison with the amendments showing normal and +1 font sizing. (the text on my samples may benefit from increasing the line height using css) http://pollenation.net/assets/public/python-text-comparison-new.gif http://pollenation.net/assets/public/python-text-comparison.gif As a side note, I haven't been to any school of 'control the user experience'. Furthermore I think making comments such as accusing me of having a 'childish ego' and being 'arrogant' are IMO extremely disrespectful and I would appreciate an apology. I am quite hurt and dissapointed to see such coments on what I had considered a respectable forum for discussion although I'm sure they are not representative. Tim Parkin Terry: > I otherwise do not have too much concern about particulars and therefore > not much to contribute. From Jon_Aquino at shaw.ca Sun Sep 7 02:03:56 2003 From: Jon_Aquino at shaw.ca (Jonathan Aquino) Date: 6 Sep 2003 23:03:56 -0700 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> Message-ID: (Paul Foley replied to my e-mail directly. Below are his remarks, which I was interested to read. At the end is my reply.) >> 1) I abhor redundancy. My first impression on seeing self as the first >> parameter of all method declarations is that it seems redundant -- it >> probably isn't technically, but it looks redundant: (self, (self, >> (self, (self, ... PF> Of course it's not redundant -- no more than the "x" is redundant in PF> def ln(x): PF> ... PF> def sin(x): PF> ... PF> def cos(x): PF> ... PF> def tan(x): PF> ... PF> def cosh(x): PF> ... PF> def sinh(x): PF> ... PF> etc., etc. Gee, look: (x, (x, (x, (x, (x, ... >> 2) The number of parameters in the method call is one less than the >> number of parameters in the method declaration. PF> No it isn't. The first argument is just in a strange place: PF> x.foo(y,z) PF> ^ ^ ^ PF> 1 2 3 PF> x.foo is really just weird syntax for curry(foo, x); i.e., PF> q = x.foo PF> is essentially PF> q = lambda *a: foo(x, *a) PF> (but in a different namespace), so PF> x.foo(y,z) is q(y,z) is (lambda *a: foo(x, *a))(y,z) PF> and there are exactly as many args in the call as in the definition PF> (as, of course, there must be!) PF> Of course, it would be infinitely better to write foo(x,y,z), opening PF> the way to _real_ OO (with multiple dispatch), but x.foo(y,z) is what PF> Python supports... I was interested to read your response. I think you and I are looking through different lenses. Perhaps influenced by my Java/Smalltalk background, I'm simply uncomfortable when I see (1) the first parameter on all method declarations being the object (didn't have to do this before) and (2) the number of things between the parentheses being different for the method declaration and the method call. On the other hand, when I read your response it's clear to me that (1) you are comfortable looking through the lens of functional programming, so that passing the object in as the first parameter makes perfect sense to you, and (2) the mismatch in the number of things between the parentheses is not a big deal to you (though "strange", you admit) because as an experienced Python programmer you know what's going on under the covers. My opinions are the frank opinions of a Java/Smalltalk programmer learning Python. And I'm not the only newbie who thinks this seems strange: the original newbie poster also opined that this is "odd". Out of the mouths of babes ... From rdsteph at earthlink.net Tue Sep 16 21:05:24 2003 From: rdsteph at earthlink.net (Ron Stephens) Date: 16 Sep 2003 18:05:24 -0700 Subject: App development for Sharp Zaurus PDA using QTopia? References: <3f6751fc$0$162$a1866201@newsreader.visi.com> Message-ID: <8e6e8e5d.0309161705.5d6aac96@posting.google.com> The Python ipk file python_2.3-1.1_arm.ipk can be downloaded from Riverbank software at http://www.riverbankcomputing.co.uk/zaurus/download.php . I have used a lot of command line Python progams on my Zaurus and they are quite fast and snappy. As for PyQt apps, there has been some discussion of them on the Zaurus Zone web discussion board at http://www.zaurus.com/dev/board/ and if you do a search on PyQt there you will see considerable information. The "gist" of the discussion seems to be that PyQt works fine, and that for many purposes is acceptably fast, but when using complex custom widgets (user programmed as opposed to standard QT widgets), the performance can get noticeably slower. It has also been reported that AnyGui works fine on the Zaurus, finding and using the Qt toolkit. Ron Stephens From CousinStanley at hotmail.com Sat Sep 27 14:31:30 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sat, 27 Sep 2003 11:31:30 -0700 Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: >>The fun you can have on windows, I've >>managed to create files that cannot be removed > >I've had that one simply by saving a web page in IE. Seriously >annoying. > | Do you mean windows exploder will not even delete it with right-click, delete? | Or doesn't it show up at all? (how do you know it exists? dos dir?) Under Win98 they show up AND can NOT be deleted from the Right-Click context menu ... They can be deleted with no problem under DOS .... The problem in Win98 for me came from saving web pages with extra LONG file names .... -- Cousin Stanley Human Being Phoenix, Arizona From __peter__ at web.de Tue Sep 30 15:49:00 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Sep 2003 21:49:00 +0200 Subject: How to instatiate a class of which the name is only known at runtime? References: Message-ID: Robert Brewer wrote: > def get_func(fullFuncName): > """Dynamically load a module and retrieve reference to the function > (NOT an instance).""" > > # Parse out the path, module, and function > lastDot = fullFuncName.rfind(".") > funcName = fullFuncName[lastDot + 1:] > modPath = fullFuncName[:lastDot] > > aMod = __import__(modPath, globals(), locals(), ['']) > aFunc = getattr(aMod, funcName) > > # Assert that the function is a *callable* attribute. > if not callable(aFunc): raise AssertionError("%s is not callable." % > fullFuncName) > > # Return a reference to the function itself, not the results of the > function. > return aFunc > >> Maybe you should raise a TypeError rather than an ImportError to > indicate >> that what is expected to be a function is not callable. > > How about an AssertionError, since it's only included for programmers, > not users? Well, *all* Exceptions are only for the programmer, as in an ideal world a user would never see a traceback. The Exception subclass is intended to give the programmer the possibility to handle different problems in different places. A typical use case for get_func() would be in a plug-in infrastructure and thus must be dealt with in the production environment. As an AssertionError is normally raised by the assert statement which will be removed when the code is compiled with the -O optimize flag, your usage is definitely non-standard. Peter From tim.parkin at pollenationinternet.com Mon Sep 8 10:07:15 2003 From: tim.parkin at pollenationinternet.com (Tim Parkin) Date: Mon, 8 Sep 2003 15:07:15 +0100 Subject: More Comments on Python Redesign In-Reply-To: Message-ID: <000e01c37612$881089e0$0a00a8c0@JASPER> Hi, I'm replying off list as, to be honest, I've had enough. Thanks for your message though. I've made a few changes to the pages and you can see them at http://pollenation.net/assets/public/python-main.htmlhttp://pollenation. net/assets/public/python-main.html ---------------------------------------------- Tim Parkin Managing Director Pollenation Internet Ltd www.pollenation.net m : 07980 59 47 68 t : 01132 25 25 00 -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Richie Hindle Sent: 08 September 2003 14:54 To: python-list at python.org Subject: Re: More Comments on Python Redesign [Tim] > [...] I was merely reacting to some unfounded criticisms of the > design I'd put forward. If I seem to have been a little over the top > then I apologise profusely but as you can imagine the reaction to 8 > weeks of hard work that had been put in by quite a few people. > Comments like the one you have made just make me realise how much > time we've all wasted. [Gerhard] > Thanks for your work on this. I for one *do* like your design prototype. > And I'm unpleasantly surprised by the tone of the criticism as well. Hear, hear. Regardless of whether one thinks the new design is an improvement (or even a worthwhile project to undertake), it should be clear that an awful lot of work has gone into it. People should take that into account when choosing how to express their opinions. For the record, I believe the Python website looks dated and could use some improvement. I have a few small problems with the proposed redesign, but I do think that given the simple question "which is better", the new one (with its typography issues resolved) is better. Here are some (hopefully constructive and dispassionate 8-) comments: o There is no "What is Python". A homepage should explain what the company/organisation/product/project *is*, either there on the homepage or one unambiguous link away. o *All* of the non-navigation content is dedicated to case studies, "News and announcements" and "Features and articles". This will need to be constantly updated, or you'll find that the same content sits there forever. Be careful - don't commit yourself to updating a dynamic-looking site for ever more, when you could publish a more static-looking site that still fulfills all the requirements. (I speak from experience here.) o It could be a fluke, but it looks like the page has been designed to fit onto an 800x600 screen. These days, people know about scrollbars. (That is not a flippant remark - only a small number of years ago it wasn't true.) Content should not be sacrificed for the sake of avoiding scrollbars (but the most important information should go near the top). Flexibility should not be sacrificed for visual appeal. o The design as it stands makes it difficult to change. What if everyone decides that there should be a link to the FAQ on the homepage - where would you put it? The design is *so* tight and well-balanced that making edits will degrade its appearance. Not sure how to address that one (but IMHO it's a consequence of not having enough space dedicated to static content, and striving for a perfect 4x3 800x600 rectangle). o I like the logo, and I like the visual look and feel. Well done! But I agree with others that the two-tone Py/thon is at best unnecessary and at worst confusing. -- Richie Hindle richie at entrian.com -- http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Tue Sep 30 03:44:48 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Sep 2003 09:44:48 +0200 Subject: isNumber? check References: Message-ID: Tony Meyer wrote: > Rob> I don't like that solution for this particular project because, as > Rob> you say yourself, if it says yes to the second question, it only > Rob> *may* be a number. I want to know for sure. > > This also works, although it may not be best for your situation (only does > int and float for brevity): > > """ > def isInt(s): > try: > i = int(s) > except ValueError: > i = None > return i > def isFloat(s): > try: > i = float(s) > except ValueError: > i = None > return i > def isNumber(s): > return isInt(s) or isFloat(s) > """ > > One advantage is that it returns the number (as an int (preferable) or > float) rather than just True/False (None is returned if it is not able to > be > turned into a number). You're probably going to want to turn it into a > number at some point anyway, right?, so why not do it in one step. Made-up use-case: s = "123" value = isNumber(s) if value is not None: value *= 2 else: raise ValueError, "%s is not a number" % s To me this looks like a deliberate attempt to obfuscate. Nobody would guess that you have to test the result of isNumber() against None and cannot reliably treat it as a boolean value. You should at least change the function name to something like stringToNumber(). The program flow is redundant: - convert to number - "convert" exception into special return value - check for special return value - throw exception I can think of very few situations where None could actually be *used* instead of a numerical value. > Note that "0" will come back as 0.0, though, because it evaluates as > False. It would be easy enough to special case that, if necessary. This is a bug that demonstrates that your isInt()/isFloat() implementation is not even well suited to implement isNumber(). Peter From aleax at aleax.it Sun Sep 7 04:33:45 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 07 Sep 2003 08:33:45 GMT Subject: Why python??? References: <8Um6b.34442$R32.1077180@news2.tin.it> <_ru6b.4463$I_2.688035@news20.bellglobal.com> Message-ID: Sean Ross wrote: ... >> >> attribute salary is Currency >> >> "Salario mensile" >> >> restriction quantity(1) >> >> >> >> on create code Python >> >> if value[0] < minimumSalary: >> >> value = [ minimumSalary ] >> >> return value >> >> %% >> > >> > My reflexive reaction was 'ugh'. My considered reaction is 'bravo'. >> >> Glad you reconsidered;-). I'm not enthusiastic about that %%, but we ... > Could "end code" replace "%%" as 'the end of embedded Python code' > delimiter in that language? Sure, with some effort. A single token would be a drop-in replacement, two tokens would be a bit of work. Alex From peter at engcorp.com Fri Sep 19 20:11:48 2003 From: peter at engcorp.com (Peter Hansen) Date: Fri, 19 Sep 2003 20:11:48 -0400 Subject: bizarre behavior using .lstrip References: <681f9321.0309191607.4e8b858a@posting.google.com> Message-ID: <3F6B9B44.9EAD3CF9@engcorp.com> Pete Jereb wrote: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 > > >>> s = 'chg bonn_fee' > >>> print s > chg bonn_fee > >>> print s.lstrip('chg ') > bonn_fee > > >>> s = 'chg conn_fee' > >>> print s > chg conn_fee > >>> print s.lstrip('chg ') > onn_fee > > Does this make any sense at all? where did the lead c in conn_fee go? Based on the behaviour you describe, I would assume lstrip() removes, starting at the beginning of the string, all characters which are *anywhere* in the argument string you give it, until it encounters a character not in that string, at which point it stops. -Peter From nicola-mingotti at libero.it Mon Sep 15 21:39:40 2003 From: nicola-mingotti at libero.it (Nicola Mingotti) Date: 16 Sep 2003 03:39:40 +0200 Subject: distributing a standalone python app. under Linux References: Message-ID: Alexander Eisenhuth writes: > Hallo alltogether, > > under windows, the py2exe is first choice, but has anybody done it > under Linux ? My first try with Installer > most linux these days already have a python interpreter installed so i think the simplest (simplistic) method would be send the *.py or *.pyc file/s . ( i follow this way when i give little apps to my friends ) i you want to ensure that the host machine has python ( or the right relase of it ) you can write a bash script that 1) install python 2) install your program [this part can be done in python itself] bye From duncan at NOSPAMrcp.co.uk Tue Sep 16 10:51:27 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 16 Sep 2003 14:51:27 +0000 (UTC) Subject: Print always puts newline (or adds a space) References: <3d9e1e6e689e3a662f59990c4b401713@news.teranews.com> <3F64DEF7.F98CFAB8@alcyone.com> Message-ID: Tobias Pfeiffer wrote in news:bk77de$pt7i4$1 at ID-162581.news.uni-berlin.de: >> Yep, call sys.stdout.write directly. > > Is it then also possible to "jump back" a few chars to, e.g., have a > progress... (damn, I forgot that word) however, that shows the > percentage of progress? Like print "25%" and then jump back three > chars and write "26%"? Back three characters: "\b\b\b" Back to start of line: "\r" e.g. >>> for i in range(10000): ... j = pow(2,i) ... if j%100: ... sys.stdout.write("\b"+"/-\\|"[i%4]) ... > And then, on my Linux machine, such things just don't happen at all. > E.g. in a loop like... > > for i in range(1000): > j = pow(2,i) > if j%100: print "#", > > ...I will get nothing for a long time and then ten "#" chars at one > time. Is there a solution for that? Maybe sys.stdout.flush()? -- 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 mertz at gnosis.cx Mon Sep 8 00:33:49 2003 From: mertz at gnosis.cx (David Mertz) Date: Mon, 08 Sep 2003 00:33:49 -0400 Subject: Comments on Python Redesign References: Message-ID: |>We developers should not be treated as second class Python users because |>someone got the idea that the page should look like what PHBs expect. Graham Fawcett wrote previously: |Developers will always be first-class Python users; it's a programming |language, after all. Whether they should be first-class users of |www.python.org, in my humble opinion, is questionable. |http://dev.python.org/ would fly from my fingers just as quickly as |http://www.python.org/ . There's something too this claim, actually. I find the page at http://ibm.com/ to be a bit too busy and marketing-oriented (but not nearly so much so as Parkin's sample); however, one click on the "Developers" link that is fairly prominent brings you right to the much better organized developerWorks site (where I write, after all). In fact, the general layout of dW is quite similar to that of the current python.org site. However, given that hardly anyone would bother making links to this new marketing-oriented http://www.python.org, the benefit of Fawcett's organization would be reduced. Any PHB who actually searched for a term like "Python programming" would still get http://dev.python.org/ since that's the one everyone would go to (at least as google's first choice). |They suggest that the owners of the site know business, that they bathe |regularly and might even own a tie. They offer smells of competency, |viability and longeivity, and these are good smells to offer to |decision-makers. I guess so. But as someone who makes a lot of recommendations via my writing, I find many of those same "knows business" signs to significantly lessen my first impressions of a product. I want something that works well, not something where the money goes to the marketing department. It's a big red flag to my mind to see a web page that looks like a brochure. Admittedly, I am nobody's -boss-. And I don't directly buy much software. But I do exercise a certain "moral influence" on technology choices. And after all... I'm not sure where the idea came from that the PSF is a for-profit company that WANTS to market Python (as opposed to just make the best tools possible). |P.S. Not in reply to you, Lulu, but I *do* think they should offer a |boxed Python set: bundle a Python 2.3 development environment on a |CD-ROM for $299; I'd like to announce that Gnosis Software is hereby offering a $299 boxed set of Python that includes the full development environment for Python 2.3 (and dozens of widely used 3rd party Python packages, chosen from widely used free software) for multiple platforms on CD; it further includes both an attractive spiral bound edition of Guido's Tutorial, the standard Library documentation, and a copy of Mertz' book _Text Processing in Python_ in the box. Just email for details on payment/shipping. The first order may take an extra week for setup time (it might take a couple days for me to talk to my local copy-shop about printing the box and so on). [only *wink*ing inasmuch as I question the market, for even one $299 sale, I really would create something quite nice looking] Yours, David... -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From wware at alum.mit.edu Mon Sep 1 12:23:48 2003 From: wware at alum.mit.edu (Will Ware) Date: Mon, 01 Sep 2003 12:23:48 -0400 Subject: Hunting a memory leak References: Message-ID: <3F537294.970A0D61@alum.mit.edu> Debian User wrote: > I'm trying to discover a memory leak on a program of mine... Several years ago, I came up with a memory leak detector that I used for C extensions with Python 1.5.2. This was before there were gc.* methods available, and I'm guessing they probably do roughly the same things. Still, in the unlikely event it's helpful: http://www.faqts.com/knowledge_base/view.phtml/aid/6006 Now that I think of it, this might be helpful after all. With this approach, you're checking the total refcount at various points in the loop in your C code, rather than only in the Python code. Take a look anyway. Good luck Will Ware From yaipa at yahoo.com Fri Sep 19 00:13:15 2003 From: yaipa at yahoo.com (yaipa h.) Date: 18 Sep 2003 21:13:15 -0700 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> <3y7ab.1043$Od.78860@twister.tampabay.rr.com> <3f697584$0$10966$fa0fcedb@lovejoy.zen.co.uk> <3f6a2bd3$0$10998$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <6e07b825.0309182013.3ddeb760@posting.google.com> You have our permission to go out an buy that second monitor, so that this DREADFUL problem never happens again. ;^) Someone has to run the regressions on a dual headed system and you get our vote. On a more serious note, you will find that you use the office printer a whole lot less on a dual head machine. --Alan "John Dean" wrote in message news:<3f6a2bd3$0$10998$fa0fcedb at lovejoy.zen.co.uk>... > Hi > You may or may know that BA is based on the Qt GUI Application Toolkit, so > you problem with the duel monitor set up is something I shall take up with > Trolltech. Unfortunately, none of use at theKompany run a duel monitor setup > so it is something that we are not aware of. Thank you for bring up this > problem and I will get back to you with a solution or our proposal for a > solution From amk at amk.ca Tue Sep 16 10:01:01 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 16 Sep 2003 09:01:01 -0500 Subject: from clipper move to python References: <3812075547.20030915130057@chead.org> <6.0.0.22.0.20030915085400.041dd200@66.28.54.253> Message-ID: On Tue, 16 Sep 2003 09:58:06 +0700, ads wrote: > But right now I'm still not ready using linux, a lot of my client were > using windows. Is someone know what should I use to create text > console application like clipper using python in (stupid) windows? Use consolelib: http://effbot.org/zone/console-index.htm . It's not code-compatible with curses. --amk From jepler at unpythonic.net Thu Sep 4 23:13:41 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 4 Sep 2003 22:13:41 -0500 Subject: [Python-Dev] Discordance in documentation... In-Reply-To: <20030904200448.GA1164@hannibal> References: <20030904200448.GA1164@hannibal> Message-ID: <20030905031341.GB2023@unpythonic.net> On Thu, Sep 04, 2003 at 10:04:48PM +0200, gminick wrote: > ...or is this just me? > > Let's take a look, Reference Lib, 4.2.1 Regular Expression Syntax says: > > "|" > A|B, where A and B can be arbitrary REs, creates a regular > expression that will match either A or B. > [...] > REs separated by "|" are tried from left to right, and the > first one that allows the complete pattern to match is considered > the accepted branch. This means that if A matches, B will never > be tested, even if it would produce a longer overall match. [...] > > And now a little test: [snipped] Here's how the "tried left to right" portion has a meaning. Consider the following stupid RE: "(.)|(a)" >>> import re >>> r = re.compile("(.)|(a)") >>> m = r.search("a") >>> m <_sre.SRE_Match object at 0x81c9458> >>> m.group(1) 'a' >>> m.group(2) >>> # None Nothing you can do will ever make the second group match. But if you write this: "(a)|(.)" then the string "a" will match on the left-hand side (this is guaranteed) but the string "b" will match the second group. If this thread is to be continued, it should be on python-list at python.org Jeff From grisha at modpython.org Tue Sep 30 14:24:11 2003 From: grisha at modpython.org (Gregory (Grisha) Trubetskoy) Date: Tue, 30 Sep 2003 14:24:11 -0400 Subject: What's the best MP3 (ID3) access library to use? In-Reply-To: <182bcf76.0309290349.452a6643@posting.google.com> References: <182bcf76.0309290349.452a6643@posting.google.com> Message-ID: <20030930142258.I30767@onyx.ispol.com> The most comprehensive one I know of is this, however, I think it's readonly: http://www.omniscia.org/~vivake/python/MP3Info.py Grisha On Mon, 29 Sep 2003, Paul Moore wrote: > > > I'm looking for a Python library to access ID3 information in MP3 > files. From skip at pobox.com Mon Sep 29 17:00:04 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 29 Sep 2003 16:00:04 -0500 Subject: isNumber? check In-Reply-To: <5B71DD32-F2BB-11D7-9145-003065F081D2@cs.brown.edu> References: <20030929142027.GA6750@nl.linux.org> <5B71DD32-F2BB-11D7-9145-003065F081D2@cs.brown.edu> Message-ID: <16248.40276.812650.276578@montanaro.dyndns.org> >> Why do you want to do so? Rob> I am writing an interpreter, and my parser has to decide if an Rob> expression is a number or not. Define a regular expression which matches your notion of what numbers look like in your interpreter while your tokens are still strings. Skip From eric.brunel at pragmadev.N0SP4M.com Wed Sep 24 12:05:04 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Wed, 24 Sep 2003 18:05:04 +0200 Subject: newbie script References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> Message-ID: Gerhard H?ring wrote: > ataraxia2500 wrote: > >> I wanna do a script that launch a programm xyz and relaunch xyz if it >> crashes. what kind of module do I need for such a task? > > > Something like this: > > import os > while 1: > os.system("j:/UT2003/System/UT2003.exe") > > os.system executes a program and waits, until the program is terminated. > But there's no way to know wether the program was terminated > deliberately or wether it crashed. There is a way. Quoting the documentation for the os module for os.system: The return value is the exit status of the process encoded in the format specified for wait(), except on Windows 95 and 98, where it is always 0. And for os.wait: exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. According to my experience, it is also better to test for None in the return value, since it seems to happen when everything is OK. So, doing: while 1: exitStatus = os.system("command...") if exitStatus is None: break if exitStatus & 0xFF == 0: break should do the trick. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From jepler at unpythonic.net Wed Sep 24 09:29:28 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 24 Sep 2003 08:29:28 -0500 Subject: How to tell if a forked process is done? In-Reply-To: <879b6a51.0309231547.428214f7@posting.google.com> References: <879b6a51.0309231547.428214f7@posting.google.com> Message-ID: <20030924132928.GI32482@unpythonic.net> os.waitpid() can tell whether a child has exited, and return its status if so. It can either enter a blocking wait, or it can return immediately. >>> pid = os.spawnv(os.P_NOWAIT, "/bin/sleep", ["sleep", "30"]) With WNOHANG, it returns immediately. The returned pid is 0 to show that the process has not exited yet. >>> os.waitpid(pid, os.WNOHANG) (0, 0) Wait for the process to return. The second number is related to the exit status and should be managed with os.WEXITSTATUS() etc. >>> os.waitpid(pid, 0) (29202, 0) Waiting again produces a traceback (no danger from another process created with the same pid) >>> os.waitpid(pid, 0) Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 10] No child processes If you want to use an argument list instead of an argument string, but always want to wait for the program to complete, use os.spawn* with P_WAIT. Jeff From pyth at devel.trillke.net Mon Sep 22 09:24:07 2003 From: pyth at devel.trillke.net (Holger Krekel) Date: Mon, 22 Sep 2003 15:24:07 +0200 Subject: was: Re: looking for MOP documentation In-Reply-To: <7h3d6dt9e8i.fsf@pc150.maths.bris.ac.uk>; from mwh@python.net on Mon, Sep 22, 2003 at 12:57:48PM +0000 References: <3F66F516.3D06D946@engcorp.com> <3F69AD0F.53D51719@engcorp.com> <3F69D215.5649AF66@hotmail.com> <3F69DFEB.5B05CED8@engcorp.com> <7h37k45j895.fsf@pc150.maths.bris.ac.uk> <3F6B2AB1.2D839EF5@engcorp.com> <7h3d6dt9e8i.fsf@pc150.maths.bris.ac.uk> Message-ID: <20030922152407.B24546@prim.han.de> Michael Hudson wrote: > Holger Krekel writes: > > > Although probably 2/3 of the implementation of Python deal with the > > type/object implementations, from a using-the-language point of view > > the syntax probably contributes more obviously to the observed > > "simplicity" of Python. > > OK, I disagree with you, too :-) Nah, that's almost impossible because I have carefully interspersed the above sentence with "probably" and "more obviously" :-) > > But the term "meta object protocol" seems to point much more into > > the direction of types/objects as Michael suggests and here Python > > has a lot to offer. Is there some free material on MOP somewhere? > > http://www.elwoodcorp.com/alu/mop/contents.html Uuh, it's all LISP based, i see. Maybe i still give it a try. Anyone willing to give a pythonic crash-course in LISP in - say - 10 x 5-line paragraphs? :-) > looks like being a version of AMOP online, you know that book I > brought with me to one of the pypy sprints :-) (actually, it may have > been the Gothenbourg sprint). I can bring it to the next sprint I > come to, if you like. sounds good and like more fun than funding papers. cheers, holger From bogus@does.not.exist.com Wed Sep 10 15:46:20 2003 From: bogus@does.not.exist.com () Date: Wed, 10 Sep 2003 21:46:20 +0200 Subject: How to instatiate a class of which the name is only known at runtime? In-Reply-To: References: Message-ID: <20030910194620.GD2136@darkstar.localdomain.fake> On Tue, Sep 09, 2003 at 04:16:45PM -0400, John Roth wrote: > "Marco Herrn" wrote in message > news:mailman.1063135996.15871.python-list at python.org... > > > Currently it is planned that all these classes reside in a specific > > subdirectory. Is it possible to say 'import * from subdirectory' ? > > No. It is possible to load the names of all the modules in the > subdirectory, though. That doesn't tell you what classes are in > each module unless you either establish some standards or use > a configuration file of some kind. That is ok to me. I know the name of the subdirectory and the name of the class can be found in a configfile. The class then has to be in a file with the same name as the class, but that is ok. I already planned establishing a certain naming convention. > You could, of course, simply import all of the modules, and then > loop through them looking for the classes. How would this be done? Would I have to search the directory for files and load each of them with __import__("subdir/filename")? Marco -- Every morning, I get up and look through the 'Forbes' list of the richest people in America. If I'm not there, I go to work -- Marco Herrn herrn at gmx.net (GnuPG/PGP-signed and crypted mail preferred) Key ID: 0x94620736 From achrist at easystreet.com Sun Sep 21 21:14:42 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Sun, 21 Sep 2003 18:14:42 -0700 Subject: Help me choose a C++ compiler to work with Python References: <616fccba.0309210907.1e35b92d@posting.google.com> <3dd5593c.0309211615.747ba123@posting.google.com> Message-ID: <3F6E4D02.7868D52C@easystreet.com> d2003xx wrote: > > > I use Windows XP and 98. Have very little experience with C++. Am > > doing statistical and other simulations that require billions of > > calculations (taking 1 to 2 hours in Excel VBA). GCC is free, MS > > C++.Net is affordable > It is equally trivial to connect Python to Delphi using ctypes. Delphi can easily make a DLL that looks to the outside world like C. I have found Delphi to be maybe a little bit slower than MS C, but a little faster than gcc. They are all pretty close on speed, so you can't really pick a winner a priori. If you are doing VBA now, can't you buy the entry-level version of VB for around 100 bucks and create C-callable DLL's? Al From pkbf-tspx at dea.spamcon.org Mon Sep 22 13:53:16 2003 From: pkbf-tspx at dea.spamcon.org (chauhan) Date: 22 Sep 2003 10:53:16 -0700 Subject: Trouble with wxListCtrl Message-ID: <49c4d036.0309220953.29b6fd1e@posting.google.com> Hi, I am new to pogramming. I have written a small program which retrieves emails from server, unless all the messages are loaded only then it displays on screen properlely. Whole thing works fine if I use events to activate logMail() after start but I don't know how to activate an event at the start (witout pressing mouse or menu key) as I want this to load messages at the start of the program. I am also having problem with statement self.list.GetItemText(self.currentItem). The statement self.currentItem gives the current selected item position on listctrl this statement works fine in wxPanel (demo example wxlistctrl in wxPython) and not with wxFrame which I am using now as I want menubar in my application. Can some body tell me how to get the current selected items position in wxListCtrl with wxFrame? Same kind of problem with wxPoint(self.x, self.y) but I can use wxGetMousePosition(). Also I would like to know how to check if internet connection is on. Thanks in advance Chauhan ######### from wxPython.wx import * import poplib from poplib import * emailloglist=[2,('mail.icenter.net','username?','password?'),('pop.netzero.com','username?', 'password?'),] list_items = [ "item value", "on any", "Right click", ] class main_window(wxFrame): def __init__(self, parent, id, title): wxFrame.__init__(self, parent, -1, title, size = (800, 600), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) splitter = wxSplitterWindow(self, -1, style=wxNO_3D|wxSP_3D) tID=wxNewId() self.list = wxListCtrl(splitter, tID, style=wxLC_REPORT|wxSUNKEN_BORDER|wxLC_SINGLE_SEL) self.log = wxTextCtrl(splitter, -1, style=wxTE_MULTILINE) splitter.SplitHorizontally(self.list, self.log, 450) splitter.SetMinimumPaneSize(20) self.list.InsertColumn( 0, 'listTitle' ) for x in list_items: self.list.InsertStringItem(0,x) self.Show(true) EVT_COMMAND_RIGHT_CLICK(self.list, tID, self.OnRightClick) EVT_RIGHT_UP(self.list, self.OnRightClick) self.log.WriteText(emailloglist[emailloglist[0]][2]+'\r\n') p=self.logMail() def OnRightClick(self, event): self.log.WriteText("OnRightClick %s\n" % self.list.GetItemText(1))#GetItemText(self.currentItem) if not hasattr(self, "popupID1"): self.popupID1 = wxNewId() EVT_MENU(self, self.popupID1, self.OnPopupOne) menu = wxMenu() menu.Append(self.popupID1, "FindItem tests") self.PopupMenu(menu, wxGetMousePosition()) #wxPoint(self.x, self.y) menu.Destroy() def OnPopupOne(self, event): self.log.WriteText("Popup one Find: "+str(self.list.FindItem(-1, 'on any'))+'\r\n') def logMail(self): try: print wxSocketBase.IsConnected p = POP3 (emailloglist[emailloglist[0]][0]) self.log.WriteText(p.user (emailloglist[emailloglist[0]][1])+'\r\n') self.log.WriteText(p.pass_ (emailloglist[emailloglist[0]][2])+'\r\n') return p except error_proto: self.log.WriteText('msg') class App(wxApp): def OnInit(self): frame = main_window(None, -1, "wxPython: (A Demonstration)") self.SetTopWindow(frame) return true app = App(0) app.MainLoop() ######## From adalke at mindspring.com Wed Sep 24 00:44:21 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 24 Sep 2003 04:44:21 GMT Subject: Pre-PEP: reverse iteration methods References: Message-ID: Sean Ross: > This will mostly just be some alternate naming suggestions: > > How about just ".backwards", where backwards acts like a read-only property > that returns a generator for reverse iteration? -1 from me. 'backwards' looks to me like something which changes the list ordering in place, like what 'reverse' does. Or something which returns a new list but in reverse order. It's an adjective, when it should be a verb. ibackwords would work, but so would riter or reviter or variations thereof. Andrew dalke at dalkescientific.com From bluheaven2 at yahoo.com Fri Sep 5 14:02:49 2003 From: bluheaven2 at yahoo.com (Dave) Date: 5 Sep 2003 11:02:49 -0700 Subject: Python port to Swiss Ephemeris work with 2.3? References: <734b753f.0309041612.2066021@posting.google.com> <734b753f.0309042237.5ded1230@posting.google.com> Message-ID: <734b753f.0309051002.4e625e8e@posting.google.com> > I found it on the Vaults under the Misc heading. Looks good. > Looks a lot better than my interface. > You need to recompile using the same compiler that Python > was compiled with (I believe that's VC 6 for the Windows version.) > Extension modules ***always*** need to be recompiled for major > Python releases. John Roth Thanks John, I wouldn't know how to do that since I haven't worked with C much. -Dave From mertz at gnosis.cx Sun Sep 7 20:57:38 2003 From: mertz at gnosis.cx (David Mertz) Date: Sun, 07 Sep 2003 20:57:38 -0400 Subject: "Python Redesign" (fwd) Message-ID: wrote: |Can you explain to me why on earth I would put a screenshot of a HTML |page up instead of the actual HTML. Not really. But I could come up with something a little more plausible than explaining why you would design a mockup -without- using HTML. I suppose the mildly plausible explanation would be that you wanted to show how it rendered in your designed-with browser. On the other hand, I've never heard of anyone designing a page mockup that wasn't in HTML (possibly with CSS, Javascript, etc)... and I cannot quite figure out why you would do such a thing. |As a respected contributor to the Python world, perhaps you could spend |some more time being constructive about the design rather than being |destructive. I guess you chose not to read the suggestions that I made, or that many other people made. I don't reckon there's much else I can do... except, of course, vigorously oppose use of this bad design. Btw. What is this "commercial customer" thing you speak of? Python is guaranteed to remain Free Software. It's not like the PSA is selling "Python boxed sets"... which you seem to believe. 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 mwilson at the-wire.com Thu Sep 11 17:47:42 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 11 Sep 2003 17:47:42 -0400 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> Message-ID: <+1OY/ks/KP3R089yn@the-wire.com> In article , "Steve Holden" wrote: >"Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote... >> And if in some future version of Python the suggestion I made was >> implemented, when you see f(x) you will still know that x cannot be >> rebound - but when you see f(ref x) you will know that x may well be >> rebound. >> >OK, remind me why this is better than > >x = Inc(x) > >or > >x, y = DoubleInc(x, y) My poster child here would be the idiom number, digit = divmod (number, base) which is really handy in converting number to a representation in some given base. A different function could simplify this (in a way) to digit = refdivmod (ref number, base) but at the cost of a new function def refdivmod (ref a, b): ... which, for all the duplication and the new keyword is *less* capable than what we have, since we can use divmod for everything refdivmod could do .. but not vice versa. (A bit late, since everybody in the thread already agrees): Mel. P.S. This seems like another case of a change that simplifies some particular line of code, while spreading complication throughout the rest of the language (new keywords, more complexity hidden behind subroutine calls, non-obvious namespace handling.) I haven't been able to articulate this opinion of mine well enough to expect it to stand up in a newsgroup. Gerald Weinberg's _The Psychology of Computer Programming_ has some remarks on language design that may help me out eventually. Yet another discussion of removing the 'self' parameter from class methods started me off. MPW From davidb at mcs.st-and.ac.uk Wed Sep 17 17:44:56 2003 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 17 Sep 2003 14:44:56 -0700 Subject: import on modules/files that don't have .py extension References: <899f842.0309170649.517e0bb9@posting.google.com> Message-ID: <4de76ee2.0309171344.1d919cee@posting.google.com> anthony_barker at hotmail.com (Anthony_Barker) wrote in message news:<899f842.0309170649.517e0bb9 at posting.google.com>... > Is it possible to import modules/files that have something other than > the .py extension? You can use the imp module to achieve this. For example, for a module called "mymodule" in a source file called "myfile" then import imp mymodule = imp.load_source("mymodule", "myfile") should import the contents of "myfile" as a module which you can use as normal. The "mymodule" parameter to the load_source function presumably just ensures that mymodule.__name__ = "mymodule" so that anything relying on that has no nasty surprises. Note that, for this example, you may end up with a file called "myfilec" alongside "myfile". David From bokr at oz.net Wed Sep 10 00:32:38 2003 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2003 04:32:38 GMT Subject: CGI -- generating images -- \x0A always added! References: Message-ID: On Wed, 10 Sep 2003 03:05:51 GMT, "M-a-S" wrote: >Hi All, > >I'm trying to use Python for generating (or copying) images. >The environment is Python 2.3/Apache 2.0.43/Windows XP. >I couldn't make Apache use mod_python (anybody can help? >Apache complains "The requested operation has failed" >if I add LoadModule python_module modules/mod_python.so) >so I use the CGI mechanism. This is the sample: > I would try switching to using sys.stdout.write >#!C:\Apps\Python\python.exe -u > import sys >img = open( 'a.gif', 'rb' ) # OK, don't make the image, just use the file >if img: > data = img.read() > img.close() > >print "Content-type: image/gif" >print The above two might work ok, but might as well use sys.stdout.write consistently instead, e.g., # untested ... sys.stdout.write('Content-type: image/gif\n\n') # should be the same > >print data, sys.stdout.write(data) sys.stdout.close() > ># EOF > >Everything's good, and '-u' helps not to add '\x0D' for each '\x0A' >inside the data. BUT it seems that the last print ALWAYS adds LF >'\x0A' in spite of the final comma. How can I fix that? Thank you. > HTH. It should be easy to try. Let us know. Regards, Bengt Richter From uce at ftc.gov Thu Sep 18 16:00:26 2003 From: uce at ftc.gov (Gordon Airport) Date: Thu, 18 Sep 2003 16:00:26 -0400 Subject: Scaling Tk scrollbar handles In-Reply-To: References: Message-ID: Thanks, I hadn't seen those. There are quite a few documents about this out there with highly variable readability, comprehensiveness, and up-to-date-edness. I think I've been relying on the effbot documents too much. From dokaspar at student.ethz.ch Thu Sep 25 14:01:02 2003 From: dokaspar at student.ethz.ch (Dominik Kaspar) Date: 25 Sep 2003 11:01:02 -0700 Subject: sockets Message-ID: <62e9c66e.0309251001.2bfa684@posting.google.com> i want to write a thread in python that listens for client connections to a socket and creates new server threads for each of the connections it detects. is there a simple way to do this by using socket.listen(1) and socket.accept()? -- dominik From ivoras at fer.hr Thu Sep 18 05:49:31 2003 From: ivoras at fer.hr (Ivan Voras) Date: Thu, 18 Sep 2003 11:49:31 +0200 Subject: Multithreading and locking Message-ID: Is it true what I heard (as a "rumour" of sorts), that in multithreaded Python programs global variables are already automagically protected by mutexes? Can someone clarify on that? -- -- Every sufficiently advanced magic is indistinguishable from technology - Arthur C Anticlarke From martin at v.loewis.de Mon Sep 22 16:31:52 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 22 Sep 2003 22:31:52 +0200 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> <299f1138.0309220724.7b684aa2@posting.google.com> Message-ID: jallan at smrtytrek.com (jallan) writes: > So is Python just another shit legacy implementation? Yes :-) Regards, Martin From peter at engcorp.com Sun Sep 28 17:57:29 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 28 Sep 2003 17:57:29 -0400 Subject: Checking for invalid keyword arguments? References: Message-ID: <3F775949.18A9312A@engcorp.com> Roy Smith wrote: > > I've got a function that takes a couple of optional keyword arguments. > I want to check to make sure I didn't get passed an argument I didn't > expect. Right now I'm doing: > > conversion = None > drop = False > for key, value in kwArgs.items(): > if key == 'conversion': > conversion = value > elif key == 'drop': > drop = value > else: > raise TypeError ('Unexpected keyword argument %s' % key) > > which seems kind of verbose. Is there a neater way to do this check? I'd suggest writing a general-purpose subroutine which can do the necessary checks for you, then use a one-liner to call it with the "pattern" you require. It might look like this for the call: conversion, drop = checkOptArgs(kwArgs, conversion=None, drop=False) This clearly shows the allowed keyword args, their default values, and assigns values to the local names on return. It can of course raise the TypeError for you if a bad name is in kwArgs. -Peter From fuerte at sci.fi Tue Sep 2 12:42:19 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Tue, 02 Sep 2003 19:42:19 +0300 Subject: Simple question: How to pass a C++ class reference to a callback? In-Reply-To: References: <17fbc98a.0309020423.11ac7b8d@posting.google.com> Message-ID: David Abrahams wrote: > "T. Panbru" writes: > >>Try encapsulating your C++ class reference in a CObject, using: >> >> PyObject* PyCObject_FromVoidPtr( void* cobj, void (*destr)(void *)) >> void* PyCObject_AsVoidPtr( PyObject* self) >> >>and so forth, to go back and forth between the C++ and Python realms. >> >>Check out the Python docs at: >> >> http://www.python.org/doc/2.3/api/cObjects.html >> > > > Or use one of the high-level wrapping tools such as Boost.Python > (http://www.boost.org/libs/python) which make this stuff much easier > and safer. Boost.Python is not 2.3 compatible yet, but it seems very good. Harri From peter at engcorp.com Mon Sep 15 16:35:41 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Sep 2003 16:35:41 -0400 Subject: calling objects parents' __init__? References: Message-ID: <3F66229D.1C28AD48@engcorp.com> user at domain.invalid wrote: > > Normally, when I inherit from a class that I have written, > I want instances of the new class to call the __init__ of > the old (actually, starting from the top of the tree, and > moving on down). > > What is the preferred way to do this? The preferred way is to call your parent's __init__, if it has one: class Parent: def __init__(self): # useful stuff happens here class Child: def __init__(self): Parent.__init__(self) # other stuff, some useful, happens here There are more sophisticated, less readable approaches, and I suspect Python 2.2 or 2.3 add a new idiom as well. -Peter From abelikov72 at hotmail.com Fri Sep 5 01:20:45 2003 From: abelikov72 at hotmail.com (Afanasiy) Date: Fri, 05 Sep 2003 05:20:45 GMT Subject: Coloring markup simply... Message-ID: What's the best method for coloring simple markup? You can assume it is not HTML or XML or valid anything except markup which happens to look somewhat like them. You can assume xyz < > = and " always exist for each tag. What methods are usually employed? I am not exactly looking for a boxed or roundabout solution using a big 3rd party package. I am curious and want something simple and/or clever. I would like to know what the common methods for doing this might be. If re supported some sort of nesting/recursion I think I could do it, but it seems it does not, so I am currently using a bunch of re expressions, and it's not exactly fun. I am considering a straight parser with finite state machine instead... but I thought I'd ask... What other methods? ( p.s. The coloring aspect is not exactly important, as long as whatever the method is would allow me to color it, ie. parse it ) From mwh at python.net Thu Sep 18 09:28:14 2003 From: mwh at python.net (Michael Hudson) Date: Thu, 18 Sep 2003 13:28:14 GMT Subject: was: Re: looking for MOP documentation References: <3F62123C.F671D058@engcorp.com> <3F6319E9.4C7BAA0F@engcorp.com> <3F66F516.3D06D946@engcorp.com> <3F69AD0F.53D51719@engcorp.com> Message-ID: <7h3k786cjsf.fsf@pc150.maths.bris.ac.uk> Peter Hansen writes: > Paul Foley wrote: > > > > On Tue, 16 Sep 2003 07:33:42 -0400, Peter Hansen wrote: > > > > > Ng Pheng Siong wrote: > > >> > > >> According to Peter Hansen : > > >> > kasper graversen wrote: > > >> > > On Fri, 12 Sep 2003 14:36:44 -0400, Peter Hansen wrote: > > >> > > >> Erm, what's "MOP" mean? > > >> > > what has all this talk to do with documentation of the MOP??? > > >> > Er, if you'll look back, you'll see that Anthony asked what MOP > > >> > meant > > >> > > >> Meta Object Protocol. > > > > > Thanks, but one might say that this is what it spells, not what it _means_. > > > > Read the introduction to _The Art of the Metaobject Protocol_, at > > http://www2.parc.com/csl/groups/sda/publications/papers/Kiczales-AMOP/ > > Thanks Paul. > > If that description is taken as authoritative about "the MOP", then it > seems to me after a first reading that Python *has no MOP*, and probably > will not, given Guido's approach to language design. > > Am I correct? I'm not sure. In Python, you can come fairly close to being able to do class MyType(object): ... and have instances of instances of MyType look pretty much like instances of instances of type (which is to say, regular Python objects), which I think of as being one of the properties of having a full blown MOP. But I don't think you can get all the way there (e.g. getting isinstance to work properly with ones custom objects & types seems unlikely). >From one viewpoint, this is partially because various bits of the Python core just reach in for, e.g., the tp_bases field of a type object. To have a "true MOP", it feels as if these bits would need to be changed to respects any descriptors that may have been set on, e.g. again, __bases__. This would probably have performance (and circularity) implications for the interpreter. (I spent a while last year trying to find a way of creating a metaclass that would allow mutation of __bases__, which is where these thoughts come from). > Or does the term really have a broader meaning than what > I get out of that page, and Python in fact has aspects that could be called > its meta-object protocol? > > Key phrase: "Metaobject protocols are interfaces to the language > that give users the ability to incrementally modify the language's > behavior and implementation...". Near as I can tell, part of the > whole character of Python is that a user *cannot* do either of those > things. I would say Python's metaclass facility is at least part of a MOP. Python certainly does not have as thorough a MOP as that describe in the Art of the Metaobject Protocol, to be sure. I'm not sure how much interest (or value...) there would be in extending what we have now. Could make an interesting dissertation project :-) Cheers, mwh -- Finding a needle in a haystack is a lot easier if you burn down the haystack and scan the ashes with a metal detector. -- the Silicon Valley Tarot (another one nicked from David Rush) From kalike2003 at netscape.net Fri Sep 12 10:54:58 2003 From: kalike2003 at netscape.net (Kali K E) Date: 12 Sep 2003 07:54:58 -0700 Subject: Copying latest version of the file Message-ID: Hi, I am new to Python and excuse me if this problem is very trivial. The problem is like this. There is a directory (dirA) that contains files like mypacakge-2.2.5-15.rpm, mypacakge-2.2.5-90.rpm, anotherpackage-3.4.25.rpm etc.. As can be seen, some of the files are new versions of same rpm (mypacakge-2.2.5-15.rpm, mypacakge-2.2.5-90.rpm in this example). It is also true that their timestamps are different. The program has to check for latest version of each package and copy them to another directory (dirB). That means in this case, it has to copy mypacakge-2.2.90.rpm to another directory. The directory dirA would be containing more than 500 files. Out of these many, about 100 files may be having new version. Another point is the number of files of same package is NOT limited to 2. So we may have mypacakge-2.2.5-15.rpm, mypacakge-2.2.5-90.rpm, mypacakge-2.2.5-100.rpm, mypacakge-2.2.5-227.rpm in dirA and only mypacakge-2.2.5-227.rpm has to be copied to dirB. The same thing has to be repeated in other directories at the same level as dirA. Please let me know how to do this. Thanks, Kali From jjl at pobox.com Sun Sep 21 17:43:56 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Sep 2003 22:43:56 +0100 Subject: Proxy Authentication using urllib2 References: Message-ID: <87u1754y1v.fsf@pobox.com> Andre Bocchini writes: > I'm having some trouble using proxy authentication. I can't figure > out how to authenticate with a Squid proxy. I know for a fact the > proxy is using Basic instead of Digest for the authentication. I can > authenticate just fine using Mozilla. I've done some Google searches, > but the closest piece of code I've is is for HTTPBasicAuthHandler: [...] > proxy_handler = urllib2.ProxyHandler({"http" : "http://myproxy:3128"}) > proxy_auth_handler = urllib2.ProxyBasicAuthHandler() > proxy_auth_handler.add_password(None, "myproxy", "myname", "mypass") > opener = urllib2.build_opener(proxy_handler, proxy_auth_handler) > urllib2.install_opener(opener) > f = urllib2.urlopen("http://www.python.org") > data = f.readlines() Can't see anything wrong with that. > I always get a 407 error. Are you sure you don't need a realm? Try sniffing what Mozilla and Python are sending (using eg. ethereal). You *should* get a 407 response, IIRC, but then urllib2 should respond with an appropriate Proxy-authorization header. If that helped, please look at the doc patch here http://www.python.org/sf/798244 test it, and post a comment to say whether or not it worked (and which examples you tried -- preferably all of them ;). John From a9605473 at unet.univie.ac.at Wed Sep 17 04:43:30 2003 From: a9605473 at unet.univie.ac.at (Gaubitzer Erwin) Date: Wed, 17 Sep 2003 10:43:30 +0200 Subject: Dislin compilation References: <3f62eabc$0$12398$3b214f66@usenet.univie.ac.at> <3F6725B7.1E854D44@linmpi.mpg.de> Message-ID: <3f681ef1$0$19360$3b214f66@usenet.univie.ac.at> Thanks to all, who have answered (per mail or in thread) For all others, who also don't know how to do I summarize shortly 1. The make_py script looks for the Include and the Config directories. These are in the Python developers version (python-devel rpm for SuSE: PYTH_INC="/usr/include/python2.2/" for python version 2.2 PYTH_CONF="/usr/lib/python2.2/config" in the appropriate section (lnx for Linux) 2. The DISLIN variable has to be defined, for instance in the shell by export DISLIN=/usr/local/dislin (default directory) 3. Calling make_py lnx for Linux OS 4. Copying the module to the right directory cp dislinmodule.so /usr/local/dislin/python Now it should work From max at nospam.com Tue Sep 2 15:44:22 2003 From: max at nospam.com (max) Date: Tue, 02 Sep 2003 19:44:22 GMT Subject: current HTML generation frameworks rundown... Message-ID: Hi all, I am looking for a recent rundown of HTML generation frameworks rated by 1) being up-to date 2) power 3) complexity and more informally - what do python folks like to use for HTML generation these days? thanks - max From webmaster at ac-strasbourg.fr Fri Sep 26 05:25:25 2003 From: webmaster at ac-strasbourg.fr (webmaster at ac-strasbourg.fr) Date: 26 Sep 2003 02:25:25 -0700 Subject: Compiling informxidb-1.3 on python2.2? References: Message-ID: <92c875f.0309260125.7fcdceeb@posting.google.com> I'm trying to compile it in order to use it on Zope 2.6.1 (python 2.1.3) on a RedHat 7.3, with Informix SDK csdk280_UC21LIN. Is it possible at least ? I've find a few infos about it in the ng, and here's what I dit : cd $INFORMIXDIR/lib/esql mkdir tmp cp libifgen.so orig_libifgen.so cp libifgen.a tmp cd tmp ar x libifgen.a gcc -shared -o libifgen.so *.o cp libifgen.so .. cd .. rm -rf tmp su - root ldconfig In informixdb-1.3 sources directory: ./configure Edit ext/Makefile: change CFLAGS (line 100) to include -I${INFORMIXDIR}/incl/esql esql ext/_informix.ec" and here's what I get : /usr/informix/lib/esql/libifos.so: the use of `mktemp' is dangerous, better use `mkstemp' /usr/lib/gcc-lib/i386-redhat-linux/2.96/../../../crt1.o: In function `_start': /usr/lib/gcc-lib/i386-redhat-linux/2.96/../../../crt1.o(.text+0x18): undefined reference to `main' /tmp/cc3c2Xz6.o: In function `ifxdbCursor': /tmp/cc3c2Xz6.o(.text+0x346): undefined reference to `PyObject_Init' /tmp/cc3c2Xz6.o: In function `ifxdbCurClose': /tmp/cc3c2Xz6.o(.text+0x5bc): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x5c1): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `ifxdbPrintError': /tmp/cc3c2Xz6.o(.text+0x753): undefined reference to `PyErr_SetString' /tmp/cc3c2Xz6.o: In function `ifxdbClose': /tmp/cc3c2Xz6.o(.text+0x7e2): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x7e7): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `connectionGetAttr': /tmp/cc3c2Xz6.o(.text+0x833): undefined reference to `Py_FindMethod' /tmp/cc3c2Xz6.o: In function `ifxdbCommit': /tmp/cc3c2Xz6.o(.text+0x90e): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x913): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `ifxdbRollback': /tmp/cc3c2Xz6.o(.text+0x9aa): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x9af): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `ibindRaw': /tmp/cc3c2Xz6.o(.text+0xbb5): undefined reference to `dbiValue' /tmp/cc3c2Xz6.o(.text+0xbc8): undefined reference to `PyObject_Str' /tmp/cc3c2Xz6.o: In function `ibindDate': /tmp/cc3c2Xz6.o(.text+0xcb5): undefined reference to `dbiValue' /tmp/cc3c2Xz6.o(.text+0xcc0): undefined reference to `PyNumber_Long' /tmp/cc3c2Xz6.o(.text+0xcdd): undefined reference to `PyLong_AsLong' /tmp/cc3c2Xz6.o(.text+0xd93): undefined reference to `PyErr_SetString' /tmp/cc3c2Xz6.o: In function `ibindString': /tmp/cc3c2Xz6.o(.text+0xdb9): undefined reference to `PyObject_Str' /tmp/cc3c2Xz6.o(.text+0xe36): undefined reference to `PyLong_Type' /tmp/cc3c2Xz6.o: In function `ibindFcn': /tmp/cc3c2Xz6.o(.text+0xeb5): undefined reference to `dbiIsRaw' /tmp/cc3c2Xz6.o(.text+0xed3): undefined reference to `dbiIsDate' /tmp/cc3c2Xz6.o(.text+0xeeb): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `bindInput': /tmp/cc3c2Xz6.o(.text+0x10b4): undefined reference to `PyObject_Size' /tmp/cc3c2Xz6.o(.text+0x1112): undefined reference to `PySequence_GetItem' /tmp/cc3c2Xz6.o(.text+0x1187): undefined reference to `PyErr_SetString' /tmp/cc3c2Xz6.o: In function `bindOutput': /tmp/cc3c2Xz6.o(.text+0x1259): undefined reference to `PyTuple_New' /tmp/cc3c2Xz6.o(.text+0x12d5): undefined reference to `Py_BuildValue' /tmp/cc3c2Xz6.o: In function `ifxdbCurExec': /tmp/cc3c2Xz6.o(.text+0x1538): undefined reference to `PyArg_ParseTuple' /tmp/cc3c2Xz6.o(.text+0x1828): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x182d): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x1839): undefined reference to `PyEval_SaveThread' /tmp/cc3c2Xz6.o(.text+0x187d): undefined reference to `PyEval_RestoreThread' /tmp/cc3c2Xz6.o(.text+0x18b3): undefined reference to `Py_BuildValue' /tmp/cc3c2Xz6.o: In function `doCopy': /tmp/cc3c2Xz6.o(.text+0x1a7e): undefined reference to `PyInt_FromLong' /tmp/cc3c2Xz6.o(.text+0x1a87): undefined reference to `dbiMakeDate' /tmp/cc3c2Xz6.o(.text+0x1aa4): undefined reference to `PyInt_FromLong' /tmp/cc3c2Xz6.o(.text+0x1aad): undefined reference to `dbiMakeDate' /tmp/cc3c2Xz6.o(.text+0x1b08): undefined reference to `Py_BuildValue' /tmp/cc3c2Xz6.o(.text+0x1b20): undefined reference to `PyFloat_FromDouble' /tmp/cc3c2Xz6.o(.text+0x1b3c): undefined reference to `PyFloat_FromDouble' /tmp/cc3c2Xz6.o(.text+0x1b64): undefined reference to `PyFloat_FromDouble' /tmp/cc3c2Xz6.o(.text+0x1b7b): undefined reference to `PyInt_FromLong' /tmp/cc3c2Xz6.o(.text+0x1b8d): undefined reference to `PyInt_FromLong' /tmp/cc3c2Xz6.o(.text+0x1bba): undefined reference to `PyString_FromStringAndSize' /tmp/cc3c2Xz6.o(.text+0x1bc3): undefined reference to `dbiMakeRaw' /tmp/cc3c2Xz6.o(.text+0x1bce): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x1bd3): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `processOutput': /tmp/cc3c2Xz6.o(.text+0x1bf0): undefined reference to `PyTuple_New' /tmp/cc3c2Xz6.o(.text+0x1c38): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `ifxdbCurFetchOne': /tmp/cc3c2Xz6.o(.text+0x1cb7): undefined reference to `PyEval_SaveThread' /tmp/cc3c2Xz6.o(.text+0x1cf8): undefined reference to `PyEval_RestoreThread' /tmp/cc3c2Xz6.o(.text+0x1d20): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x1d25): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `ifxdbFetchCounted': /tmp/cc3c2Xz6.o(.text+0x1d88): undefined reference to `PyList_New' /tmp/cc3c2Xz6.o(.text+0x1df3): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x1e2e): undefined reference to `PyList_Append' /tmp/cc3c2Xz6.o: In function `ifxdbCurFetchMany': /tmp/cc3c2Xz6.o(.text+0x1ed5): undefined reference to `PyArg_ParseTuple' /tmp/cc3c2Xz6.o: In function `ifxdbCurSetInputSizes': /tmp/cc3c2Xz6.o(.text+0x1f29): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x1f2e): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `ifxdbCurSetOutputSize': /tmp/cc3c2Xz6.o(.text+0x1f39): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x1f3e): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o: In function `cursorGetAttr': /tmp/cc3c2Xz6.o(.text+0x1f82): undefined reference to `_Py_NoneStruct' /tmp/cc3c2Xz6.o(.text+0x1f87): more undefined references to `_Py_NoneStruct' follow /tmp/cc3c2Xz6.o: In function `cursorGetAttr': /tmp/cc3c2Xz6.o(.text+0x1fcb): undefined reference to `Py_FindMethod' /tmp/cc3c2Xz6.o: In function `ifxdbLogon': /tmp/cc3c2Xz6.o(.text+0x1ff5): undefined reference to `PyArg_ParseTuple' /tmp/cc3c2Xz6.o(.text+0x2022): undefined reference to `PyObject_Init' /tmp/cc3c2Xz6.o(.text+0x205a): undefined reference to `PyEval_SaveThread' /tmp/cc3c2Xz6.o(.text+0x2083): undefined reference to `PyEval_RestoreThread' /tmp/cc3c2Xz6.o: In function `init_informixdb': /tmp/cc3c2Xz6.o(.text+0x214d): undefined reference to `Py_InitModule4' /tmp/cc3c2Xz6.o(.text+0x2167): undefined reference to `Py_BuildValue' /tmp/cc3c2Xz6.o(.text+0x2187): undefined reference to `PyModule_GetDict' /tmp/cc3c2Xz6.o(.text+0x2192): undefined reference to `PyDict_SetItemString' /tmp/cc3c2Xz6.o(.text+0x21cc): undefined reference to `initdbi' /tmp/cc3c2Xz6.o(.data+0x24): undefined reference to `PyType_Type' /tmp/cc3c2Xz6.o(.data+0xe4): undefined reference to `PyType_Type' collect2: ld returned 1 exit status What's wrong with this ? Thanks From jeffh at activestate.com Tue Sep 9 11:33:28 2003 From: jeffh at activestate.com (Jeff Hobbs) Date: Tue, 09 Sep 2003 15:33:28 GMT Subject: Image on disabled button In-Reply-To: <1062436629.69505.0@dyke.uk.clara.net> References: <1062436629.69505.0@dyke.uk.clara.net> Message-ID: Richard Townsend wrote: > Is there a known problem with images on disabled buttons on Tk8.4.4 ? > > If I create a button widget using a bitmap as the image and make the button > disabled, not all of the image becomes stippled. The 3 left hand columns of > pixels and the bottom 3 rows of pixels are left unchanged. This is most > obvious if you use a black square as the bitmap. > > If I run the same application using Tk8.3.4 this doesn't happen - the > stipple is applied to the whole image. > > I am using Python2.3 + Tkinter to test this. Do you have a sample bitmap and code snipper (Tcl/Tk or Tkinter) that one can repro this with? There were some fixes that went in for compound buttons (those that display both image and text), but I don't think anything changed for regular bitmaps. -- Jeff Hobbs The Tcl Guy Senior Developer http://www.ActiveState.com/ Tcl Support and Productivity Solutions From graham at rockcons.co.uk Fri Sep 12 08:48:12 2003 From: graham at rockcons.co.uk (Graham Nicholls) Date: Fri, 12 Sep 2003 13:48:12 +0100 Subject: list to string References: Message-ID: <9gj8b.7030$YL.2741@news-binary.blueyonder.co.uk> Gon?alo Rodrigues wrote: > On Thu, 11 Sep 2003 23:07:38 +0100, Graham Nicholls > wrote: > >>Hi. Sorry if this is really dim, but I'm trying to do something like: >> >>main (args): >> fhand=open(args[1:],"r+") >> > > args[1:] is a slice. So if args is a list, args[1:] is a list, if it's > a string, it's a string, etc... open expects a string -- as you > probably have already figured out. > >>and get an error that open is expecting a string not a list. >> > > So either you are passing the wrong argument: e.g. a list instead of a > string, or then, if you do want to pass a list then you have to change > your code. But now the course to follow depends on what you want to > do. So you have to explain a little more. > > With my best regards, > G. Rodrigues Thanks all - I knew it was something stupid. These days I don't get to do enough programming, so I tend to make silly mistakes like this one - clearly I wanted something like: fhand=open(argv[1],"rw") So thanks again. Graham -- #include From axel at pizza.home.kosnet.com Thu Sep 18 10:51:40 2003 From: axel at pizza.home.kosnet.com (Axel Straschil) Date: Thu, 18 Sep 2003 16:51:40 +0200 Subject: How to inheritance overwrite non virtual? Message-ID: Hi! I've got an class with a couple of depending methods. I want to inheritance and create a new class where just one method ist overwritten. My problem: When python is executing the mother-method, not the depending mother-method is taken, it take the method of the chield. In my example, i want that K2.bestCaptionlong() returns the same as KObject.bestCaptionlong() - no way! I've tryed (in K2) something like: def bestCaptionlong(self): return KObject().bestCaptionlong() which I expected to be like KObject::bestCaptionlong() in C++, but it doesn't work ;-( Any Idea how to make the mother-class calling her method's? Here is my Example: class KObject: def __init__(self): self._label=None self._caption=None self._captionlong=None def __str__(self): return ( "label: [%s], %s, (%s)\n"+ "caption: [%s], %s, (%s)\n"+ "captionlong: [%s], %s, (%s)" )%( self._label, self.label(), self.bestLabel(), self._caption, self.caption(), self.bestCaption(), self._captionlong, self.captionlong(), self.bestCaptionlong() ) def label(self): return self._label def caption(self): return self._caption def captionlong(self): return self._captionlong def bestLabel(self): return self.label() def bestCaption(self): if self.caption() is not None: return self.caption() else: return self.bestLabel() def bestCaptionlong(self): if self.captionlong() is not None: return self.captionlong() else: return self.bestCaption() class K2(KObject): def bestCaption(self): return "Overwritten" k = KObject() k._label='x' k2 = K2() k2._label='x' print k print k2 Thanks, AXEL. From tim at remove_if_not_spam.digitig.co.uk Tue Sep 23 10:19:12 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Tue, 23 Sep 2003 15:19:12 +0100 Subject: Thoughts on PEP315 References: Message-ID: On Tue, 23 Sep 2003 04:39:14 +0100, Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote: >On Mon, 22 Sep 2003 21:47:05 -0400, "John Roth" > wrote: >>do: >> bibbity >> bobbity >> boo >> while condition # note the lack of a colon! > >Yuck!!! > >This is really no different to the following, which is quoted in the >PEP as something to move away from... > > while True : > ... > if condition : break > ... > >The fundamental problem is that the exit point is not obvious because >it is 'hidden' in the detail of the loop - it is a statement within >the loop body instead of being lexically a part of the loop. It is very different indeed. In the second case stuff can go after the "if condition: break", so the terminating condition is potentially buried in the surrounding code. On my reading of John's proposal nothing can go after the "while condition", so the end is clearly marked in the Python way by the indentation dropping back a level. What I /don't/ like about it is the overloading of the "while" keyword. I would much sooner reverse the condition and use "until", though I realise the back-compatibility issues of introducing new keywords. From aahz at pythoncraft.com Sat Sep 6 11:00:05 2003 From: aahz at pythoncraft.com (Aahz) Date: 6 Sep 2003 11:00:05 -0400 Subject: OT: best book in years References: <3F5891C8.A7DD1A20@hotmail.com> Message-ID: In article <3F5891C8.A7DD1A20 at hotmail.com>, Alan Kennedy wrote: > >On a lighter note, a fantastic book that I really enjoyed reading (for >leisure) was > >Kil'n People, by David Brin. >http://www.amazon.co.uk/exec/obidos/tg/used/-/1841491381/ >It's nothing less than a masterpiece of modern sci-fi. IMHO :-) Ugh. It's not a bad book, but while I like David Brin in general, his quality has slipped in recent years and I'd recommend something else, depending on the taste of the reader: Military SF: David Weber (start with _On Basilisk Station_) or Lois McMaster Bujold (start with _Shards of Honor_, but don't read _Barrayar_ yet if you pick up the _Cordelia's Honor_ omnibus). Social SF: anything by Ursual K. LeGuin, _Courtship Rite_ by Donald Kingsbury General SF: _In Conquest Born_ by C.S. Friedman; _Sundiver_, by David Brin; _Pride of Chanur_, C.J. Cherryh; _The Mote in God's Eye_, Larry Niven & Jerry Pournelle Fantasy: _Godstalk_ by P.C. Hodgell (available in the omnibus _Dark of the Gods_) High fantasy: _Riddlemaster of Hed_ by Patricia McKillip These are just a few that I pulled up with a couple of minutes thought; I've got many, many more. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From ajsiegel at optonline.net Thu Sep 4 23:17:43 2003 From: ajsiegel at optonline.net (Arthur) Date: Thu, 04 Sep 2003 23:17:43 -0400 Subject: Open Source leader? (was Re: Celebrity advice) Message-ID: <007b01c3735c$481c3720$0c02a8c0@Arts> >Come on guys, no fighting! >Would it help if we all just agreed that you're both a couple of assholes >and get it over with? ;-) I disagree! What was the question? Art From lupan at zamek.gda.pl Mon Sep 22 15:34:41 2003 From: lupan at zamek.gda.pl (Lukasz Pankowski) Date: Mon, 22 Sep 2003 21:34:41 +0200 Subject: Trouble with wxListCtrl References: <49c4d036.0309220953.29b6fd1e@posting.google.com> Message-ID: <874qz41usu.fsf@psi.lupan.zamek.gda.pl> pkbf-tspx at dea.spamcon.org (chauhan) writes: > I am also having problem with statement > self.list.GetItemText(self.currentItem). The statement > self.currentItem gives the current selected item position on listctrl > this statement works fine in wxPanel (demo example wxlistctrl in > wxPython) and not with > wxFrame which I am using now as I want menubar in my application. Can > some body tell me how to get the current selected items position in > wxListCtrl with wxFrame? Same kind of problem with wxPoint(self.x, > self.y) but I can use wxGetMousePosition(). > Hi, wxPanel or wxFrame has nothing to do with self.currentItem, this attribute is set to 0 in TestListCtrlPanel.PopulateList in mentioned example, they register a handler for item selection EVT_LIST_ITEM_SELECTED(self, tID, self.OnItemSelected) and in this hanler they set it to currently selected item: def OnItemSelected(self, event): ##print event.GetItem().GetTextColour() self.currentItem = event.m_itemIndex # [...] This method tracks user selection, the other way is to find the selected item when you need it: currentItem = self.list.GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED) this finds first selected item (first after -1). -- =*= Lukasz Pankowski =*= From ask at me.com Tue Sep 30 13:48:46 2003 From: ask at me.com (Greg Krohn) Date: Tue, 30 Sep 2003 17:48:46 GMT Subject: xml.dom.minidom question References: <3f79ad4b$0$10696$ba620e4c@reader2.news.skynet.be> Message-ID: <2mjeb.10237$NX3.9179@newsread3.news.pas.earthlink.net> "Geiregat Jonas" wrote in message news:3f79ad4b$0$10696$ba620e4c at reader2.news.skynet.be... > I'm using xml.dom.minidom, I get some data by using > obj.getElementsByTagName("name")[0] then I have an object, but how can I > get the data between the tags ? I could do .toxml() and then strip it > away. But is there a better way maybe a function made for it ? > Also is it possible using the xml.dom.minidom module to create modify an > xml file ? Given Greg, 'Greg' is considered an element inside the 'name' element. So, all you have to do is go one level of elements deeper. myname = obj.getElementsByTagName("name")[0].childNodes[0].data greg From guettli at thomas-guettler.de Wed Sep 10 09:54:36 2003 From: guettli at thomas-guettler.de (Thomas Guetttler) Date: Wed, 10 Sep 2003 15:54:36 +0200 Subject: xml.sax: Raising Exception with line number of xml source References: Message-ID: Am Mon, 08 Sep 2003 17:08:56 +0200 schrieb Thomas Guetttler: > Hi! > > How can I raise an exception while parsing with sax, > which contains the current line in the xml-file? > > I want to create an message like this: > test.xml: Line: 100, Col: 20: not allowed in > > I have the filename in my content handler. I just need > the line und column number. Found it myself: in e.g. startElement() of MyContentHandler: self._locator.getLineNumber() thomas From mpeuser at web.de Tue Sep 2 14:40:42 2003 From: mpeuser at web.de (Michael Peuser) Date: Tue, 2 Sep 2003 20:40:42 +0200 Subject: Polymorphism the Python way References: Message-ID: "Bertel Lund Hansen" schrieb im Newsbeitrag news:js99lvguv5vdvmmjfpdmgmo5dnq5akttfb at news.stofanet.dk... > Daniel Klein skrev: > > >It's not a problem really. I just thought there would be a better, > >more elegant way to achieve polymorphism without using getters. > > A note on words: > > If a class operates with for instance a bullet, then derived > classes thereof may operate with a metal bullet, a rubber bullet, > a grenade or a missile. They all operate as bullets, and the fact > that the same object can be instantiated as many different > things, is called polymorphism. "Poly morph" = "many shaped". > > "Encapsulation" is the word that describes the effort(s) to make > it impossible for the user of a module to access the attributes > (and hidden methods) directly and only allow him to do it through > public methods with build-in check so that no disasters occur. > There is another term: "overloading" and I put the OP's question in that drawer. But I have lerned now, that "overloading" can be catalogued as "ad-hoc-polymorphism" whereas the situation when applying a method of a base class to an instance of a derived class is called "universal polymorphism" ;-) Kindly Michael P From robin at jessikat.fsnet.co.uk Mon Sep 29 06:41:22 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 29 Sep 2003 11:41:22 +0100 Subject: extension call backs and the GIL Message-ID: I'm trying to better my understanding of multithreading. I believe a thread that calls an extension must have the GIL. What happens if the extension then calls back into Python? Can a function or method somehow 'belong' to a different thread? My understanding was that things should be OK provided the extension code doesn't mess with the GIL (which it doesn't). I'm asking because the ReportLab tool kit contains an accelerator for a stringWidth function that relies on a callback to fill in some global data upon demand. A user reports thread problems when using the accelerator. -- Robin Becker From just at xs4all.nl Tue Sep 9 07:42:02 2003 From: just at xs4all.nl (Just) Date: Tue, 09 Sep 2003 13:42:02 +0200 Subject: MacOS/NeXTStep propert list parsing? References: <57f2d810.0309080440.21eae97a@posting.google.com> Message-ID: In article <57f2d810.0309080440.21eae97a at posting.google.com>, lars_news at larsshack.org (Lars Kellogg-Stedman) wrote: > I've been trying to find a Python module for parsing the non-XML > PropertList format used in MacOS X (this is what Apple's docs refer to > as "ASCII format" property lists). > > I've sound one or two parsers for the XML format, but nothing that > parses the legacy format. I was hoping someone here had written (or > was aware of) a parser for the older style. If you're only running this on MacOSX, then look at PyObjC, I'm pretty sure Cocoa itself can parse these files. Just From guineapig at pi.be Thu Sep 4 07:06:44 2003 From: guineapig at pi.be (Tom Van den Brandt) Date: Thu, 04 Sep 2003 13:06:44 +0200 Subject: pyQT pushButton References: <8765kaox6q.fsf@pobox.com> Message-ID: John J. Lee wrote: > Tom Van den Brandt writes: > >> Is there anyone using pyQt who can tell me if I can set/change the >> internal >> id of a pushbutton myself ? I can't find anything in the docs... > > What internal id? I don't remember one. What problem are you trying > to solve? > > > John Every button within a buttongroup gets a buttongroupid. That way if a button is clicked, you can know wich button in the group it was... Problem is solved now, I could simply set the id's with qtdesigner. That was something I overlooked. Tnx, -- Tom Van den Brandt I try... From david at fielden.com.au Mon Sep 1 20:17:02 2003 From: david at fielden.com.au (DG) Date: Tue, 2 Sep 2003 10:17:02 +1000 Subject: just a beep In-Reply-To: Message-ID: <000701c370e7$892ed550$5401a8c0@borg.fielden.com.au> print chr(7) :) > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Leo > Sent: Tuesday, 2 September 2003 10:04 AM > To: python-list at python.org > Subject: just a beep > > > hi there > > i want python to do a beep. > > in the docu i found in tkinter the method > bell() > but the script: > import Tkinter > Tkinter.bell() > gives the error: > AttributeError: 'module' object has no attribute 'bell' > > so how can i make python beep? (maybe even without the > tkinter overhead?) > > cheers, leo From ia4598 at fh-wedel.de Fri Sep 19 04:52:26 2003 From: ia4598 at fh-wedel.de (Masiar Farahani) Date: Fri, 19 Sep 2003 10:52:26 +0200 Subject: PpythonWin: Unix File Mode Message-ID: Hi, Is there a option in PythonWin to write files in unix file mode? Regards Masiar From eppstein at ics.uci.edu Mon Sep 22 19:35:39 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 22 Sep 2003 16:35:39 -0700 Subject: Slicing vs .startswith References: <3F6F12A1.3010702@bu.edu> <6e7b9822.0309221439.6dea760e@posting.google.com> <3F6F8306.1ABCC6D@engcorp.com> Message-ID: In article <3F6F8306.1ABCC6D at engcorp.com>, Peter Hansen wrote: > Paul wrote: > > > > However, what if you don't want case sensitivity? For example, to > > check if a file is a jpg, I do name[-3:].lower() == 'jpg'. This will > > work with both foo.jpg and foo.JPG. > > > > Is this slower than name.lower().endswith('jpg')? Is there a better > > solution altogether? > > Yes, of course. :-) > > import os > if os.path.splitext(name)[1].lower() == 'jpg': > pass > > That also handles the problem with files named "ThisFileIs.NotAjpg" > being mistreated, as the other solutions do. ;-) I was about to post the same answer. One minor nit, though: it should be os.path.splitext(name)[1].lower() == '.jpg' It may be a little longer than the other solutions, but it expresses the meaning more clearly. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From Huzzah! at Huzzah.com Thu Sep 18 06:58:44 2003 From: Huzzah! at Huzzah.com (Todd Stephens) Date: Thu, 18 Sep 2003 10:58:44 GMT Subject: audio module References: <9bP9b.71118$Mb2.2369961@twister.tampabay.rr.com> Message-ID: Joe Francia wrote in article : > Todd Stephens wrote: >> Is there such a module containing audio tools? I am looking specifically >> for tools to manipulate ogg-vorbis and convert other formats (mp3, wav) >> to ogg. >> > > Here are some Ogg Vorbis bindings for Python: > > http://www.andrewchatham.com/pyogg/ Excellent. Thanks to everyone that responded. Honestly I was not sure if there was going to be anything out there for this. I think I can work with what I have been shown here. Thanks again. -- Todd Stephens ICQ# 3150790 "A witty saying proves nothing." -Voltaire From skip at pobox.com Wed Sep 3 15:40:10 2003 From: skip at pobox.com (Skip Montanaro) Date: 3 Sep 2003 12:40:10 -0700 Subject: Quickie mail.python.org status Message-ID: <727daa7e.0309031140.1af820b2@posting.google.com> (Posted via Google so some fraction of the c.l.py community sees it. :-) I noticed that python-related mail has been at best trickling in today, so took a quick peek at mail.python.org. Since 4am today exim has rejected over 15,000 messages because they contained executable attachments or suspicious (sobig-style) subjects. I'm sure that's nothing compared to sites like SourceForge or AOL, but it conspires to keep useful mail from flowing through that machine. They said it was going to be bad after everyone returned from the long holiday and late-summer vacations. I guess they were right... Skip From tjreedy at udel.edu Sun Sep 7 12:59:52 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 7 Sep 2003 12:59:52 -0400 Subject: Redesign of Python site References: Message-ID: "Aahz" wrote in message news:bjfm7k$fi1$1 at panix2.panix.com... > Speaking as the champion of Lynx, I absolutely agree. ;-) Don't worry, > I'll veto anything that doesn't have excellent readability, though I > don't know to what extent I personally will check against browsers other > than Lynx and Opera. Email me a URL of a serious proposal and I will view with IE and reply with comment re readability. Or just post and let several people test. Terry J. Reedy From max at alcyone.com Sun Sep 7 15:51:45 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 07 Sep 2003 12:51:45 -0700 Subject: Comments on Python Redesign References: Message-ID: <3F5B8C51.6462BC38@alcyone.com> Tim Parkin wrote: > Perhaps the people who have commented on the site should realise it's > a > proposal and a work in progress. Could someone remind me what need there is for a redesign in the first place? Of all the Python-related efforts that one could put time into, this seems like one of the least useful. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Then you give me that Judas Kiss / Could you hurt me more than this \__/ Lamya From jjl at pobox.com Tue Sep 30 07:58:35 2003 From: jjl at pobox.com (John J. Lee) Date: 30 Sep 2003 12:58:35 +0100 Subject: python, vtk, C++ References: Message-ID: <87d6dicwt0.fsf@pobox.com> "Yi-Yu Chou" writes: > I want to use python as my GUI to load a 3D volume (vtkImageData), > and use a pointer to pass this 3D image to my own C++ class. > My question is I don't know how to communicate between python and C++. > Any suggestion would be appreciated. Google. John From skip at pobox.com Thu Sep 4 14:18:28 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 4 Sep 2003 13:18:28 -0500 Subject: Zope mailing lists dead ? In-Reply-To: References: Message-ID: <16215.33268.31710.220181@montanaro.dyndns.org> >> I didn't receive anything from the various Zope mailing lists I >> should receive. aahz> mail.python.org is currently not processing mail; dunno whether aahz> it's related. It was. mail.python.org == mail.zope.org. Barry Warsaw, Andrew Kuchling and Jeremy Hylton got things put back together nicely and mail is flowing once again. I kibbitzed. If you run into any of them, they deserve a beer. Skip From Mike at DeleteThis.Geary.com Mon Sep 8 03:44:34 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 8 Sep 2003 00:44:34 -0700 Subject: Is there a unicode EOF mark like DOS ascii ctl-z or unix crl-d ? References: Message-ID: Martin v. L?wis wrote: > No, there is no need to have one (neither is there a need to have one > for plain ASCII files): The end-of-file is when the file ends. Most > operating systems support a notion of a "file size", and the file ends > when file-size bytes have been consumed. > > Why Microsoft decided to use ctr-z in text files is beyond me, it does > not fulfil any useful function... It came from CP/M, which believe it or not had *no* way to specify an exact file length. File lengths were measured in sectors, not bytes. So there had to be some way to tell where a text file ended, and CP/M used Ctrl+Z. MS-DOS picked up this convention, although if memory serves it always had exact file lengths even in version 1.0. Nobody uses Ctrl+Z in Windows/DOS text files any more, although I think the COPY command still respects it if you use the /A switch or concatenate files. -Mike From Mike at DeleteThis.Geary.com Thu Sep 25 12:55:13 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Thu, 25 Sep 2003 09:55:13 -0700 Subject: "for" with "else"? References: Message-ID: Mark Jackson wrote: > (This happens to be the *reverse* of what my intuition expects - it > would seem more natural if the syntax meant "do this for loop to > completion, else do this extra stuff," but this is the way it is and > one must simply remember it.) I'm with you there--the use of "else" here has seemed a bit confusing to me. The use case that Alex just posted gave me another way to think about it: for item in allitems: if fraboozable(item): print "first fraboozable item is", item break else: print "Sorry, no item is fraboozable" If I think of the else statement as being related to the if statement inside the loop, then it makes some sense--the else statement is executed when the if statement never comes up true. (It's twisted logic, I know, but at least it helps me keep track of what "else" does here.) -Mike From mpeuser at web.de Thu Sep 4 15:17:24 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 4 Sep 2003 21:17:24 +0200 Subject: Optionmenu. References: Message-ID: "Thor" schrieb im Newsbeitrag news:bj7j47$g5rpn$1 at ID-108351.news.uni-berlin.de... > I have the following function (with some things removed): > > def add_stock(): > stockw=Tk() > stockw.title("New stock solution") > sofl=Frame(stockw) > sofl.pack() > u=StringVar() > u.set("M") > cw=OptionMenu(sofl,u,"M","m","u","v","w") > cw.grid(row=1,column=2) > > but the widget keeps not showing teh selected option. If I fo the same out > of the function it works without problem (with stockw.mainloop()). What am > I missing? Anybody can point me out to the solution/the right webpage? > -- Works fine with Python 2.2 Tk8.3. Though it's looks a little bit funny that you initialize Tk inside the function and that you use a local variable u for your your interface... Kindly Michael P From Mike at DeleteThis.Geary.com Sat Sep 20 18:23:38 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Sat, 20 Sep 2003 15:23:38 -0700 Subject: starship.python.net DNS problems References: Message-ID: Aahz wrote: > There seems to be some kind of problem with Starship's DNS. Until it's > fixed, please use the direct IP of 217.160.219.194 A handy way to fix this is to add this line to your /etc/hosts or %windir%\system32\drivers\etc\hosts file: 217.160.219.194 starship.python.net Of course, you'll need to update this if the IP address changes, but it's a good temporary fix. -Mike From opo at opo.com Tue Sep 30 11:35:53 2003 From: opo at opo.com (franck) Date: Tue, 30 Sep 2003 17:35:53 +0200 Subject: can i implement virtual functions in python ? References: Message-ID: my friend python coder, tell me all function are virtual in python , so... "Prabu" a ?crit dans le message news: e73c30c6.0309300653.24456567 at posting.google.com... > Hi, > > I'm new to python, so excuse me if i'm asking something dumb. > Does python provide a mechanism to implement virtual functions? > Can you please give a code snippet also...:) > Thanx in advance > -Prabu. From dave at pythonapocrypha.com Tue Sep 2 22:09:22 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 2 Sep 2003 20:09:22 -0600 Subject: How to accelerate python application GUI speed In-Reply-To: <43e3984e.0309030532.3fe88bbc@posting.google.com> References: <43e3984e.0309030532.3fe88bbc@posting.google.com> Message-ID: <200309022009.22533.dave@pythonapocrypha.com> On Wednesday 03 September 2003 07:32 am, ulysses wrote: > Hi,all > > I use wxPython make a bittorrent client. I find wxPython very slow and > use many many memory. > When app start, it need 19MB memory. I only use common GUI components. > Python is a really good > programming language. But how to do a small,smart, efficency GUI in > win32,it's a big question. Another option is to use Venster, which is based on ctypes. It'll have a pretty small memory and disk footprint (relatively speaking). It's not as mature or high-level as wx though, but if you're more or less familiar with Win32 GUI programming it's pretty straightforward. If the GUI is pretty simple (a few dialog boxes) then you could just build the dialogs in something like Visual Studio and store them in a resource DLL, and then use Win32 calls to display them. You could also build the dialogs on the fly using Win32 calls (ctypes or win32all, although win32all has some nice helper routines - look at win32ui.CreateDialogIndirect for more info). -Dave From BoteDesSchattens at web.de Wed Sep 17 10:35:40 2003 From: BoteDesSchattens at web.de (Tobias Pfeiffer) Date: 17 Sep 2003 14:35:40 GMT Subject: audio module References: <9bP9b.71118$Mb2.2369961@twister.tampabay.rr.com> Message-ID: Hi! Todd Stephens wrote in news:9bP9b.71118$Mb2.2369961 at twister.tampabay.rr.com: > I am looking > specifically for tools to manipulate ogg-vorbis and convert other > formats (mp3, wav) to ogg. Well. I think at least for converting into ogg, the Python bindings provided on http://www.vorbis.com/download_unix.psp should help (never tried myself). Bye Tobias From cygwin-help at cygwin.com Fri Sep 5 13:08:25 2003 From: cygwin-help at cygwin.com (cygwin-help at cygwin.com) Date: 5 Sep 2003 17:08:25 -0000 Subject: ezmlm response Message-ID: <1062781705.2842.ezmlm@cygwin.com> Hi! This is the ezmlm program. I'm managing the cygwin at cygwin.com mailing list. Acknowledgment: The address python-list at python.org was not on the cygwin mailing list when I received your request and is not a subscriber of this list. If you think you've unsubscribed, but continue to receive mail, please check the following URL for help: http://sources.redhat.com/lists.html#unsubscribe-full-addr-unknown This URL will lead you to information which will enable you to unsubscribe. --- Administrative commands for the cygwin list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: To remove your address from the list, send a message to: Send mail to the following for info and FAQ for this list: Similar addresses exist for the digest list: To get messages 123 through 145 (a maximum of 100 per request), mail: To get an index with subject and author for messages 123-456 , mail: They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: To stop subscription for this address, mail: In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at cygwin-owner at cygwin.com. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: Received: (qmail 2816 invoked from network); 5 Sep 2003 17:08:23 -0000 Received: from unknown (HELO manatee.mojam.com) (199.249.165.175) by sources.redhat.com with SMTP; 5 Sep 2003 17:08:23 -0000 Received: from montanaro.dyndns.org (titan.itcs.northwestern.edu [129.105.214.230]) by manatee.mojam.com (8.11.6/8.11.6) with ESMTP id h85H8GM18777 for ; Fri, 5 Sep 2003 12:08:16 -0500 Received: from montanaro.dyndns.org (localhost [127.0.0.1]) by montanaro.dyndns.org (8.12.9/8.12.2) with ESMTP id h85H8LGp000928 for ; Fri, 5 Sep 2003 12:08:21 -0500 (CDT) Received: by montanaro.dyndns.org (8.12.9/8.12.2/Submit) id h85H8KXw000925; Fri, 5 Sep 2003 12:08:20 -0500 (CDT) From: Skip Montanaro MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: <16216.49924.568426.59717 at montanaro.dyndns.org> Date: Fri, 5 Sep 2003 12:08:20 -0500 To: cygwin-uc.1062780137.kbieladcacinmagdhccn-python-list=python.org at cygwin.com Subject: Re: confirm unsubscribe from cygwin at cygwin.com In-Reply-To: <1062780137.21812.ezmlm at cygwin.com> References: <1062780137.21812.ezmlm at cygwin.com> X-Mailer: VM 7.14 under 21.5 (beta9) "brussels sprouts" XEmacs Lucid Reply-To: skip at pobox.com From manuelbastioni at tin.it Tue Sep 9 14:07:53 2003 From: manuelbastioni at tin.it (Manuel Bastioni) Date: Tue, 09 Sep 2003 18:07:53 GMT Subject: Get the date of last modification of a file References: <3F5CBAB8.F8888E3@engcorp.com> <3F5DBB20.26FE6D30@engcorp.com> Message-ID: > The question was strange, since requiring a true builtin for > this is pointless, so I interpreted the question as though > you were a newbie who didn't use the term "built-in" to mean > what it usually means in Python. I figured you just wanted > to use a module that came with standard Python instead of > requiring a separate download. > > So since you've clarified that, I'll be interested to see the > answer to Erik Max Francis' question, too. :-) I want use only built-in module because I'm writing a python scripts from Blender. To have all standard libs, the Blender user (often not developer) must install the full python distribution, and after must set the python path in Blender. http://www.elysiun.com/forum/viewtopic.php?t=7723 To semplify this, I want use only the built-in function, directly in Blender interpreter. You can see my script here: http://www.dedalo-3d.com/makehuman.html http://www.dedalo-3d.com/disp_en.html Thanks, Manuel PS for Gerhard: >What a stupid thing to say. This is only an automatic message from my antivirus. From hans at zephyrfalcon.org Mon Sep 29 16:47:46 2003 From: hans at zephyrfalcon.org (Hans Nowak) Date: Mon, 29 Sep 2003 16:47:46 -0400 Subject: write to log file In-Reply-To: <3F789981.5060508@zephyrfalcon.org> References: <3F789981.5060508@zephyrfalcon.org> Message-ID: <3F789A72.1000309@zephyrfalcon.org> I wrote: > >>> g = open('c:/temp/test.txt', 'a+r') Then again, using 'a' or 'a+' should work too... -- Hans (hans at zephyrfalcon.org) http://zephyrfalcon.org/ From aahz at pythoncraft.com Mon Sep 29 11:36:03 2003 From: aahz at pythoncraft.com (Aahz) Date: 29 Sep 2003 11:36:03 -0400 Subject: extension call backs and the GIL References: Message-ID: In article , Robin Becker wrote: >In article , Aahz >writes >>In article , >>Robin Becker wrote: >>> >>>I'm trying to better my understanding of multithreading. I believe a >>>thread that calls an extension must have the GIL. What happens if the >>>extension then calls back into Python? Can a function or method somehow >>>'belong' to a different thread? My understanding was that things should >>>be OK provided the extension code doesn't mess with the GIL (which it >>>doesn't). >> >>You need to reacquire the GIL prior to making the callback. > >So does calling an extension release the GIL? I believed the opposite >for some reason. Looks like Bernhard has put you on the right track, but just for the record: calling an extension does not automatically release the GIL; you need to explicitly call the Py_BEGIN_ALLOW_THREADS macro. I was just assuming that because you said "accelerator" you were already releasing the GIL. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "It is easier to optimize correct code than to correct optimized code." --Bill Harlan From davidcfox at post.harvard.edu Thu Sep 4 21:19:58 2003 From: davidcfox at post.harvard.edu (David C. Fox) Date: Fri, 05 Sep 2003 01:19:58 GMT Subject: Selecting elements from a list In-Reply-To: <87y8x4w6ym.fsf@gvdnet.dk> References: <87y8x4w6ym.fsf@gvdnet.dk> Message-ID: <2xR5b.354503$YN5.241285@sccrnsc01> Martin Christensen wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Howdy! > > Suppose I have a list A containing elements that I want to put into > list B if they satisfy some property. The obvious way of doing it > would be, > > B = [] > for i in A: > if A.property(): > B.append(i) > > Now, list comprehensions, map() etc. can make a lot of list operations > easier, but I haven't found a shorter, more elegant way of doing this. > Have I missed something, or will I have to stick to my explicit loops? > > Martin > B = filter(lambda x: x.property(), A) David From rainerd at eldwood.com Sat Sep 27 14:46:22 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 27 Sep 2003 18:46:22 GMT Subject: Now that rexec is gone... References: Message-ID: <2Wkdb.599239$YN5.441191@sccrnsc01> Alex Martelli wrote: > Actually, such a "butchered" Python interpreter might be a fun and > useful project indeed. You would have to add programmable limits on > resource consumptions -- e.g., memory allocatable by the script[s], > time (CPU or maybe elapsed) usable thereby, etc. And you should > rename everything, say to use Qy instead of Py, so that a normal and a > butchered interpreter could easily be embedded in the same program. That might be a useful project, but it also sounds like a lot of work. I don't think I'll be going that route. As it turns out, I can solve my security problem in a different way entirely: by confirming that any Python code I run is from a trusted source. No need to run untrusted code at all. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From link0937 at hotmail.com Mon Sep 22 21:55:16 2003 From: link0937 at hotmail.com (Link) Date: Tue, 23 Sep 2003 09:55:16 +0800 Subject: How can load dll in C? Message-ID: Dear, How is the wonderful PYTHON for me. It attracts me with its additional variety. I am developing in C program as well as first to use C++ with extending & embedding PYTHON. It seems not to easy. What do I mean? See that following steps what I am doing. step 1. Success to make a example.dll with SWIG from MSVC6.0. After, copy this DLL to C:\Python23\Lib. step 2. Getting into Pythinwin to run the following commands. >>> import example >>> c = example.new_Circle() >>> print c _a03f6e01_p_Circle >>> step 3. Making a C file with MSVC6.0 and running. void main() { //initialized the interpreter. Py_Initialize(); // int r0 = PyRun_SimpleString("import example\n"); int r1 = PyRun_SimpleString("c = example.new_Circle()\n"); int r2 = PyRun_SimpleString("print c\n"); //destory the interpreter Py_Finalize(); } The results: 1. See the step2, To make a example.dll from MSV6.0 to be called by PYTHON. Of course, it's OK. 2. See the step3, while running the statement - 'PyRun_SimpleString("import example\n")' missing to load the DLL and always return the value r0 = -1, My quesions are: 1. example.dll can be called on Pythonwin but fail to load by C program. 2. Shall I set the PYTHONPATH while loading the DLL in C program? If YES, How can I do? From rdsteph at earthlink.net Wed Sep 10 22:14:34 2003 From: rdsteph at earthlink.net (Ron Stephens) Date: 10 Sep 2003 19:14:34 -0700 Subject: Learning Python, 2'nd Edition, O'Reilly Message-ID: <8e6e8e5d.0309101814.393a8ed0@posting.google.com> Does anyone know when this is due to be released? I am assuming that this version will cover Python 2.3, and be the first book to fully do so. Ron Stephens From mpeuser at web.de Sat Sep 6 11:01:34 2003 From: mpeuser at web.de (Michael Peuser) Date: Sat, 6 Sep 2003 17:01:34 +0200 Subject: Why python??? References: <87fzjalogu.fsf@pobox.com> <87vfs6unsx.fsf@pobox.com> Message-ID: "John J. Lee" schrieb im Newsbeitrag news:87vfs6unsx.fsf at pobox.com... > "Michael Peuser" writes: > Windows is an esoteric OS? Counted by numbers, the widest spread OS is an endless loop, interrupted by hardware timer interrupts. About 50 billion I should say, but can be much more. There is one on your video card and in your hard disk and even inside your Compact Flash (CF) card. Then come some real proprietary OS. And - granted - there are also some Linux and Windows boxes running. This shifts to more standardisation (VxWorks, QNX embedded Linux,...) as electronic equipment becomes more intelligent (DVD Player e.g) A modern limousine contains about 50 microcontrolles with independant operating systems. > Still, you make an interesting point here: is it the case that more > code is written for hard real-time systems than not? That would > certainly surprise me. Where do you get your data? I am still looking for something traceable. My information is from some diagrams in seminare hand-outs from end of the 90. So they probably come from data of the early 90. They say there are twice as many commercial programmers working in technical (embedded systems) than in administrative programming. Since then there has been have a lot of web programming which was non-existent 10 years ago, but we also have a lot of telecommunication. > > > May be they will be programmed in Python in 20 years, though I do not see > > it. You need a certified compiler, a fail proof and predictable garbage > > collector, and a little bit more. > > Yes. And? We seem not to be communicating here... That is my fault. You are proably thinking of the language as such. I was thinking of its standard implementation as open system with hundreds of more or less mature add-ons [..] > Sorry, I don't quite follow that. How does that relate to the rest of > the paragraph? (There were some mixed threads here, I was ansering as well to some Linux argument....) [...] > > > Python is an order of magnitude easier to learn than C++, but it > > > brings really significant programmer-efficiency benefits. As a > > > result, the argument about training simply doesn't stand up: the costs > > > are lower than the benefits even on a short timescale. > > > > I know this argument well and have repeated it myself in the days of Pascal > > and Algol68. Few have listened..... > Well, they'd be right not to listen if you argued it about Pascal. > There's a real difference in productivity between Pascal and Python. > Pascal doesn't even have built-in garbage collection, for heaven's > sake, which places it much closer to C than to Python in this respect. I said "in the time of Pascal and Algol 68". If you kindly would consult a calender you will find out that had been 35 years ago. Pascal had been designed to not need a garbage collector which was a great issue for Algol68 with its (explicit) heap concept. Some of the first C++ compilers 20 years later were notorious for their never working GC. There are companies still not using C++ for embedded aplication because they mistrust even modern concepts. > > > Programmers are generally not trained in their company, they are hired > > including their special language skills. > > You're begging the question: arguably, that is the mistake of those > hiring. Training (for Python, anyway) will frequently be cheaper than > sticking to, say, C++. Other skills are more important than > pre-existing ability to use a language like Python (though that's > certainly not irrelevant!). > > > [..] > > > > This is an important factor. However all investigations show that > > > > programmer's productivity is an unmeasurable quantity. > > > > > > How would an empirical investigation show such a thing? > > > > Alex gave a hint to a German study. I think he was refering to: > > http://www.ipd.uka.de/~prechelt/Biblio/jccpprtTR.pdf > (That was probably the one I was thinking of in another paragraph in > my reply) I don't see how such a study could show that "programmer's > productivity is an unmeasurable quantity". It's obvious that > variations between individuals make differences due to languages hard > to measure, but that doesn't make it impossible. The study was meant (and shows) that using scripting languages for special projects is advantegeous over using standard languages. It also shows the"productivity" of the (wide range of ) programmers. I will have to look into it again .... ... yes take page 22: Total times of programming: The JAVA programers needed between 3 and 63 hours. This is nothing you can work with when it comes to estimating the costs for your next project. On the other hand it shows that there are some Python programmers who delivered their task much faster. So what? Everyone knows that Python programmers are the better, faster, busier species ;-) This is not a general distrust for statistics (I studied mathematics) but also my personal experience from 30 years of programming. I do not remember who (Dijkstra?) once said: "When a programmer is good he is generally very good, and when he is bad he is generally very bad". But all of them want to earn their money in the software business. Kindly Michael P From CousinStanley at hotmail.com Wed Sep 3 17:37:15 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 3 Sep 2003 14:37:15 -0700 Subject: How to accelerate python application GUI speed References: <43e3984e.0309030532.3fe88bbc@posting.google.com> <87n0dmj82w.fsf@flibuste.net> <877k4q6jj1.fsf@pobox.com> <87ekyxinsx.fsf@flibuste.net> Message-ID: | What is HTA ? Wilk .... HTA ... HTML Application http://msdn.microsoft.com/workshop/author/hta/reference/objects/hta.asp Example containing a bit of VBScript to access some common applications under Windows ... http://fastq.com/~sckitching/HTML/Start_Page.hta -- Cousin Stanley Human Being Phoenix, Arizona From tjreedy at udel.edu Thu Sep 11 16:44:28 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Sep 2003 16:44:28 -0400 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <4cjulvoapgvre33kr76k0d2f4l4l1rltge@4ax.com> <66t0mv410it5ftvjokfpkov0v029trv6lp@4ax.com> Message-ID: "Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:66t0mv410it5ftvjokfpkov0v029trv6lp at 4ax.com... > Actually I'm sick to death of the old 'your just trying to turn Python > into X' argument whenever I suggest that *maybe* Python might learn a > trick from another language. [etc] This seems to be a predictible c.l.py response to proposals. I got similar accusations several years ago, which made me similarly sick, when I proposed the addition of list.pop() (which Guido did, in more generalized form, about a year later). My main objection was/is that expressed by Michael Chermside today: this would complexify a simplicity that I consider a good feature of Python. Reading Bengt Richter's lastest response, also today, I realize that 'ref x' would have to have much the same effect of Lisp's FEXPR defun keyword -- of automatically quoting rather than evaluating args -- although on just one rather than all. Perhaps you should be accused of 'trying to Lispify Python' -- or perhaps not ;-). Terry J. Reedy From skip at pobox.com Thu Sep 11 10:30:59 2003 From: skip at pobox.com (Skip Montanaro) Date: Thu, 11 Sep 2003 09:30:59 -0500 Subject: OT: Americans love their guns In-Reply-To: <000b01c37824$c972de10$3a0ff10c@teaset> References: <16223.15950.299463.959577@montanaro.dyndns.org> <000b01c37824$c972de10$3a0ff10c@teaset> Message-ID: <16224.34595.360519.654147@montanaro.dyndns.org> Al> MY children were taught to handle firearms safely beginning age 5. Al> Are yours? No, we're more intelligent than that. We have no guns in our house. Why is this on c.l.py anyway? Skip From glingl at aon.at Wed Sep 17 17:00:23 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed, 17 Sep 2003 23:00:23 +0200 Subject: None, False, True In-Reply-To: <0KI9b.12967$x21.4828@twister.southeast.rr.com> References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> Message-ID: <3F68CB67.5000409@aon.at> M-a-S schrieb: > Can anybody explain this: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>None = 3 > > :1: SyntaxWarning: assignment to None > Interestingly this doesn't occur in IDLE: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. ... IDLE 1.0 >>> None = 3 SyntaxError: assignment to None (, line 1) >>> print None None In a recent posting to this list I asked how to write-protect names. This seems to be done here with the Name None. But again: how is it done? ---- On the other side the existence and knowledge of the None-object doesn't disappear completely in the plain Python interpreter: >>> None = 3 :1: SyntaxWarning: assignment to None >>> None 3 >>> def f(): ... pass ... >>> print f() None But: >>> def g(): ... return None ... >>> g() 3 So you can use f to restore the value of None (if you happened to forget to save it): >>> None = f() :1: SyntaxWarning: assignment to None >>> None >>> print None None From adalke at mindspring.com Thu Sep 4 17:09:17 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Thu, 04 Sep 2003 21:09:17 GMT Subject: Comparing objects - is there a maximum object? References: <7bdbb1a6.0309041124.6801b755@posting.google.com> Message-ID: <1SN5b.8786$tw6.4739@newsread4.news.pas.earthlink.net> Martin v. L?wis: > The easiest way to produce a maximum object is > > class Max: > def __cmp__(self, other): > return 1 Shouldn't there also be a def __rcmp__(self, other): return -1 ? Andrew dalke at dalkescientific.com From claird at lairds.com Sun Sep 28 08:59:00 2003 From: claird at lairds.com (Cameron Laird) Date: Sun, 28 Sep 2003 12:59:00 -0000 Subject: Access to database other web sites References: <87n0crbi8z.fsf@pobox.com> <87eky2574t.fsf@pobox.com> Message-ID: In article <87eky2574t.fsf at pobox.com>, John J. Lee wrote: . . . >> Complementing that difficulty is the poverty of inference I antici- >> pate you'll be able to ground on what you find there; their commerce has a lot >> more noise than signal, as I see it. > >What do you mean 'their commerce has more noise than signal'? > > >> 'Twould be great, though, for you to >> uncover something real. Good luck. > >What I was wondering was where the sales data are going to come from. . . . That's a typical part. As I understand Jenny, she's going to look at, say, eBay, and correlate "sales" with "price" and "marketing" variables. I apologize for being obscure in abbreviating my judgment that that approach is likely to yield "more noise than signal"; you're quite right for ask- ing what I mean. What I mean by that is that all the variables strike me as poorly replicable, in at least three respects: A. eBay and other operators have an interest in releasing data only as they support their own success, and not for their analytic clarity. Their incentives to categorize and aggregate variables can do no more than to leave the underlying relations unbiased, and that's plenty unlikely. B. I suspect the universes are so small as to provide ittle inferential power. I'm most tentative about this one. I know eBay is big business, but I suspect that looking at any other operation will yield only data from an exceptional period, be- cause the businesses are *not* sustainable. C. Measurements of "marketing effort" and "promotion intensity" and other such quali- tative notions ... well, it sounds ambitious to me. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From jjl at pobox.com Sun Sep 21 16:38:08 2003 From: jjl at pobox.com (John J. Lee) Date: 21 Sep 2003 21:38:08 +0100 Subject: Help me choose a C++ compiler to work with Python References: <616fccba.0309210907.1e35b92d@posting.google.com> Message-ID: <877k416fnz.fsf@pobox.com> "Cy Edmunds" writes: > "rhmd" wrote in message > news:616fccba.0309210907.1e35b92d at posting.google.com... [...] > This one really has me squirming in my seat. C++ isn't a very good language > for learning just a little bit of. Compared to Python I would say the Agreed! But Koenig & Moo's book (Accelerated C++) is the best I've seen for doing that. [...] > I wouldn't choose your C++ compiler for Python compatibility. How good is I don't think that's unreasonable, as long as you're *aware* of all the other issues. Ease of use with standard Python might come out as most important. And on Windows, Python work with MSVC is much less of a pain for most things than gcc (aka mingw). [...] > The .NET compiler has a very good debugger and much better standard > compliance than the old 6.0 compiler, but I haven't used lot of different > recent vintage C++ compilers. What *is* the current position with MSVC 7 and Python? Anyone? I still haven't heard a clear story. John From axel at pizza.home.kosnet.com Thu Sep 18 13:02:01 2003 From: axel at pizza.home.kosnet.com (Axel Straschil) Date: Thu, 18 Sep 2003 19:02:01 +0200 Subject: How to inheritance overwrite non virtual? References: Message-ID: Hello! > What you want seems to be > class KObject: > def bestCaptionlong(self): > # class made explicit to guard against overriding > return KObject.bestCaption(self) > Yes, that behaves the way I excpected, thank's to you and the other for helping me! > Do-nothing accessor methods may be acceptable style in C++ but are > superfluous in Python. I'm afraid I'm still not thinking in python, I'll work on it ;-) Lg, AXEL. From aleax at aleax.it Mon Sep 22 10:46:15 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 14:46:15 GMT Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale related?)) References: Message-ID: Duncan Booth wrote: ... >>> So maybe it's about time to change the sort() method to support a >>> second argument >>> >>> list.sort(compare=None, mapping=None) >>> >>> that, if provided, would perform the DSU magic. Or was that already >>> proposed and rejected? >> >> I have not seen this proposed before, and I'm not very clear on what >> the "compare" and "mapping" arguments are supposed to be in order to >> let you specify any DSU. Basically it seems you would need two >> callables, "decorate" to be called with each item in the list (to >> return for each item the decorated tuple) and "undecorate" to be >> called with each decorated tuple after the sort (to return the item >> for the result). How do you turn that into "compare" and "mapping"? >> >> > You don't need two callables because the sort function would be doing > the decorating, so it knows also how to undecorate. I think the > suggestion is that the mapping argument returns something that can be > compared. > > For example, here is a DSU function that does a not-in-place sort and > takes a suitable mapping argument. Changing it to in-place sort is, > of course, trivial. > >>>> def DSU(aList, aMapping): > newList = [ (aMapping(item), index, item) for (index, item) Ah, I see -- the alleged "mapping" is in fact meant to be a *CALLABLE*, NOT a mapping in the Python sense. Yes, you could get away with just one callable in this way, of course. It also seems to me that shoe-horning that second argument (in practice mutually exclusive with the first one) to the sort method, when there seem to be no real advantages to keeping it a method, is not a great idea. Rather, a new built-in function appears to me to be best here -- something like: def sort(iterable, decorate=None): if decorate is None: aux = [ (item, index, item) for index, item in enumerate(iterable) ] else: aux = [ (decorate(item), index, item) for index, item in enumerate(iterable) ] aux.sort() return [ item for __, __, item in aux ] so as to have no arbitrary constraints on the iterable being a list, or the sort being necessarily in-place, when there is no performance advantage in so doing -- and also serve the frequent need of a non-in-place sort returning the sorted list without any actual need for decoration. E.g., I often use the equivalent of: for key in sort(somesmalldict): print key, somesmalldict[key] and it would be handy to have that little 'sort' function built-in for all such uses. The only downside I can see to this proposal is that Python isn't really all that good at passing the callable decorate argument -- one would end up with a lot of little ad hoc functions, or lambdas, and neither is a great solution. It's the kind of situation where Smalltalk/Ruby shine by letting an arbitrary block of code (albeit one only) be passed into any method (in Ruby, this DSU-sort would probably become a method of the Enumerable "module" [mix-in] -- a rather elegant solution overall, "architecturally" nicer-looking than Python's, although "pragmatically" we're probably abot even). Alex From job at webde-ag.de Wed Sep 17 08:40:52 2003 From: job at webde-ag.de (Joerg Beyer) Date: Wed, 17 Sep 2003 12:40:52 +0000 (UTC) Subject: ANN: script to visualize python profiling data with kcachegrind Message-ID: Dear List Reader, with the kind help of Josef Weidendorfer, I wrote a script to transform the profiling data of the pstats.Stats class to a format that the program kcachegrind could read and visualize. kcachegrind is free software by Josef Weidendorfer, see http://kcachegrind.sourceforge.net . It was developed with the very nice valgrind (see http://developer.kde.org/~sewardj/ ), which is (among other things a C/C++ profiling tool). kcachegrind is the best visualisation of gcc compiled profiling code I have seen yet. With this, one could profile it's python python code and generate the pstats.Stats results, e.g. like that: ------------------------------------------- #!/usr/bin/env python # _*_ coding: latin1 _*_ import hotshot def busy(x): for i in range(x): pass def h(): busy(10) f() def f(): busy(250) def run(): f() h() filename = "pythongrind.prof" prof = hotshot.Profile(filename, lineevents=1) prof.runcall(run) prof.close() ------------------------------------------- When you run this tiny python code, you get the profiling results in "pythongrind.prof". Now you can transform them with hotshot2cachegrind (my script, see below) like this: hotshot2cachegrind -o cachegrind.out.42 pythongrind.prof this will produce the file cachegrind.out.42, the input to kcachegrind. The filename _has_ to be in the format "cachegrind.out."+. now start kcachegrind with this data file as input: kcachegrind cachegrind.out.42 Now a kcachegrind window should open, with the profiling results, like a calltree and a list of costs (how expensive are the functions). For a description of how to interpret this data, please take a look at the kcachegrind documentation, but most of it is very easy and intuitive. The costs are given in "Ticks", which is what hotshot tells me as costs (tdelta of the logread). I am not sure what is the unit of this, could anybody tell me? There may be small mistakes, since I am e.g. not sure where the costs of a call should go: to the calling or the called function. So, python experts are needed to justify these details. Besides this, I was able to find and improve the hot spots in some python sources without big efforts. At least the relative numbers seem right. The script hotshot2cachegrind is in it's early stages, I plan to extend it to display the source line and the associated costs, just like kcachegrind could do with assembler lines. I believe in "release early, release often", so please take a look at it, profile some of you code an tell me, if the results are resonable. Josef and I plan to make the current version of the hotshot2cachegrind script available from http://kcachegrind.sourceforge.net/ Until that, I append the python code to this posting. I am not aware of other visualisations of python profiling results, so links are welcome. Comments are welcome. Joerg below is hotshot2cachegrind: ---------------------------------------------------------------------- #!/usr/bin/env python # _*_ coding: latin1 _*_ # # Copyright (c) 2003 by WEB.DE, Karlsruhe # Autor: J?rg Beyer # # hotshot2cachegrind 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, version 2. # # 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; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # # This script transforms the pstat output of the hotshot # python profiler into the input of kcachegrind. # # example usage: # modify you python script to run this code: # # import hotshot # filename = "pythongrind.prof" # prof = hotshot.Profile(filename, lineevents=1) # prof.runcall(run) # assuming that "run" should be called. # prof.close() # # it will run the "run"-method under profiling and write # the results in a file, called "pythongrind.prof". # # then call this script: # hotshot2cachegrind -o # or here: # hotshot2cachegrind cachegrind.out.0 pythongrind.prof # # then call kcachegrind: # kcachegrind cachegrind.out.0 # # import os, sys from hotshot import stats,log import os.path what2text = { log.WHAT_ADD_INFO : "ADD_INFO", log.WHAT_DEFINE_FUNC : "DEFINE_FUNC", log.WHAT_DEFINE_FILE : "DEFINE_FILE", log.WHAT_LINENO : "LINENO", log.WHAT_EXIT : "EXIT", log.WHAT_ENTER : "ENTER"} # a pseudo caller on the caller stack. This represents # the Python interpreter that executes the given python # code. root_caller = ("PythonInterpreter",0,"execute") class Stack: """A tiny Stack implementation, based on python lists""" def __init__(self): self.stack = [] def push(self, elem): """put something on the stack""" self.stack = [elem] + self.stack def pop(self): """get the head element of the stack and remove it from teh stack""" head = self.stack[0] self.stack = self.stack[1:] return head def top(self): """get the head element of the stack, stack is unchanged.""" head = self.stack[0] return head def size(self): """ return how many elements the stack has""" return len(self.stack) def do_calls(output, current_function, current_source_file, costs): """print, what kcachegrind needs for a function call""" output.write("cfn=%s\n" % current_function) output.write("calls=1\n0 %d\n" % costs) output.write("fn=%s\n" % current_function) def return_from_call(caller_stack, call_dict, current_cost): """return from a function call remove the function from the caller stack, add the costs to the calling function. """ called, cost_of_left_funct = caller_stack.pop() caller, caller_cost = caller_stack.pop() #print "pop: caller: %s size: %d" % (caller, caller_stack.size()) per_file_dict = call_dict.get(caller[0], {}) per_caller_dict = per_file_dict.get(caller[2], {}) call_cost, count = per_caller_dict.get(called, (0, 0)) cost_of_left_funct += current_cost per_caller_dict[called] = (call_cost+cost_of_left_funct, count + 1) per_file_dict[caller[2]] = per_caller_dict call_dict[caller[0]] = per_file_dict #print "push caller %s, size: %d : %s" % (caller, caller_stack.size(), (caller,caller_cost + cost_of_left_funct)) caller_stack.push((caller,caller_cost + cost_of_left_funct)) def convertProfFiles(output, inputfilenames): """convert all the given input files into one kcachegrind input file. """ call_dict = {} cost_per_line = {} cost_per_function = {} caller_stack = Stack() caller_stack.push((root_caller, 0)) total_cost = 0 i = 0 number_of_files = len(inputfilenames) for inputfilename in inputfilenames: i += 1 sys.stdout.write("lese File %d von %d, costs: %s \r" % (i, number_of_files, total_cost)) sys.stdout.flush() cost = convertProfFile(inputfilename, caller_stack, call_dict, cost_per_line, cost_per_function) total_cost += cost print print "total_cost:",total_cost dumpResults(output, call_dict, total_cost, cost_per_line, cost_per_function) def convertProfFile(inputfilename, caller_stack, call_dict, cost_per_line, cost_per_function): """convert a single input file into one kcachegrind data. """ item_counter = 0 total_cost = 0 try: logreader = log.LogReader(inputfilename) current_cost = 0 last_file = None last_func = None for item in logreader: item_counter += 1 what, pos ,tdelta = item (file, lineno, func) = pos #line = "%s %s %d %s %d" % (what2text[what], file, lineno, func, tdelta) #print line #if what == log.WHAT_LINENO: if what == log.WHAT_ENTER: caller_stack.push((pos, tdelta)) elif what == log.WHAT_EXIT: return_from_call(caller_stack, call_dict, tdelta) else: # add the current cost to the current function p, c = caller_stack.pop() c += tdelta caller_stack.push((p,c)) cost = cost_per_line.get(pos, 0) #print "buche tdelta: %d auf pos: %s -> %d" % (tdelta, pos, cost + tdelta) cost_per_line[pos] = cost + tdelta total_cost += tdelta # I have no idea, why sometimes the stack is not empty - we # have to rewind the stack to get 100% for the root_caller while caller_stack.size() > 1: return_from_call(caller_stack, call_dict, 0) except IOError: print "could not open inputfile '%s', ignore this." % inputfilename except EOFError, m: print "item_counter: %d %s" % (item_counter, m) return total_cost def pretty_name(file, function): #pfile = os.path.splitext(os.path.basename(file)) [0] return "%s [%s]" % (function, file) #return "%s_%s" % (pfile, function) def write_fn(output, file, function): output.write("fn=%s\n" % pretty_name(file, function)) def write_fl(output, file, function): output.write("fl=%s\n" % pretty_name(file, function)) def write_cfn(output, file, function): output.write("cfn=%s\n" % pretty_name(file, function)) def dumpResults(output, call_dict, total_cost, cost_per_line, cost_per_function): """write the collected results in the format kcachegrind could read. """ # the intro output.write("events: Tick\n") output.write("summary: %d\n" % total_cost) output.write("cmd: your python script\n") output.write("\n") last_func = None last_file = None # now the costs per line for pos in cost_per_line.keys(): output.write("ob=%s\n" % pos[0]) write_fn(output, pos[0], pos[2]) # cost line output.write("%d %d\n" % (pos[1], cost_per_line[pos])) output.write("\n\n") # now the function calls. For each caller all the called # functions and their costs are written. for file in call_dict.keys(): per_file_dict = call_dict[file] output.write("ob=%s\n" % file) #print "file %s -> %s" % (file, per_file_dict) for caller in per_file_dict.keys(): write_fn(output, file ,caller) write_fl(output, file ,caller) per_caller_dict = per_file_dict[caller] #print "caller %s -> %s" % (caller, per_caller_dict) for called in per_caller_dict.keys(): output.write("cob=%s\n\ncfl=%s\n" % (called[0], called[0])) write_cfn(output, called[0], called[2]) cost, count = per_caller_dict[called] # detect recursion if file == called[0] and caller == called[2]: output.write("r"); output.write("calls=%d\n%d %d\n" % (count, called[1], cost)) #output.write("calls=%d\n%d %d\n" % (count, called[1], cost)) def run_without_optik(): """parse the options without optik, use sys.argv""" if len(sys.argv) < 4 or sys.argv[1] != "-o" : print "usage: hotshot2cachegrind -o outputfile in1 [in2 [in3 [...]]]" return outputfilename = sys.argv[2] try: output = file(outputfilename, "w") args = sys.argv[3:] convertProfFiles(output, args) output.close() except IOError: print "could not open '%s' for writing." % outputfilename def run_with_optik(): """parse the options with optik""" parser = OptionParser() parser.add_option("-o", "--output", action="store", type="string", dest="outputfilename", help="write output into FILE") output = sys.stdout close_output = 0 (options, args) = parser.parse_args() try: if options.outputfilename and options.outputfilename != "-": output = file(options.outputfilename, "w") close_output = 1 except IOError: print "could not open '%s' for writing." % options.outputfilename if output: convertProfFiles(output, args) if close_output: output.close() # check if optik is available. try: from optik import OptionParser run = run_with_optik except ImportError: run = run_without_optik if __name__ == "__main__": try: run() except KeyboardInterrupt: pass -- Simplicity is prerequisite for reliability. Edsger W. Dijkstra From missive at frontiernet.net Wed Sep 24 21:13:02 2003 From: missive at frontiernet.net (Lee Harr) Date: Thu, 25 Sep 2003 01:13:02 GMT Subject: What is the meaning of the astarisk in Python References: <3f6ce54f$0$10962$fa0fcedb@lovejoy.zen.co.uk> Message-ID: In article <3f6ce54f$0$10962$fa0fcedb at lovejoy.zen.co.uk>, John Dean wrote: > Hi > Below is a line taken from Andy Dustman's MySQLdb module: > def Connect(*args, **kwargs): > > I would be grateful if somebody explain the meaning of the astarisks, since > I was under the impression that pointers are not used in Python and the > above look very must like pointers to me > http://python.org/doc/current/tut/node6.html#SECTION006600000000000000000 http://python.org/doc/current/tut/node6.html#SECTION006720000000000000000 http://python.org/doc/current/tut/node6.html#SECTION006730000000000000000 From whiteywidow at yahoo.com Sat Sep 6 21:37:14 2003 From: whiteywidow at yahoo.com (rt lange) Date: Sun, 07 Sep 2003 01:37:14 GMT Subject: Redesign of Python site Message-ID: came across this page searching feedster. dont know whether this is the official resdesign or just a proposal; but the mockups look very nice. http://www.pollenation.net/journal/index.php?p=37&c=1 main page mockup: http://www.pollenation.net/assets/public/python-main.html interior page: http://www.pollenation.net/assets/public/python-interior.html From plb at iotk.com Thu Sep 18 14:00:30 2003 From: plb at iotk.com (Peter L. Buschman) Date: 18 Sep 2003 11:00:30 -0700 Subject: Join equivalent for tuples of non-strings? Message-ID: <1a884f4a.0309181000.749eb8a1@posting.google.com> I'm trying to think in Python, but am stumped here... What is the equivalent for the following if you are dealing with a tuple of non-strings? >>> import string >>> foo = ( '1', '2', '3' ) >>> string.join( foo, '.' ) '1.2.3' With a tuple of integers, this fails with a traceback as below: >>> bar = ( 1, 2, 3 ) >>> string.join( bar, '.' ) Traceback (most recent call last): File "", line 1, in -toplevel- string.join( bar, '.' ) File "C:\Python23\Lib\string.py", line 135, in join return sep.join(words) TypeError: sequence item 0: expected string, int found >>> --PLB From tjreedy at udel.edu Sun Sep 7 16:21:26 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 7 Sep 2003 16:21:26 -0400 Subject: Testing References: Message-ID: "Andy" wrote in message news:pan.2003.09.07.18.08.26.970255 at onetel.com... > This is not a post it is a test - please ignore Test posts should generally go to misc.test, which exists just for this purpose. From mack at incise.org Thu Sep 4 01:11:11 2003 From: mack at incise.org (Nick Welch) Date: Thu, 4 Sep 2003 00:11:11 -0500 Subject: strings In-Reply-To: References: Message-ID: <20030904051111.GI16821@incise.org> On Thu, Sep 04, 2003 at 04:18:38AM +0000, Scribe wrote: > if it is a decimal I want to return the number without the commer any > others return 0. "commer"? str.isdigit() should do most of it for you. def foo(mystr): if mystr.isdigit(): return "the number without the commer (??) :)" else: return 0 -- Nick Welch aka mackstann | mack @ incise.org | http://incise.org Penguin Trivia #46: Animals who are not penguins can only wish they were. -- Chicago Reader 10/15/82 From bokr at oz.net Mon Sep 8 19:07:23 2003 From: bokr at oz.net (Bengt Richter) Date: 8 Sep 2003 23:07:23 GMT Subject: Eureka! (Re: Comments on Python Redesign) References: <3F5CD10B.2020709@teksavvy.com> <200309072018.05589.dave@pythonapocrypha.com> <3F5CF116.2F755AA6@engcorp.com> Message-ID: On Mon, 08 Sep 2003 17:13:58 -0400, Peter Hansen wrote: >Skip Montanaro wrote: >> >> Dave> I don't know of any problem with tinyurls - *any* server can >> Dave> provide a "bad" redirect; as with any URL whether or not you >> Dave> follow it depends on the context and on how much you trust the >> Dave> sender. >> >> The only other reasons I could think of to object to tiny urls are: >> >> * Perhaps the tinyurl folks are not trustworthy (are they keeping track of >> your browsing habits and selling that info?). That seems unlikely, since >> they don't appear to be storing cookies in my browser. >> >> * The tinyurl website can become a bottleneck, preventing people from >> getting where they want to go. The tinyurl.com website seems to be fairly >> unreachable for me at the moment, though this is the first time I've seen >> this, and it appears to be a problem more with Northwestern's connection >> to the net than tinyurl.com's. >> >> * There's no guarantee tiny urls will remain unique or even available for >> long periods of time. Their current practice of using four lower-case >> letters suggests they have space for about 450,000 unique URLs before >> extending to a fifth letter. > >* You can't tell ahead of time what site you are going to be redirected to. > As a result, you lose complete freedom to choose whether or not you should > follow the link. (Note for the imprecise: I didn't say you completely lose > freedom, I said you lose complete freedom.) > I guess it wouldn't be too hard to set up a cgi url on python.org, if desired, to do two-step redirection -- i.e., you'd pass it a small string and it would look up the URL and generate a minimal html page with a plain url link in it, e.g., www.python.org coded url service http://the.real.target.com And then you could choose whether to click, but you only have to type e.g., http://codedurl.python.org?smallstring or such. And you could accept URLs via a form and generate and store the short codes. Some filtering would probably be advisable. As far as tinyurl itself, I wonder if one couldn't get the real url (without committing to go there) by doing the http protocol step by step with telnetlib. I'm not feeling motivated enough to do it at the moment ;-) Regards, Bengt Richter From BjornPettersen at fairisaac.com Wed Sep 17 22:03:20 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Wed, 17 Sep 2003 21:03:20 -0500 Subject: database Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907624D1F@stpmsg00.corp.fairisaac.com> > From: Alberto Vera [mailto:avera at coes.org.pe] > > Hello: > > Do you have any example about how access to a database > using ODBC or native driver? using the win32all odbc module >>> import odbc >>> cn = odbc.odbc('AcctDB') >>> c = cn.cursor() >>> c.execute('select * from AcctMetaInfo order by snapshotdate') 0 >>> row = c.fetchone()[:10] # first ten columns >>> row (141410449310712784L, 7051, , 2147483646, 0, 2147483646, '?1', 2147483646, '?1', ) >>> str(row[2]) 'Mon Apr 15 11:14:04 2002' >>> str(row[-1]) '\t\x13\x14\x01\x00\x00\x00\x00\x00\x00\x00' >>> using the adodbapi module (http://sourceforge.net/projects/adodbapi): >>> import adodbapi >>> cn = adodbapi.connect('AcctDB') >>> c = cn.cursor() >>> c.execute('select * from AcctMetaInfo order by snapshotdate') >>> row = c.fetchone()[:10] >>> row (141410449310712779L, 7051, datetime.datetime(2002, 4, 15, 11, 14, 4), 2147483646, 0, 2147483646, u'?1', 2147483646, u'?1', ) >>> row[2] datetime.datetime(2002, 4, 15, 11, 14, 4) >>> str(row[-1]) '\t\x13\x14\x01\x00\x00\x00\x00\x00\x00\x00' using query analyzer: AccountID ...ID SnapshotDate ... -------------------- ----------- ------------------------ 141410449310712779 7051 2002-04-15 11:14:04.000 ... The account id is a bigint, and as you can see the odbc module loses precision because it is first converted to a float internally. Both modules convert currency/money data to float: >>> c.execute('select Amount from FinancialInfo where acountid = 1234') >>> c.fetchone() (80.439999999999998,) >>> which is of course completely horrible. With the adodbapi module you can change the default behavior however: ---------------------- import adodbapi class Money(long): def __new__(self, value): return long.__new__(Money, value) def __repr__(self): d, c = divmod(self, 10000) return '$%s.%s' % (d,c) def cvt_money((hi,lo)): # not extensively tested :-) return Money((hi<<32) + (lo < 0 and (2**32+lo) or lo)) adodbapi.variantConversions[adodbapi.adCurrency] = cvt_money cn = adodbapi.connect('AcctDb') c = cn.cursor() c.execute('select Amount from FinancialInfo where where acountid = 1234') print c.fetchone() ---------------------- the output: ($80.4400,) which is much better :-) I don't have mxODBC, nor any native drivers to test with (although I'd be interested in the results if anyone else does..) taking-a-break-from-mdx'ly y'rs, -- bjorn From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 01:14:54 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 06:14:54 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> Message-ID: On Tue, 23 Sep 2003 04:49:42 GMT, "M-a-S" wrote: > >> > Some more looping thoughts - this time on integer for loops... > >I guess this should be a matter of optimization. Why don't the Python >compiler recognize 'for in [x]range(,):'? It should be >pretty easy. Microsoft does marvels optimizing loops in C. Why an open >source project like Python can't do it? For all I know it does. Complaints about the 'xrange' notation are normally about the syntax, not the efficiency. For instance, take this quote from Guidos parade of PEPs... """ PEP 284 - Integer for-loops - Eppstein, Ewing Yet another way to address the fact that some people find for i in range(10): too ugly. """ The word is "ugly", not "slow". -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From max at alcyone.com Tue Sep 16 15:43:46 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 16 Sep 2003 12:43:46 -0700 Subject: Print always puts newline (or adds a space) References: <3d9e1e6e689e3a662f59990c4b401713@news.teranews.com> <3F64DEF7.F98CFAB8@alcyone.com> Message-ID: <3F6767F2.90C426B8@alcyone.com> Tobias Pfeiffer wrote: > Is it then also possible to "jump back" a few chars to, e.g., have a > progress... (damn, I forgot that word) however, that shows the > percentage > of progress? Like print "25%" and then jump back three chars and write > "26%"? That's typically done with printing BS characters to back up one space ('\b') or CR characters to return the carriage to the beginning of the line ('\r'). Note that strictly speaking these may not have the desired effect, although in most environments they will. > And then, on my Linux machine, such things just don't happen at all. > E.g. > in a loop like... > > for i in range(1000): > j = pow(2,i) > if j%100: print "#", > > ...I will get nothing for a long time and then ten "#" chars at one > time. > Is there a solution for that? You're encounting buffering; use sys.stdout.write directly and call sys.stdout.flush() after you've printed some partial output. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Custom reconciles us to everything. \__/ Edmund Burke From newsgroups at jhrothjr.com Wed Sep 24 14:13:18 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 24 Sep 2003 14:13:18 -0400 Subject: __init__ return value References: Message-ID: No. __init__(self) returns None. In fact, I'm not certain whether it even checks for the value of the return. __init__()'s function is to initialize the instance which is it's first parameter, you cannot change the instance it is working on. If you need to provide your own instance object, use __new__(). John Roth "Batista, Facundo" wrote in message news:mailman.1064424817.693.python-list at python.org... Studying the Tim Peter's FixedPoint code, found this: # can we coerce to a float? yes = 1 try: asfloat = float(value) except: yes = 0 if yes: self.__init__(asfloat, p) return This code is part of the __init__ method of the class. The question is about the last two lines: When you call self.__init__(...), doesn't it return a value that you should return too? Thanks for all. Facundo Batista Gesti?n de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5132 0132 From alanmk at hotmail.com Fri Sep 12 05:58:49 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 12 Sep 2003 10:58:49 +0100 Subject: Parsing XML streams References: <659f82ff.0309111530.c17e4a6@posting.google.com> Message-ID: <3F6198D9.F92A70BE@hotmail.com> Peter Scott wrote: > I'm writing another program that should parse that sort of XML on its > stdin, printing out a more user-friendly representation. For this, I > need to parse the XML as it comes in, not all at once. Peter, Check out the IncrementalParser class in the library module Lib/xml/sax/xmlreader.py This extension of the standard XMLReader class acts just like a SAX parser, in that it delivers SAX2 events to your ContentHandler as it processes the tokens from the source XML document. But rather than the parser itself controlling when and how it gets its input, you control that through the use of the .feed() method. So you can "drip feed" the parser with input if you wish. Not all XML parsers support an IncrementalParser interface. In order for an XML parser to support incremental parsing, it must have been coded specifically to do so. Fortunately, the expat wrapper supplied with the base distribution of python does support incremental parsing. Which I think should solve your problem quite nicely. When you start up your process for the first time, feed() the IncrementalParser a document element (all XML document must have one and only one document element). Then simply feed the output of your logging stream directly to the IncrementalParser, as and when you receive it. You should not have any problems with XML tokens being split over two different .feed() calls either. For example, this should work just fine ip = IncrementalParser() ip.feed('') When your logging stream is closing, simply feed a close tag for your document element to your IncrementalParser, and everything will clean up nicely. Here is some sample code: #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= import xml.sax from xml.sax.handler import ContentHandler logentry = """ Hello, my bot This is a message PeterScott PeterSc """ incr_parser = xml.sax.make_parser('xml.sax.expatreader') incr_parser.setContentHandler(ContentHandler()) incr_parser.feed('') incr_parser.feed(logentry) incr_parser.feed('') #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From tim.one at comcast.net Sun Sep 21 11:02:30 2003 From: tim.one at comcast.net (Tim Peters) Date: Sun, 21 Sep 2003 11:02:30 -0400 Subject: python script as an emergency mailbox cleaner In-Reply-To: Message-ID: [Phil Weldon] > Inboxer for Outlook is a plugin written with Python that will analyze > collections of what you consider legitimate e-mail and and what you > consider illegitimate e-mail. The classification engine in Inboxer comes from the free spambayes project: http://www.spambayes.org/ Inboxer is a commercial product (produced by some old friends of mine from Dragon Systems, but I have no other connection to it), which can afford to pay people to research and add ease-of-use features. The spambayes project is behind on that count, but for the technically-minded should perform equally well. > I downloaded it and ran it against a collection of 1500 messages > generated by the Worm.Automat.AHB and 265 the latest legitimate > e-mails I've received. The spambayes engine works best when trained on approximately equal numbers of ham and spam. You should actually get better results if you train on far *fewer* than 1500 of a particular species of spam. In my home classifier, I eee I've trained on 6 slightly different instances of Worm.Automat spew, and that's all. All the rest I've gotten were classed as spam (but I have my spam cutoff set to 80, and IIRC Inboxer defaults that to 90). > After the analysis, Inboxer has detected about 250 Worm.Automat.AHB > generated messages with no false negatives and no false positives > (granted there were only three new legitimate e-mails. If you start getting some, the paradoxical best thing to do would, again, be to train on *fewer* worm spew messages. From peterm at resmed.com.au Tue Sep 30 17:42:53 2003 From: peterm at resmed.com.au (Peter Milliken) Date: Wed, 1 Oct 2003 07:42:53 +1000 Subject: [ANN] pylint-0.2 References: <83ekxyii45.fsf@musca.logilab.fr> Message-ID: Sorry mate, but I am in the same directory of the Python file I am trying to run through pylint and I get the same message originally posted by Mark Hahn. So something is wrong - perhaps you should verify that what is on the web-site is actually working as you expect? Here is the full error message from one of my runs: roebourne#1(~/swimming)$ python c:/Python22/Lib/site-packages/logilab/pylint/lint.py roll.py No config file found, using default configuration Traceback (most recent call last): File "c:/Python22/Lib/site-packages/logilab/pylint/lint.py", line 529, in ? Run(*sys.argv[1:]) File "c:/Python22/Lib/site-packages/logilab/pylint/lint.py", line 496, in __init__ modname = '.'.join(modpath_from_file(modname)) File "c:\Python22\Lib\site-packages\logilab\common\modutils.py", line 70, in modpath_from_file raise Exception('Unable to find module for %s in %s' % ( Exception: Unable to find module for c:\usr\local\swimming\roll in c:\usr\local\swimming, c:/Python22/Lib/site-packages/logilab/pylint, c:\Python22, c:\Python22\DLLs, c:\Python22\Lib, c:\Python22\Lib\lib-tk, c:\usr\local\swimming, c:\Python22\lib\site-packages, c:\usr\local\share\emacs\site-lisp\pymacs [exited with 1] Note that I am running Python 2.2.2. Peter "Sylvain "Th?nault"" wrote in message news:83ekxyii45.fsf at musca.logilab.fr... > "Mark Hahn" writes: > > > They not only feel no need to document, they also feel no need to follow ANN > > threads they start. > > Sorry, I don't have the time to follow c.l.py at the moment and that's > just today that I've been informed about this thread. > > So, regarding the command line, pylint expects the name of a package > or module as argument. As a convenience, you can give to it a file > name if it's possible to guess a module name from the file's > path, using the python path. Some examples : > > "pylint mymodule.py" should always works since the current working > directory is automatically added on top of the python path > > "pylint directory/mymodule.py" will work if "directory" is a python > package (i.e. has an __init__.py file) or if "directory" is in the > python path. > > "pylint /whatever/directory/mymodule.py" will work if either: > - "/whatever/directory" is in the python path > - your cwd is "/whatever/directory" > - "directory" is a python package and "/whatever" is in the python path > - "directory" is a python package and your cwd is "/whatever" > and so on... > > > Regarding the lack of documentation, we're pretty busy at this time at > logilab, but I hope we'll have the time to write some until the next > release... Anyway, any contribution would be welcome ;) > > > Hope that helps, > regards > -- > Sylvain Th?nault LOGILAB, Paris (France). > > http://www.logilab.com http://www.logilab.fr http://www.logilab.org From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Sep 21 17:33:42 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 21 Sep 2003 23:33:42 +0200 Subject: how to find a user in a xml document In-Reply-To: References: Message-ID: <3f6e1936$0$58713$e4fe514c@news.xs4all.nl> Martin wrote: > hi, I need to find a way to check in a XML document if a certain user exist, > if not i want to add it in the document. > I am able to add it in the xml doc, but I cant make sure he doesnt exist > thanks > Martin http://www.catb.org/~esr/faqs/smart-questions.html#beprecise --Irmen From s.keim at laposte.net Fri Sep 26 03:35:29 2003 From: s.keim at laposte.net (sebastien) Date: 26 Sep 2003 00:35:29 -0700 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> Message-ID: <7da8d8f8.0309252335.2add37ff@posting.google.com> "Raymond Hettinger" wrote in message news:... > If you have a magic method, __riter__, then the corresponding > function needs to be a builtin. They go hand in hand. The > core parts of the language need to be usable without having > to know about itertools. I don't think so: We already have this situation for the the copy module: copy.copy() use the __copy__ magic method and copy.deepcopy() use __deepcopy__ I've never heard about problems with this behaviour. In fact it's not the __riter__ magic method which will use riter() function but the opposite, so an object which define __riter__ doesn't need to now anything about riter(). From alleon at club-internet.fr Fri Sep 5 02:37:01 2003 From: alleon at club-internet.fr (Sophie Alléon) Date: Fri, 5 Sep 2003 08:37:01 +0200 Subject: newbie question about dictionnary ? Message-ID: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Hi, CONTEXT I do numerical simulation for which I have to process mesh. A mesh is made of triangle which are made of points. I want from this information to create edges and build triangle from edges rather than from points. PROBLEM An edge is shared by possibly more than one triangle. ALGORITHM have a triangle class (made of 3 edges) have an edge class (made of 2 points and embeding a triangle list (those connected to the edge) for each triangle construct its edges but I have to check if the edge already exists for doing this I thought the dictionary was excellent but the key is a string while I want it to be the 2 points forming the edge ? How to do it ? Have you a better idea ? Thanks Guillaume From mitchchapman at earthlink.net Sat Sep 13 12:18:42 2003 From: mitchchapman at earthlink.net (Mitch Chapman) Date: Sat, 13 Sep 2003 10:18:42 -0600 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <16227.13073.611762.21526@montanaro.dyndns.org> Message-ID: On Saturday, September 13, 2003, at 09:09 AM, Skip Montanaro wrote: > Mitch> Unlike Andrew I don't think the lack of maintenance for > 1.4's > Mitch> free threading packages is due to any perception that > threading > Mitch> performance is unimportant. It seems more likely that the > Mitch> packages were not updated because they proved not to solve > the > Mitch> performance problems, and that no alternatives have emerged > Mitch> because the problem is hard to solve. > > One reason (maybe the primary reason) it never went further than a > patch to > 1.4 was that it was slower in the (common) single-threaded case. For more on the patch, see the FAQ: http://www.python.org/doc/faq/library.html#can-t-we-get-rid-of-the- global-interpreter-lock I wish I'd read this entry before my latest reply to Andrew Kuchling. It explains why somebody (GvR, according to the old FAQ) believes free-threading would decrease the suitability of Python for existing users. > You can read the few messages in > python-dev in the archive for September: > > > http://mail.python.org/pipermail/python-dev/2003-September/thread.html > > Search for "thread safe". Thanks for publishing the pointers. I didn't consider that others might be interested in the original thread. -- Mitch From buzzard at urubu.freeserve.co.uk Thu Sep 18 09:16:40 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Thu, 18 Sep 2003 14:16:40 +0100 Subject: convert ints in a range to strings References: <3F6900D2.7080806@hotmail.com> Message-ID: "hokiegal99" wrote in message news:3F6900D2.7080806 at hotmail.com... > Thanks Heather... this did it: > > outputFile = file('ips.txt', 'w') > r = range(256) > for r in range(256): > f = '192.168.1.%s\n' % r #Change this line to macth your network. > outputFile.write(f) > outputFile.close() > [snip] The second line of this code does nothing useful. My feeling is that as r is an integer you should really use %d, rather than %s. Duncan From alan.gauld at btinternet.com Thu Sep 4 09:31:10 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Sep 2003 13:31:10 GMT Subject: Code complete electronic version ? References: <3f566672.342116427@news.blueyonder.co.uk> Message-ID: <3f573c71.396898579@news.blueyonder.co.uk> On 04 Sep 2003 10:09:21 +0200, Syver Enstad wrote: > > Code Complete is essential reading for any prpfessional > > programmer IMHO, but it may not be essential for non pros... > > I agree that Code Complete is a very good book, but I also think it is > getting somewhat long in the tooth. For once it doesn't cover > object-orientation. Thats a deliberate choice, OO was well established when McConnell wrote the book. And apart from trivial details (usually language specific ones) there is no difference between coding in an OO language or a procedural one. That is the real issues of naming, layout, control structures, data structures, testing and debugging remain constant. > On the topic of coding I wonder if people are not > better off buying Refactoring by Martin Fowler and Kent Beck. These books are more about design than coding IMHO. > topic of project managment and development practices I would think > that the XP white book would be more up to date. Code Complete doesn't cover these, but Rapid Development covers the principles behind XP etc quite well given that XP per se wasn't invented then. (But pair programming and several other features of XP have been around for 20+ years so McConnell was well aware of them.) XP is also not universally accepted as being suitable for all projects, particularly big ones, and McConnell tries to cover all bases. The other coding centred books that are worth considering in a similar vein (IMO!) are The Practice of Programming by Kernighan & Pike and The Pragmatic Programmer by Hunt & Thomas And for an overview of all the different development lifecycle/methodologies I recommend the book: Wicked Problems, Righteous Solutions by DeGrace & Stahl Its pre XP but most of XP can be found there in one form or another. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From j_k_wd at bellsouth.net Fri Sep 19 23:20:30 2003 From: j_k_wd at bellsouth.net (Jeremy Dillworth) Date: Fri, 19 Sep 2003 23:20:30 -0400 Subject: bizarre behavior using .lstrip In-Reply-To: <200309192243.27913.j_k_wd@bellsouth.net> References: <681f9321.0309191607.4e8b858a@posting.google.com> <3F6B9B44.9EAD3CF9@engcorp.com> <200309192243.27913.j_k_wd@bellsouth.net> Message-ID: <200309192320.32647.j_k_wd@bellsouth.net> whoops! Forgot the '^' in the regex... >>> import re >>> s = 'chg cbonn_fee' >>> print re.sub('^chg ', '', s) On Friday 19 September 2003 10:43 pm, Jeremy Dillworth wrote: > As an alternative you could use re.sub() > > >>> import re > >>> s = 'chg cbonn_fee' > >>> print re.sub('chg ', '', s) > > cbonn_fee > > On Friday 19 September 2003 8:11 pm, Peter Hansen wrote: > > Pete Jereb wrote: > > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > > > win32 > > > > > > >>> s = 'chg bonn_fee' > > > >>> print s > > > > > > chg bonn_fee > > > > > > >>> print s.lstrip('chg ') > > > > > > bonn_fee > > > > > > >>> s = 'chg conn_fee' > > > >>> print s > > > > > > chg conn_fee > > > > > > >>> print s.lstrip('chg ') > > > > > > onn_fee > > > > > > Does this make any sense at all? where did the lead c in conn_fee go? > > > > Based on the behaviour you describe, I would assume lstrip() > > removes, starting at the beginning of the string, all characters > > which are *anywhere* in the argument string you give it, until > > it encounters a character not in that string, at which point it > > stops. > > > > -Peter From peter at engcorp.com Tue Sep 16 15:11:39 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 16 Sep 2003 15:11:39 -0400 Subject: tuples vs lists References: <9egemvkhp2s55horjr9dfveml22158d62g@4ax.com> Message-ID: <3F67606B.C9A89EF3@engcorp.com> Ivan Voras wrote: > > Ok, I gather touples should be smaller & faster as I thought :) Don't make a decision based on performance. Use tuples if you require the immutability, or if you want to follow Guido's "advice" (?) to treat them as simple unnamed structs. Use lists any time you want lists of stuff, even if you think you might benefit by the supposedly higher performance of a tuple. Anyone reading your code will likely be much happier, and you won't find yourself getting caught in a bind because you've used an immutable tuples where you really should have used a list. -Peter From exarkun at intarweb.us Sat Sep 27 03:15:53 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 27 Sep 2003 03:15:53 -0400 Subject: Digest Authentication (RFC 2831) Message-ID: <20030927071553.GA11955@intarweb.us> I've been trying to implement support for this authentication scheme for a little while now, and in the last couple days I've been completely stumped. I know about the digest authentication code in urllib2, and while I'd like to use it directly, it is too closely tied to HTTP for my needs. I have taken hints from the code, but I am still stuck with something that doesn't recognize correct challenge responses as correct. I've reduced the problem to this code: user = "exarkun" passwd = "password" realm = "intarweb.us" nonce = "abcdefg" qop = "auth" method = "REGISTER" uri = "sip:exarkun at intarweb.us" nc = cnonce = '' def H(s): return md5.md5(s).digest() def KD(k, s): return H(k + ":" + s) def HEX(s): return s.encode('hex') def A1(user, realm, passwd, nonce, cnonce): r = H(user + ":" + realm + ":" + passwd) return r + ":" + nonce + ":" + cnonce def A2(uri, method): return method + ":" + uri def RESP(a1, nonce, nc, cnonce, qop, a2): r = nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" return HEX(KD(H(a1), r + HEX(H(a2)))) def g(): return RESP( A1(user, realm, passwd, nonce, cnonce), nonce, nc, cnonce, qop, A2(uri, method) ) correct = '8cf8b637395da8475d65aaf45e4cfad5' v = g() print v == correct print correct print v It is, essentially, a straight translation from the RFC, but I have been unable to get it to produce the given correct value for the given inputs. One sticking point seems to be that the client authenticating against me omits both the nc and cnonce values. If there is a standard correct way of computing the digest without those values, it does not seem to be covered by the RFC. I have tried the obvious approaches of simply removing them, supplying "" as their value, etc, but nothing works. I am on the verge of breaking down the md5() calls so I can discover the point of failure more accurately, but before I did that I was hoping I might find someone who has implemented this before and could give me some hints. Any help is appreciated, Jp -- No, `Eureka' is Greek for `This bath is too hot.' -- Dr. Who -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From python at sarcastic-horse.com Fri Sep 19 14:40:11 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Fri, 19 Sep 2003 14:40:11 -0400 (EDT) Subject: How do I learn operator overriding? In-Reply-To: <53332.199.169.240.132.1063995923.squirrel@svr1.turboweb.net> References: <53332.199.169.240.132.1063995923.squirrel@svr1.turboweb.net> Message-ID: <50473.199.169.240.132.1063996811.squirrel@svr1.turboweb.net> I forgot to mention some things. If I do subtraction between two qDate objects, I want to get an integer that shows the number of periods (in this case, quarters) between the two dates: >>> 2001q1 = qDate(year=2001, quarter=1) >>> 2001q4 = qDate(year=2001, quarter=4) >>> 2001q4 - 2001q1 3 But if I subtract an integer from my qDate object, I want to get a new qDate object returned, like this: >>> 2001q4 - 2 (new qDate object with year=2001 and quarter=2) Any ideas how to make this possible? > Hi- > > > I need to make a class for quartlerly dates. I need to be able to compare > two quarterly dates and get the number of quarters between them. For > example: > >>>> 2001q1 = qDate(year=2001, quarter=1) >>>> 2001q4 = qDate(year=2001, quarter=4) >>>> 2001q4 - 2001q1 > 3 > > The only problem is that I have no idea how to override operators in > python. Can anyone give me a few trivial examples of how it is done? > > And, on a completely unrelated note, I am getting a truly amazing amount > of spam today. Anyone else? > > > Thanks for the help. > > -- > http://mail.python.org/mailman/listinfo/python-list > From jfmoxley at mit.edu Thu Sep 11 14:20:11 2003 From: jfmoxley at mit.edu (Joel) Date: 11 Sep 2003 11:20:11 -0700 Subject: nested data structures in classes References: Message-ID: For posterity, here's what ended up working. Many thanks to Tom Minka for showing me this. I understood the class stuff in principle, but I just couldn't implement correctly. class ReactionClass: def __init__(self,Name='',Reactant=[],Product=[]): self.Name = Name self.Reactant = Reactant self.Product = Product def __str__(self): # how to print the object return self.Name+': '+str(self.Reactant)+' -> '+str(self.Product ) Reaction = [] # two different ways of defining a reaction Reaction.append(ReactionClass('Kinase',['GLUC', 'ATP'],['G6P', 'ADP'])) print(Reaction[0].Name) print(Reaction[0]) Reaction.append(ReactionClass()) Reaction[1].Name = 'and so on' Reaction[1].Reactant = ['one', 'two'] Reaction[1].Product = 'something else' print(Reaction[1]) print(Reaction[1].Reactant[1]) jfmoxley at mit.edu (Joel) wrote in message news:... > Does anyone have any thoughts on this? > > Joel Forrest Moxley wrote in message news:... > > Greetings python-list! > > > > The good news is that I've been having a blast with Python since early > > Spring. I've had great success in both learning the language from online > > / usegroup resources and implementing it in one of my projects. However, > > I can't pretend to be an expert, and I do not have a strong comp sci > > background. > > > > This is a question that I've had for a while. Usually, I'll stumble > > across the answer with repeated attempts and re-searching the groups, but > > I didn't have luck with this one, even in a Dietel book I picked up at the > > library. I'm assuming there's an obvious answer, so maybe ya'll can save > > me some time. > > > > My Python use involves organizing nested list information. In a > > simplified example, you could imagine a list of reactants and products in > > a chemical reaction. Thus, > > > > len(nested_list_of_reactants) = len(nested_list_of_products) => "number of > > reactions" > > where: nested_list_of_reactants[i] => "list of reactants for reaction i" > > where: nested_list_of_reactants[i][j] => "reactant j of reaction i" > > > > And so forth. Obviously, there are many attributes associated with a > > specific reaction. Currently, I just pass these attribute lists (nested > > and non-nested) into and out of functions. However, I'd like to be able > > to create a class that would streamline this. > > > > E.g., (this is a MATLAB structure whose qualities I'd like to emulate): > > reaction(27).name = 'fawlty towers' > > reaction(27).reactant(2).name = 'john cleese' > > > > Currently, I'd have a list and a nested list to take care of this... > > reaction_name[27] = 'fawlty towers' and reactants[27][2] = 'john cleese' > > if this makes sense. > > > > Any thoughts or suggestions on this type of data structuring would be > > greatly appreciated. Python love, Joel From spam at magnetic-ink.dk Tue Sep 30 08:04:33 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Tue, 30 Sep 2003 12:04:33 +0000 (UTC) Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> <3f7918e1-cebe25d5-ba02-4762-ae3e-ad3bb70874cb@news.szn.dk> <_e9eb.9852$NX3.7090@newsread3.news.pas.earthlink.net> Message-ID: <3f797151-bf04018c-520c-41ee-90cc-98041c2bdafd@news.szn.dk> Andrew Dalke wrote: >> I found 5,761,455 primes < 1E8. > > http://www.utm.edu/research/primes/howmany.shtml has the same > number. (found by googling for "5,761,455" - 3rd hit. :) Cool! > That's using Proof by Consensus, > http://www.isip.msstate.edu/about_us/misc/humor/proofs/ :-) // Klaus -- ><> unselfish actions pay back better From tzot at sil-tec.gr Tue Sep 16 18:48:03 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 17 Sep 2003 01:48:03 +0300 Subject: Help with Python References: Message-ID: On Tue, 16 Sep 2003 14:16:56 -0700, rumours say that "Fernando Armenta" might have written: >I need to check for a directory and move it to other directory if is >found. The directory always starts with outlog.XYZ and ends in XYZ >(where XYZ are variables). I need to use wild characters. Here is what >I have, but is not working. Any help would be appreciated. > > > >#Path for the file > >home_trace = "/home/testeng/ca/tds/outlog.* " > > > >#Path for the directory where I want to move the file > >directory = "/home/testeng/ca/tds/unattached" > > > >#If statement > >if os.path.exists(home_trace): > > os.system ("chmod -fR 775 outlog.* ") > > os.system ("mv outlog.* " + directory) Import glob, then for each file in glob.glob('outlog.*'), use os.chmod() and os.rename() with appropriate parameters. os.rename() would probably fail if you moved your files to another filesystem, but in your example this does not seem to be the case. PS I just remembered that I have seen at least one C++ freshly-graduated programmer serving as a sysadm in a university praising C++ as a scripting language (!); his code was full of system() calls. When I asked him, "why not a shell script?", he said "this is faster... it's C++...". I mentioned the difference of a shell doing spawn() and an executable doing spawn() to a shell doing another spawn(). Discussing it further, he said that executables are not "legible"; so, *just before* suggesting a "chmod 500" operation on a root-owned script, I told him about the "strings" command as an obvious counter-argument for a naive disassembly. I chose the wrong order of sentences; he actually removed /usr/bin/strings in haste, as if his job was depending on its disappearance... FWIW, it did --in the opposite way. There are no limits. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From jordan at krushen.com Mon Sep 29 22:56:54 2003 From: jordan at krushen.com (Jordan Krushen) Date: Tue, 30 Sep 2003 02:56:54 GMT Subject: Threading and Windows. References: <21064255.0309291225.259555ec@posting.google.com> Message-ID: On Mon, 29 Sep 2003 23:29:18 -0300, Jorge Godoy wrote: >> Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and >> spawnvpe() are not available on Windows. New in version 1.6. > > So I should be safe since I'm using spawnv (and not spawnvp or > spawnvpe). :-) For running a file based on its extension, you could try os.startfile(). J. From skip at pobox.com Wed Sep 24 14:35:49 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 24 Sep 2003 13:35:49 -0500 Subject: __init__ return value In-Reply-To: References: Message-ID: <16241.58373.833630.615370@montanaro.dyndns.org> Facundo> The question is about the last two lines: When you call Facundo> self.__init__(...), doesn't it return a value that you should Facundo> return too? No, __init__ method return values are always ignored. Skip From skip at pobox.com Wed Sep 17 10:33:14 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 17 Sep 2003 09:33:14 -0500 Subject: Can Python Module Locate Itself? In-Reply-To: References: Message-ID: <16232.28842.523390.480626@montanaro.dyndns.org> sj> I have written several small shell utilities in Python and typically sj> use comments at the start of the source file as documentation. A sj> command line option allows the user to read this documentation. The sj> problem is that I have to explicitly code the source files location sj> within the source which is not very portable. Is there anyway for a sj> python module to locate its own source ? This doesn't answer your question about locating the source file (yes, you can most of the time, check the __file__ global), but I start out with this template when creating a new script: #!/usr/bin/env python """ Python Script Template usage %(prog)s [ -h ] ... -h - print this documentation and exit. """ import sys import getopt prog = sys.argv[0] def usage(msg=None): if msg is not None: print >> sys.stderr, msg print >> sys.stderr, __doc__.strip() % globals() def main(args): try: opts, args = getopt.getopt(args, "h", ["--help"]) except getopt.GetoptError, msg: usage(msg) return 1 for opt, arg in opts: if opt in ("-h", "--help"): usage() return 0 return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:])) This guarantees I always have a help capability, no matter how trivial. (This is not original with me. I gleaned all the idioms used in this script from this group over the years.) Skip From ulope at gmx.de Thu Sep 18 08:19:08 2003 From: ulope at gmx.de (Ulrich Petri) Date: Thu, 18 Sep 2003 14:19:08 +0200 Subject: How to pass parameter to a module? References: Message-ID: "M-a-S" schrieb im Newsbeitrag news:Vwfab.2454$9G2.2174 at twister.southeast.rr.com... > I'd like to parametrize a module. That is, to set and pass > some values into the module, while it is being imported. > I tried this: > > # sub_1.py -- main program > extern = "OK" > import sub_2 > print sub_2.noway # prints 'no extern' :-( > # EOF > > # sub_2.py -- parametrized module, parameter is the 'extern' var > try: > noway = extern > except: > noway = 'no extern' > # EOF > It looks like you are using modules where you would rather use functions. exp: -------------------cut--------- def sub2(blah=None): if blah is None: return "no extern" else: return blah sub2('test') sub2() HTH Ciao Ulrich From gh at ghaering.de Mon Sep 15 11:44:20 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 15 Sep 2003 17:44:20 +0200 Subject: Multiple instances of modules In-Reply-To: References: Message-ID: <3F65DE54.1040605@ghaering.de> Daniel Pryde wrote: > Hi there. > > I'm currently trying to learn Python, my aim being to create my final > year project at university using only Python instead of Java. I've run > into a problem though while trying to make multiple instances of > modules. > > For example, say I made a CD.py module which held details of an audio > compact dic (album name, track names, etc..), and wanted my Python > script to make a record collection using multiple CD's, I can't make > them seperately. I tried using the 'import module as name' format, but > any changes made to one instance affects the other. I assume this is > because Python is simply referencing the one instance of CD.py rather > than seperate ones. Is there a solution to this that doesn't involve > using cPython or Jython? Any help would be greatly appreciated. Use class instances to keep state, not modules. This is really the basics of object-oriented programming and should be explained in the (Python) tutorials. -- Gerhard From jjl at pobox.com Sat Sep 6 18:52:14 2003 From: jjl at pobox.com (John J. Lee) Date: 06 Sep 2003 23:52:14 +0100 Subject: Why python??? References: <87fzjalogu.fsf@pobox.com> <87vfs6unsx.fsf@pobox.com> Message-ID: <87n0dhpm1t.fsf@pobox.com> "Michael Peuser" writes: > "Basile STARYNKEVITCH" [...] > But you bring up Python's aspects as a "glue language". Is Python the better > "glue language"? May be. Have look at DISLIN which (I think) is a FORTRAN > project by nature. And SIP and WSIG are quite nice. Mmm? What about them? > However the *real* programs then are the mathematical packages, OpenGL, > simulation and visualisation. See below. > But may be the whole concept of programming is changing somehow - not in the > direction of OOP; that is "by the way" so to speak. But to the following > understanding: > A program is an entity that controls other entities by support of an > underlying virtual machine. No, I don't see why the definition of a computer program needs any modification. > This new view will support the existing differentiation between package > maker ("real programmer") and scripting user ("domain specialist") So application programming isn't "real programming" and doesn't require a "real programmer"? You're beginning to sound like a troll! (though I'm sure you don't mean to) > In this interpretation (as secondary glue language) I see a good future for > Python. The reality of programming in Python is that in applications programming (and much else too, of course), it's languages like C that are secondary. Most of the time, it's rare that you need to drop down there to speed something up. And much of the time that one *does* use C (or whatever) libraries, the major reason is simply that solid working code already exists there, rather than some failing of Python (though there are certainly also many cases where close to raw C speed is crucial). [...] > You might already have guessed, that I belong to the generation that learnt > programming the Knuthian way, starting with assembly language and beeing > always aware that a van Neumann hardware interpreted their compiled code. > And input and output were a teletype..... And you got out of bed in the morning three hours before you went to sleep, I know ;-) John From danielk at aracnet.com Tue Sep 2 09:05:09 2003 From: danielk at aracnet.com (Daniel Klein) Date: Tue, 02 Sep 2003 06:05:09 -0700 Subject: Polymorphism the Python way References: Message-ID: <5959lvs6au0b454r2lbvkb5nourhmigvnj@4ax.com> On Sun, 31 Aug 2003 03:47:49 -0400, Graham Fawcett wrote: >Why not just use the same attribute name in each class? > > class Dead(object): > def __init__(self, deadthing): > self.thing = deadthing > > class Parrot(object): > def __init__(self, parrotthing): > self.thing = parrotthing > >Then you can access the attribute as `someobj.thing`. > >Given that you hate getters, and that you didn't title your message, >"Encapsulation the Python Way", accessing instance attributes directly >is fair game. ;-) Yes, I could do this, but a method provides better control over the state. Daniel Klein From rjc at tampabay.rr.com Thu Sep 25 13:24:56 2003 From: rjc at tampabay.rr.com (Robert Clayton) Date: Thu, 25 Sep 2003 17:24:56 GMT Subject: Packages and PyKyra References: <1dCcb.11020$Of2.520042@twister.tampabay.rr.com> <6wCcb.164799$R32.5291608@news2.tin.it> Message-ID: Thank you! There are no PyKyra .py, .pyc, .pyd files. There is a release PyKyra.dll and a source directory contains a __init__.py file. Trying to use the PyKyra.dll returns: "ImportError: dynamic module does not define init function (initPyKyra)" Therefore I was attempting to define the location of the Package (directory structure). There is little information about creating path references for Packages in Windows. Some material suggest various registry entrys others suggest a environment variable. I have attempted the three suggestions I found: 1) A System Environment Variable "PYTHONPATH" with the directory string. 2) Addition of the directory to the existing Registry Key String "HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.2\PythonPath" 3) Creation of a new Registry Key HKEY_LOCAL_MACHINE\SOFTWARE\Python\PYTHONPATH with the accompanying directory, None of these seem to work. The error "ImportError: No module named xxxxxxxx" appears to mean that nothing is treated as a package. "Alex Martelli" wrote in message news:6wCcb.164799$R32.5291608 at news2.tin.it... > Robert Clayton wrote: > > > In the PyKyra example programs what does the statement: > > > > "from PyKyra import *" > > > > I now assume that this represents a Package hierarchy and not the file > > "PyKyra.py" as there is none but for Windows 2000 I am unable to determine > > whereor how the path is represented (registry, environment, etc.). Any > > suggestions? > > I have no idea about what PyKyra is, but: > > [a] > You can find out what the path is, at any time, by the two statements: > > import sys > print sys.path > > [b] > If you're right in stating there is no PyKyra.py file, then the > import may be coming from: > [b1] a PyKyra.pyc or .pyo bytecode file > [b2] a PyKyra.pyd or .dll C-coded extension module > [b3] the __init__.py file in a PyKyra directory on the path > > The only case involving "packages" is [b3] -- that's what a > package _IS_... a directory with an __init__.py file. > > > In any case, the "from PyKyra import *" statement gets the > contents listed in the __all__ entry in module PyKyra, or, if > no such entry, then all entries in module PyKyra whose names > do not start with a single underscore character _ . > > The usage of "from whatever import *" is generally unadvisable > except perhaps in those rare cases in which module 'whatever' > has been carefully designed to support this. Personally, I've > lost the habit of "import *" just about entirely -- even for > carefully designed modules such as Tkinter and Numeric, I do > "import Tkinter as Tk" or "import Numeric as N" and then access > their entries explicitly as Tk.Tk, N.array, etc, etc. I find, > personally, that this makes my programs more maintainable. > > > Alex > > From cliechti at gmx.net Sun Sep 28 20:37:44 2003 From: cliechti at gmx.net (Chris Liechti) Date: 29 Sep 2003 02:37:44 +0200 Subject: ANN: Win32 Screensaver library Message-ID: Win32 Screensaver This is a complete rewrite of my old screensaver module. This one is pure Python with the help of ctypes and py2exe. It is intended to make it easy to write windows screensavers in pure Python. Screensavers using the pyscr module can be implemented with ctypes (a little wrapper class around a DC already exits) or win32all. The pyscr_pygame module also gives the opportunity to write the screensaver with pygame. The Win32 parts are implemented using ctypes. Requires Python 2.3, ctypes, py2exe. Download archive with the library and examples: http://homepage.hispeed.ch/py430/python/index.html chris -- Chris From piet at cs.uu.nl Mon Sep 1 10:31:06 2003 From: piet at cs.uu.nl (Piet van Oostrum) Date: 01 Sep 2003 16:31:06 +0200 Subject: method (a, b = '', *c, **d): gets a syntax error? References: <3F4F644D.2060003@uni-bonn.de> <3dqcndZe5u2g4NKiXTWJiA@comcast.com> Message-ID: >>>>> Andreas Neudecker (AN) wrote: AN> Still it puzzles me that in one case it is okay in the other one not. Seems AN> unlogical to me. Can anyone enlighten me to why this is so? It is quite logical. The idea behind the optional comma after the last parameter is such that it would be easy to change your function to include additional parameters. When you put each parameter on a separate line (as you did in your examples) , you just have to add a single line with the new parameter and it doesn't matter whether the new parameter comes in as the last one or at any other place. If you leave out the final comma, and the new parameter is the last one, you would have to add the comma to the previous line, which can easily be forgotten. However, when you have **kwargs it must be last, so there is no need to put an additional comma. In fact it would be confusing as it would suggest that you can add additional parameters after it. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: P.van.Oostrum at hccnet.nl From buzzard at urubu.freeserve.co.uk Sat Sep 27 09:41:20 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 27 Sep 2003 14:41:20 +0100 Subject: Saving Numeric arrays to file? References: Message-ID: "Emile van Sebille" wrote in message news:bl2ov9$78mdr$1 at ID-11957.news.uni-berlin.de... > Duncan Smith asks about writing Numeric arrays to disk: > > [ 0, 0, 0, 5, 0, 0]]) > > >>> f = file('c:\Data\IS_rounded.txt', 'w') > > > > Perhaps with 'wb' ? > > Emile van Sebille > emile at fenx.com > > It doesn't work for me. Looks like I'll maybe have to avoid \n altogether, use spaces to separate the strings and read characters individually. Basically I have a few hundred thousand sets of 4 tables, each associated with a unique key. The idea was to store them as a text file so that I could quickly fire them into a dictionary (memory permitting?) when I need to use them. Maybe I should be using MySQL for persistence? What I *would* like is a reasonably generic (and not terribly inefficient) solution for storing strings that contain escape characters in text files. Cheers. Duncan From aleax at aleax.it Fri Sep 5 08:29:20 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 12:29:20 GMT Subject: OT: best book in years References: Message-ID: Patrick Useldinger wrote: > trying to find a book or two to read there. As I have not come across > anything spectacular recently (except Python in a Nutshell), I would like > to know what *you* consider to be the best book you have read in the last > few years, about Python or IT in general. I see you got a lot of excellent recommendations (none Python-related, that I've seen, though -- oh well!) and I just thought I'd add mine...: Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin, Prentice Hall just about the book I wanted to write myself -- *except* that all examples are in Java and C++, while I would have chosen Python and Ruby. But if you can stomach reading Java and C++, this is VERY worth reading. Agile Modeling: Effective Practices for Extreme Programming and the Unified Process -- by Scott W. Ambler, John Wiley most XP / Agile development books underplay any artefacts that aren't code -- Ambler shows convincingly how and why "modeling" artefacts may play a crucial role in such dev't processes, and does so in an extremely readable way. Who Says Elephants Can't Dance? Inside IBM's Historic Turnaround by Louis V. Gerstner Jr., HarperBusiness If you're at all curious how IBM was turned around (I was, having left IBM just before its crisis became visible and being left with substantial fondness for that firm), this book will prove quite interesting indeed. Alex From no at spamail.com Sat Sep 20 10:16:58 2003 From: no at spamail.com (jimbob) Date: Sat, 20 Sep 2003 10:16:58 -0400 Subject: Newbie Help Message-ID: Hello all, I am trying to move a file from one dir to another. However I keep receiving this error: OSError: [Errno 18] Invalid cross-device link which stemms from the code: os.rename('/home/me/%s' %z ,'/home1/pics/%s' % z) /home1/pics is on a different dirve(hdb1) as opposed to /home which is on (hda1). Any ideas as to how to get around this? Thanks From mertz at gnosis.cx Thu Sep 11 03:50:51 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Thu, 11 Sep 2003 03:50:51 -0400 Subject: OT: Americans love their guns References: <16223.15950.299463.959577@montanaro.dyndns.org> Message-ID: Grzegorz Staniak wrote previously: |I think it's a mistake to cite Lott here. As an extreme libertarian he |has shown his own bias a couple of times. His famous "More guns, less |crime" findings has been challenged recently (see e.g. |http://www.jointogether.org/gv/news/alerts/reader/0,2061,562387,00.html As well as Lott's tendency to outright falsify data, which Staniak cites, Lott is pretty much an unabashed White Supremicist ideologue, e.g.: http://www.vpc.org/fact_sht/wholott.htm He's actually quite a nut in a lot of ways other than that, for example arguing that dioxin is harmless to people; or that wealthy people should not be punished for committing violent crimes, only poor people. Yours, Lulu... -- 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 jakle1 at hotmail.com Sat Sep 20 21:12:04 2003 From: jakle1 at hotmail.com (News) Date: Sun, 21 Sep 2003 01:12:04 GMT Subject: None??? Message-ID: I just started using python a few weeks ago. This is my first program. You input your income and what percent you want to save then it tells you how much to put away. The the code works, but it puts in the word "none" after it calls the function. Is the call sytax incorrect? I'd appreciate any feedback you could offer . # savings.py 09-14-03 print "Hello, welcome to my savings program." print print "I will ask you a few questions then calculate" print "the info and give you a plan of action." print first_name = raw_input("What is your first name? ") print last_name = raw_input("What is your last name? ") print income = input("How much do you make a year after taxes? ") print percent = input("What percent of your income do you want to put aside? ") print weekly_income = income/52 def compute(income, percent): result = income*percent/100 print result print "Ok,",first_name + " " + last_name print print "This is how much you should put away a week:" print "$",compute(weekly_income, percent) print print "If you stick to this you will go places!!! :-)" begin 666 smile.gif M1TE&.#EA#P`/`*(``````-754O__`.;F5/7U5=O;4____P```"'Y! 44``8` M+ `````/``\```-):*K0O="T4&IX$(1!A"?#M6B=9PJ$* U"8[H#( 6=Z[EI J4YR\5^@]W@\P#.HF!-L+D%NU' Y!C$%[1IM4C at FD&FDJA8LLPH!&$@`[ ` end From sylvain.thenault at logilab.fr Tue Sep 30 08:19:22 2003 From: sylvain.thenault at logilab.fr (Sylvain =?iso-8859-1?q?Th=E9nault?=) Date: 30 Sep 2003 14:19:22 +0200 Subject: [ANN] pylint-0.2 References: Message-ID: <83ekxyii45.fsf@musca.logilab.fr> "Mark Hahn" writes: > They not only feel no need to document, they also feel no need to follow ANN > threads they start. Sorry, I don't have the time to follow c.l.py at the moment and that's just today that I've been informed about this thread. So, regarding the command line, pylint expects the name of a package or module as argument. As a convenience, you can give to it a file name if it's possible to guess a module name from the file's path, using the python path. Some examples : "pylint mymodule.py" should always works since the current working directory is automatically added on top of the python path "pylint directory/mymodule.py" will work if "directory" is a python package (i.e. has an __init__.py file) or if "directory" is in the python path. "pylint /whatever/directory/mymodule.py" will work if either: - "/whatever/directory" is in the python path - your cwd is "/whatever/directory" - "directory" is a python package and "/whatever" is in the python path - "directory" is a python package and your cwd is "/whatever" and so on... Regarding the lack of documentation, we're pretty busy at this time at logilab, but I hope we'll have the time to write some until the next release... Anyway, any contribution would be welcome ;) Hope that helps, regards -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From jjl at pobox.com Sun Sep 7 18:21:53 2003 From: jjl at pobox.com (John J. Lee) Date: 07 Sep 2003 23:21:53 +0100 Subject: Comments on Python Redesign References: <3F5B8C51.6462BC38@alcyone.com> Message-ID: <877k4kjl32.fsf@pobox.com> aahz at pythoncraft.com (Aahz) writes: > In article <3F5B8C51.6462BC38 at alcyone.com>, > Erik Max Francis wrote: > > > >Could someone remind me what need there is for a redesign in the first > >place? Of all the Python-related efforts that one could put time into, > >this seems like one of the least useful. > > AMK's comment is a bit overdone, so here's something more understated: [snip] Whatever. Just don't get rid of all those cute skewed Python logos in all the different typefaces. All sensible people will agree that that's clearly the most important aspect of the site ;-) John From mertz at gnosis.cx Mon Sep 15 21:27:44 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 15 Sep 2003 21:27:44 -0400 Subject: object.attribute vs. object.getAttribute() References: Message-ID: Roy Smith wrote previously: |1) Implicit documentation of which attributes I intended to be part of |an object's externally visible state (accessors). Some attribute names start with an underscore. Those are the ones that are NOT intended to be part of the external interface. |2) Hooks to do data checking or invarient assertions (mutators). Yep, you need accessors (or properties) to do this. |3) Decoupling classes by hiding the details of data structures. Initial underscores again. |4) Vague feeling that I'm doing a good thing by being more in line with |mainstream OO practices :-) If you want to be mainstream, use VB. But accessors are not IMO a requirement for "proper" OOP. Yours, Lulu... -- _/_/_/ 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 mwh at python.net Wed Sep 3 07:17:08 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 3 Sep 2003 11:17:08 GMT Subject: Difference of hash and __hash__() References: <338366A6D2E2CA4C9DAEAE652E12A1DEAD454A@au3010avexu1.global.avaya.com> Message-ID: <7h3ekyygm58.fsf@pc150.maths.bris.ac.uk> Jeff Epler writes: > On Wed, Sep 03, 2003 at 07:35:31AM +1000, Delaney, Timothy C (Timothy) wrote: > > > From: Terry Reedy [mailto:tjreedy at udel.edu] > > > > > > "Stefan Fleiter" wrote in message > > > news:bj2nv5$hna$1 at news.web.de... > > > > > > > under Python 2.2.2: > > > > > > > > >>> s = slice(None,5,None) > > > > >>> hash(s) > > > > Traceback (most recent call last): > > > > File "", line 1, in ? > > > > TypeError: unhashable type > > > > >>> s.__hash__() > > > > 136775584 > > > > > > > > Can anybody explain this? > > > > > > It looks like a bug. Extended slices were added for use by Numerical > > > Python. It may never have tried to hash them or only done so only > > > through the C equivavlent of s.__hash__. Extended slicing of > > > sequences was, I believe, only added in 2.3. > > > > Looks like a bug to me too. Stefan, please raise a bug report on Sourceforge (or it will get lost). Preferably add a patch and test suite ;) > > > > Tim Delaney > > No, it's apparently deliberate that slices don't hash (so that > {}[1:2] raises an error). I think that slice(None).__hash__ is from > object.__hash__, but this is rightfully(?) ignored by PyObject_Hash() > which looks at tp_hash (NULL for slice objects) and tp_compare (non-NULL > for slice objects) with the result that the object is treated as > unhashable. That's odd. I would have expected PyType_Ready to copy the tp_hash method down from PyObjectType.tp_hash to PySliceType.tp_hash. Of course, I haven't read the code for PyType_Ready particularly recently, and don't know if it's ever called on PySliceType... Cheers, mwh -- I'm not sure that the ability to create routing diagrams similar to pretzels with mad cow disease is actually a marketable skill. -- Steve Levin -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html From duduca007 at yahoo.com Fri Sep 5 07:31:49 2003 From: duduca007 at yahoo.com (Carlos Moreira) Date: Fri, 5 Sep 2003 04:31:49 -0700 (PDT) Subject: PYTHONPATH x *.pth??? In-Reply-To: Message-ID: <20030905113149.47967.qmail@web11401.mail.yahoo.com> --- "Martin_v._L?wis" wrote: > - Why is it that you don't want to install the > packages in the default directory? Then, > considering > that reason, why would it be acceptable to > install > a .pth file there? > > - Is it acceptable that users of your application > set > PYTHONPATH? > > - Do you have to consider multiple installations of > Python > > And so on. > Both with be kept indefinitely. Thank you Martin. []?s Cadu __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From jblazi at hotmail.com Sat Sep 20 17:51:30 2003 From: jblazi at hotmail.com (jblazi) Date: Sat, 20 Sep 2003 23:51:30 +0200 Subject: Problems with string and lists (searching and replaceing) References: Message-ID: On Sat, 20 Sep 2003 21:30:37 +0000, Bengt Richter wrote: > For the above, what is wrong with > > >>> def test(): > ... s = 'helo world' > ... print s > ... s = s.replace('helo','hello',1) > ... print s > ... > >>> test() > helo world > hello world Nothing is wrong with that, of course, but my code is something like this: def vergleiche_woerter(eingabe,wort): eing = mysplit(eingabe) wo = mysplit(wort) ergebnis=['-','-','-','-','-'] # Suche zuerst nach Bullen for i in range(len(eing)): if eing[i] == wo[i]: ergebnis[i] = '*' eing[i]=wo[i] = None for i in range(len(eing)): if eing[i] == None: continue if eing[i] in wo: j = wo.index(eing[i]) ergebnis[i] = '.' wo[j] = None return join(ergebnis,'') ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From eric.brunel at pragmadev.N0SP4M.com Wed Sep 24 11:52:10 2003 From: eric.brunel at pragmadev.N0SP4M.com (Eric Brunel) Date: Wed, 24 Sep 2003 17:52:10 +0200 Subject: Python <-> C via sockets References: <8ad2cfb3.0309240113.19d9198a@posting.google.com> <8ad2cfb3.0309240530.19029a98@posting.google.com> Message-ID: Nick Keighley wrote: > Eric Brunel wrote in message news:... > >>Nick Keighley wrote: > > >>>I'm probably missing something rather obvious, but is there a known >>>problem with getting a Python based socket program to communicate with >>>a C based socket program? A simple echo server written in Python >>>(the example from Python in a Nutshell actually) will happily talk >>>to a Python based client. If a C based client is substitued the connection >>>is refused (or so the C client reports). The C client will talk to >>>a C server. >> >>Communications between C and Python via sockets definetly work: we do that >>every day (no kidding ;-) >> >>Can you post an example of your code? > > > well I assumed sockets actually worked I was guessing the slight > differences in the interfaces caused me to set the two ends up > slightly > differently. > > Python Echo Server > ------------------ > import socket > > DEFAULT_PROTOCOL = 0 > PORT = 8702 > > sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM, > DEFAULT_PROTOCOL) > sock.bind (('', PORT)) > sock.listen (5) > > # wait for a connection > try: > while True: > newSocket, address = sock.accept () > print "connected from", address > while True: > receivedData = newSocket.recv (8192) > if not receivedData: > break > print "received: ", receivedData > newSocket.sendall (receivedData) > newSocket.close() > print "disconnected from", address > finally: > sock.close () > --------------------------------------------------------------------- > C echo client (includes omitted) > ------------------------------- > #define DEFAULT_PROTOCOL 0 > #define PORT 8702 > #define HOST "localhost" > /* #define HOST "127.0.0.1" */ > /* #define HOST "cmopc018" */ > #define TYPE SOCK_STREAM > > > int main (void) > { > struct hostent *phe; > struct sockaddr_in sin; > int s; > > s = socket (PF_INET, TYPE, DEFAULT_PROTOCOL); > if (s < 0) > raise_report (LEVEL_FATAL, "tiny_echo", "can't create socket: > %s", strerror (errno)); > > > /* > * connect to the socket > */ > > memset (&sin, 0, sizeof sin); > sin.sin_family = AF_INET; > sin.sin_port = PORT; > if ((phe = gethostbyname (HOST))) > { > memcpy (&sin.sin_addr, phe->h_addr_list[0], phe->h_length); > raise_report (LEVEL_INFO, "tiny_echo", "addr is %X", > sin.sin_addr); > } > else > if ((sin.sin_addr.s_addr = inet_addr (HOST)) == INADDR_NONE) > raise_report (LEVEL_FATAL, "tiny_echo", "can't get \"%s\" > host entry", HOST); > > if (connect (s, (struct sockaddr *)&sin, sizeof sin) < 0) > raise_report (LEVEL_FATAL, "tiny_echo", "can't connect to > %s.%d: %s", HOST, sin.sin_port, strerror (errno)); > > raise_report (LEVEL_INFO, "tiny_echo", "CONNECTED"); > > return 0; > } > ------------------------------------------------------------------------------ After adding the missing htons and replacing the raise_report's by printf's, works like a charm here (Linux Mandrake 8.0 with Python 2.1). What is exactly the error you get? -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From aleax at aleax.it Fri Sep 26 06:03:17 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 10:03:17 GMT Subject: Packages and PyKyra References: <1dCcb.11020$Of2.520042@twister.tampabay.rr.com> <6wCcb.164799$R32.5291608@news2.tin.it> Message-ID: Robert Clayton wrote: > Thank you! > > There are no PyKyra .py, .pyc, .pyd files. > > There is a release PyKyra.dll and a source directory contains a > __init__.py file. > > Trying to use the PyKyra.dll returns: > > "ImportError: dynamic module does not define init function (initPyKyra)" Thus, PyKyra.dll, whatever else it may be, is not a Python extension module named PyKyra. > Therefore I was attempting to define the location of the Package > (directory structure). You need to put the PARENT directory of the PyKyra directory (where the latter is the one containing __init__.py) on sys.path. Simplest is to have a textfile, call it e.g. pykyra.pth, with a single line: c:\the\parent\directory in your site-packages directory (e.g. C:\Python23\Lib\site-packages\). > There is little information about creating path references for Packages in > Windows. I thought I covered .pth files and various alternatives (all cross-platform: why go to platform-specific approaches when cross-platform works fine?) in an adequate fashion in "Python in a Nutshell". Specifically, it seemed to me that the sentences: """ A package named P resides in a subdirectory, also called P, of some directory in sys.path. The module body of P is in the file P/__init__.py. You must have a file named P/__init__.py, even if it's empty (representing an empty module body), in order to indicate to Python that directory P is indeed a package. """ (in section Packages, p. 124) were adequate coverage of THAT issue; and (on p.121, "Searching the Filesystem for a Module"), the sentences: """ If a text file with extension .pth is found in the PYTHONHOME directory at startup, its contents are added to sys.path, one item per line """ (and following), were adequate coverage of THAT one (except that, sigh, the mention of site-packages as a preferable alternative to PYTHONHOME dropped by the wayside -- doesn't even seem to be among the errata, which were fixed in the current [09/03] reprint of which I don't yet have a printed copy). Did you find this coverage unclear, or inadequate? If so, then perhaps you might suggest how to enhance it in a future edition -- thanks! Alex From farmenta at pillardata.com Fri Sep 19 21:43:14 2003 From: farmenta at pillardata.com (Fernando Armenta) Date: Fri, 19 Sep 2003 18:43:14 -0700 Subject: How you chomp in python Message-ID: <36504F2E352484458C5D574719DC8372BAC618@caex01.trans.corp> How you cut off the ^M at the end of a line? rstrip is not working. string.rstrip(build_number) thanks, -F -------------- next part -------------- An HTML attachment was scrubbed... URL: From alleon at club-internet.fr Fri Sep 5 02:26:12 2003 From: alleon at club-internet.fr (Sophie Alléon) Date: Fri, 5 Sep 2003 08:26:12 +0200 Subject: reading large file References: <9bd0dd3f.0309030400.7fa2dc0f@posting.google.com> Message-ID: <3f582c85$0$20942$7a628cd7@news.club-internet.fr> Thanks to your comments, it is now possible to read my large file in a couple of minutes on my machine. Guillaume "Bengt Richter" a ?crit dans le message de news: bj5e61$pjr$0 at 216.39.172.122... > On 3 Sep 2003 05:00:39 -0700, g_alleon at yahoo.fr (guillaume) wrote: > > >I have to read and process a large ASCII file containing a mesh : a > >list of points and triangles. > >The file is 100 MBytes. > > > >I first tried to do it in memory but I think I am running out of > >memory therefore I decide to use the shelve > >module to store my points and elements on disks. > >Despite the fact it is slow ... Any hint ? I think I have the same > >memory problem but I don't understand why > >since my aPoint should be removed by the gc. > > > >Have you any idea ? > > > Since your data is very homogeneous, why don't you store it in a couple of > homogeneous arrays? You could easily create a class to give you convenient > access via indices or iterators etc. Also you could write load and store > methods that could write both arrays in binary to a file. You could > consider doing this as a separate conversion from your source file, and > then run your app using the binary files and wrapper class. > > Arrays are described in the array module docs ;-) > I imagine you'd want to use the 'd' type for ponts and 'l' for faces. > > Regards, > Bengt Richter From dkuhlman at rexx.com Sun Sep 7 17:12:08 2003 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 07 Sep 2003 14:12:08 -0700 Subject: Comments on Python Redesign References: Message-ID: David Eppstein wrote: > Lots of people have been rightly jumping all over the design. But > there's something else that I think is very important in the > current python.org front page and missing from the proposed > redesign: the text "Welcome to the official website for the Python > language." > > If one looks at the proposed redesign, it is difficult to tell > whether Python is an application, a magazine, a business > consulting partnership, > or what. It is also unclear whether the site is run by the same > people > responsible for Python, whatever Python is. Certainly "official > web site for programming language" is not the first thing that > springs to mind. Actually, from its appearance, the new design looks like it is trying to sell me something. "Advert filters up!" It makes me suspicious, skeptical, and cynical, as all advertising does. I don't mean to criticize the work that's being done for the new site. It looks like excellent work. I do mean to suggest that perhaps its style is not what I want for the "official Python site", and, in particular, not for the first/main page. The new design looks great. It looks exceptionally well done. But, instead of the official Python Web site, it would be better suited for "The Python Advisory Board" or for "The Friends of Python" or for whatever organization has the mission of promoting and lobbying for Python. Maybe if the new main page (python-main-2.html) were at the end of a link labelled "Python advocacy" ... And Petter Hansen wrote in a separate message: > (*) Personally, I never thought the existing site was a big problem, > but then I just view the web as a simple way to search for text > and I still use Netscape 4.7 much of the time, so I'm obviously not > the target for these improvements... I think I'm in this school. I go to the Web in general and to the Python site in particular for content, not for graphics. I think the new design is pretty and very attractive, perhaps *too* pretty and attractive. When I send or refer someone to a site like that, I'd feel I'd have to warn them: "It looks like promotional material, but don't be put off; there is really good content there if you look for it. I suppose you could brush me off as old fashioned and "old school". I certainly am. I like text and content not graphics, colors, and visual appeal. But, then I'd argue that text and cognitive content are what's appropriate for the official Python site. The current main page at www.python.org is a portal and a directory. It helps me find things that are related to Python, things that help me with Python, things that I feel will help others to use Python. That's why in much of the Python documentation I write, the current www.python.org is a "must reference". I would not feel the same about a site that contains endorsements from famous people, even nerdy famous people that I admire. I would like to request that the new site, whatever its style, give me as much help as possible finding what I need in order to use Python. I'd want the site designer to look at every piece of that page and ask: Will this help someone find what they need about Python? This new design looks great to me. But, it is not the official Python Web site. It is the site for some company trying to sell Python services or Python tools or something. Look at the Google directory page (http://www.google.com/dirhp). (It's actually built on the ODP: Open Directory Project, dmoz.org). You'll see maximum nutrition and minimum calories. It's very plain, and very popular. People know it will help them find what they want, and they trust it, at least I do. On the other hand, having several pages that show the kind of graphical interface that can be constructed with wxPython, pygtk, etc seems like a good idea to me. Hope I haven't been uncivil. I apologize in advance, if I seem to have been. And, thanks much for the work that the new site designers have done. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman dkuhlman at rexx.com From CousinStanley at hotmail.com Sun Sep 7 09:07:09 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Sun, 7 Sep 2003 06:07:09 -0700 Subject: Comments on Python Redesign References: Message-ID: Tim ... As an alternative to fixed font sizes, you might consider Any Size Design .... http://allmyfaqs.com/cgi-bin/wiki.pl?AnySizeDesign -- Cousin Stanley Human Being Phoenix, Arizona From zeitlin at parthe.lpthe.jussieu.fr Thu Sep 25 16:48:48 2003 From: zeitlin at parthe.lpthe.jussieu.fr (Vadim Zeitlin) Date: Thu, 25 Sep 2003 20:48:48 +0000 (UTC) Subject: unknown charset dialog(wxPython problem) References: Message-ID: On Wed, 24 Sep 2003 22:41:17 +0900, Charlie Kim wrote: > http://gnome.or.kr/gallery/view_photo.php?set_albumName=gnome-apps&id=aks > > Why that dialog box appear whenever run wxPython program? Because wxWindows doesn't know about "EUC-KR" encoding (it should, but it doesn't). > any idea? Normally once you select anything in this dialog it should never appear again as the result is saved. At least this is what happens at wxWindows level, maybe wxPython modifies this. 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 ads at chead.org Mon Sep 15 22:58:06 2003 From: ads at chead.org (ads) Date: Tue, 16 Sep 2003 09:58:06 +0700 Subject: from clipper move to python In-Reply-To: <6.0.0.22.0.20030915085400.041dd200@66.28.54.253> References: <3812075547.20030915130057@chead.org> <6.0.0.22.0.20030915085400.041dd200@66.28.54.253> Message-ID: <801542245.20030916095806@chead.org> Thank you for the respon, But right now I'm still not ready using linux, a lot of my client were using windows. Is someone know what should I use to create text console application like clipper using python in (stupid) windows? Thanks :) --------------- Replied message -------------- The Bat! mailer ver 1.53d ---------------------------------------------- Date : Monday, September 15, 2003 >From : Bob Gailer To : ads Subject : from clipper move to python ---------------------------------------------- At 12:00 AM 9/15/2003, ads wrote: >Hi Everyone, > >I'm starting learning python about 2 weeks, and still have >difficulties to create GUI based application because I never learn >about classes and other OOP things. Does anyone knows how to >create text console application like clipper using python In the Linux world there's the curses module. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 ---------------------------------------------- From rainerd at eldwood.com Sat Sep 27 14:46:22 2003 From: rainerd at eldwood.com (Rainer Deyke) Date: Sat, 27 Sep 2003 18:46:22 GMT Subject: Now that rexec is gone... References: Message-ID: <2Wkdb.599238$YN5.441102@sccrnsc01> Terry Reedy wrote: > Suggest you google last year of c.l.py for 'rexec'. Also check out > py-dev summaries of last fall for discussion of why removed. I see... It turns out that, short of modifying the Python interpreter, there is no way to get real security. '"".__class__' gives access to 'str', 'str' gives access to 'object', and 'object' gives access to 'file'. -- Rainer Deyke - rainerd at eldwood.com - http://eldwood.com From alan.gauld at btinternet.com Tue Sep 9 13:12:43 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Sep 2003 17:12:43 GMT Subject: Python / C: small runtime difference? References: Message-ID: <3f5e0963.369221532@news.blueyonder.co.uk> On Tue, 9 Sep 2003 15:54:41 +0200, "Martin Schneider" wrote: > for i in range(len(fileList)-1): > for j in range(len(fileList)-i-1): > if fileList[j+1] < fileList[j]: > tmp = fileList[j] > fileList[j] = fileList[j+1] > fileList[j+1] = tmp I think you might tweak that by doing: fileList[j],fileList[j+1] = fileList[j+1],fileList[j] which misses out the intermediate tmp assignment. If you are gonna tweak the C you might as well tweak the Python too! (But not with a real python, they tweak back hard! :-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From jjl at pobox.com Tue Sep 16 15:02:58 2003 From: jjl at pobox.com (John J. Lee) Date: 16 Sep 2003 20:02:58 +0100 Subject: None, False, True References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> Message-ID: <877k48y2sd.fsf@pobox.com> "M-a-S" writes: > Can anybody explain this: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information > >>> None = 3 > :1: SyntaxWarning: assignment to None > >>> False = 4 > >>> True = 5 > >>> > >>> None, False, True > (3, 4, 5) I believe there have been discussions about preventing the clobbering of builtins recently, so it may happen in the future (2.4?). Dunno why None and not True / False causes a warning, but you can turn warnings into errors using the warnings framework, I think. John From alan.gauld at btinternet.com Thu Sep 4 02:41:40 2003 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Sep 2003 06:41:40 GMT Subject: Writing solid code book References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> Message-ID: <3f56de81.372851401@news.blueyonder.co.uk> On Wed, 3 Sep 2003 22:00:45 -0600, Jules Dubois wrote: > (3), and Smalltalk (1); Thursday's vote will be between Java and Python. I > get the opportunity to learn one or the other in a week. If you picked Jython you could all be happy! :-) Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From lefevrol at yahoo.com Thu Sep 11 11:24:46 2003 From: lefevrol at yahoo.com (Olivier Lefevre) Date: 11 Sep 2003 08:24:46 -0700 Subject: Invisible function attributes References: <51809ae4.0309030715.7706cadb@posting.google.com> <87he3tfopa.fsf@pobox.com> <51809ae4.0309040627.28d7a075@posting.google.com> <2n16b.18138$hE5.641055@news1.tin.it> Message-ID: <51809ae4.0309110724.7b5f044@posting.google.com> > Python has no declarations, only executable statements. I think this was the key to my confusion in this case. > >>> bar(4) > Traceback (most recent call last): > TypeError: 'int' object has only read-only attributes (assign to .a) The way I read this, it says that a was bound to the name foo, not to the function foo stood for at the time of that function's definition; you are saying as much. Thus "foo.a" has to be looked up and resolved anew for each call. This must be costly. Why was it done this way? OTOH I read the func attr PEP and it says that they are implemented via a dict inside the function object. If so, shouldn't they be bound to the function object rather than to its name?? Or is func_dict itself an attribute? -- O.L. From jjl at pobox.com Wed Sep 17 09:50:00 2003 From: jjl at pobox.com (John J. Lee) Date: 17 Sep 2003 14:50:00 +0100 Subject: How to make URLLIB .urlopen(url1) .urlopen(url2) session related ? References: <8f41cfd.0309130423.22054528@posting.google.com> <3F631C0C.2AAA08CF@engcorp.com> <87vfrw9u23.fsf@pobox.com> <8f41cfd.0309170440.caa80ff@posting.google.com> Message-ID: <87oexjzfqv.fsf@pobox.com> xucs007 at yahoo.com (Xu, C.S.) writes: > ClientCookie works great with ebay, and a few other sites I'm interested. > > I'd like to donate a few bucks for the author to buy several cups of > coffee during writing more interesting python modules. Where should I > send the money to? Paypal, or check? [...] Rest assured my postal address will quickly find its way to you! :-)) John From tim at worthy.demon.co.uk Wed Sep 24 02:58:26 2003 From: tim at worthy.demon.co.uk (Tim Howarth) Date: Wed, 24 Sep 2003 07:58:26 +0100 Subject: CGI Redirect to another page References: Message-ID: <09a3d6364c.tim@worthy.demon.co.uk> In message "Andrew Chalk" wrote: > In a Python script running under CGI, can I programatically redirect the > program to another page. Do you mean redirect the client browser ? > Assume that I have a static HTML page that I want displayed (e.g. > index.htm). Other than 'print ...' is there any way to redirect to this > URL (for example, like Response.Redirect() in ASP)? Assuming you mean not to print the whole page, when you say "Other than 'print ...'" then; print "Location: http:abcxyz.index.html" AFAIUI it simply sends a redirect header. -- ___ |im ---- ARM Powered ---- From grante at visi.com Thu Sep 25 22:54:19 2003 From: grante at visi.com (Grant Edwards) Date: 26 Sep 2003 02:54:19 GMT Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: In article , Stephen Ferg wrote: > When did Windows start accepting the forward slash as a path separator > character? Sometime prior to 1983. DOS has always accepted it, and I assume Windows always has as well. > At one time, it was accepted as a truism that Windows (like MS-DOS) > was different from Unix because Windows used the backslash as the path > separator character, Accepted as a truism by whom? DOS would accept either. The shell's "switch" character was configurable as well -- it defaulted to '/' but changing it to '-' was trivial. > whereas Unix used the forward slash. > But now, among a small group of cognoscenti, it is a truism that this > is a myth, and that Windows will allow you to use either the forward > or the backward slash as a pathname separator. I don't remember if the actual DOS system calls accepted '/' or if the C library translated. I do know that DOS C programs could use '/' for path separator at least 20 years ago. > I hypothesize that originally Windows accepted only the backslash, and then > at some time it changed to accept the forward slash as well. Nope. AFAIK, it's always accepted '/'. I did C programming on DOS for years, and I always used '/' since it was too error working with string literals in C that contain '\'. Those same programs seemed to run fine under Windows. > Does anyone know when that change occurred? Was it with the introduction of > support for long filenames in NT and Win95? I'm not aware that there has ever been a "change". '/' has been OK since the early DOS days. -- Grant Edwards grante Yow! WHOA!! Ken and at Barbie are having TOO visi.com MUCH FUN!! It must be the NEGATIVE IONS!! From aleax at aleax.it Tue Sep 30 09:47:15 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 30 Sep 2003 13:47:15 GMT Subject: Prime number module References: <7b4hnvgplqk6g1d5vig0dsdvic1ru62r4e@4ax.com> Message-ID: Tim Hochberg wrote: ... > I believe you could implement a hybrid scheme that would be quite fast > and still maintain nearly the same level of compression that you > describe above. In addition to the above compressed data, also store, > uncompressed, every Nth prime. A binary search will get you within N > primes of your answer, to find the exact value, recreate those N-primes. > For a N of, for instance, 64 the level of compression would be minimally > affected but should make finding the number of primes less than a given > number number much faster than the basic compressed scheme. Still thinking of gmpy's primitives, I came up with a variant of this...: import gmpy import array import bisect highest_number_of_interest = gmpy.mpz(100*1000*1000) def make_primes(put_them_here, every=1000): current_prime = gmpy.mpz(put_them_here[-1]) count = 0 while current_prime < highest_number_of_interest: current_prime = current_prime.next_prime() count += 1 if count == every: put_them_here.append(int(current_prime)) count = 0 try: savefile = open('primes.dat', 'rb') except: every_1000th_prime = array.array('l', [1]) make_primes(every_1000th_prime) savefile = open('primes.dat', 'wb') every_1000th_prime.tofile(savefile) savefile.close() else: every_1000th_prime = array.array('l', []) try: every_1000th_prime.fromfile(savefile, 6000) except EOFError: pass else: warnings.warn("Only %d primes (?)" % len(every_1000th_prime)) warnings.warn("Highest is %d" % every_1000th_prime[-1]) # could fill out and re-save the array here, if needed savefile.close() print "%d primes stored (1 every 1000), highest is %d" % ( len(every_1000th_prime), every_1000th_prime[-1]) def nth_prime(N): N_div_1000, N_mod_1000 = divmod(N, 1000) try: prime = every_1000th_prime[N_div_1000] except IndexError: raise ValueError, "must be N<%d" % (1000*len(every_1000th_prime)+999) prime = gmpy.mpz(prime) for x in xrange(N_mod_1000): prime = prime.next_prime() return int(prime) print "55555th prime is", nth_prime(55555) import bisect def primes_upto(N): if N>highest_number_of_interest: raise ValueError, "must be N<%d" % highest_number_of_interest x = bisect.bisect_left(every_1000th_prime, N) if N == every_1000th_prime[x]: return x*1000+1 prime = gmpy.mpz(every_1000th_prime[x-1]) x = (x-1)*1000 while prime < N: x += 1 prime = prime.next_prime() if prime == N: x += 1 return x print "Up to 555555, there are %d primes" % primes_upto(555555) The first run, building the file primes.dat (just 23048 bytes), took almost 7 minutes elapsed time on my machine (250 CPU seconds). But any successive run is extremely fast: [alex at lancelot perex]$ time python -O prio.py 5762 primes stored (1 every 1000), highest is 99991609 55555th prime is 686671 Up to 555555, there are 45741 primes 0.06user 0.00system 0:00.14elapsed 41%CPU (0avgtext+0avgdata 0maxresident)k 0inputs+0outputs (494major+297minor)pagefaults 0swaps [alex at lancelot perex]$ I've coded this rapidly and sloppily, so I wouldn't be surprised if there were off-by-one errors here and there (needs to be checked against some other, independent way to generate/check primes!), but I think the fundamental ideas are sound. Alex From stuff at slinkp.com Tue Sep 16 17:25:16 2003 From: stuff at slinkp.com (Paul Winkler) Date: 16 Sep 2003 14:25:16 -0700 Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> Message-ID: vivek at cs.unipune.ernet.in wrote in message news:... > On Fri, Sep 12, 2003 at 06:09:02AM -0700, Ubaidullah Nubar wrote: (snip) > > 4. What types of applications are not suitable to be written in > > Python? > > > > System side softwares I don't know what "system side softwares" means... The one real drawback that comes up a lot when discussing python is speed, since it's quite a lot slower than C. Usually that's actually not a problem. When speed matters, good results can be had by A) profiling and fixing your algorithms, B) using psyco, C) replacing slow pure-python stuff with third-party C extensions, D) replacing any remaining slow pure-python slow stuff with your own C extensions. However, there is at least one case when that's not likely to be enough. An application that has critical realtime deadlines should probably not have the python interpreter running in the realtime part. Example, realtime DSP. Say you're processing audio in a live performance setting. If the interpreter decides to do a bunch of garbage collection or otherwise slows down for a moment, you could easily miss a deadline and get very nasty dropouts in the output. Even in this case, python can be a useful part of the application as long as the interpreter is kept away from the time-sensitive parts of the app. Here's a REALLY cool project with a C DSP engine controlled by the movement of physical objects whose movements are detected and refleted by a Python / OpenGL UI: http://web.media.mit.edu/~jpatten/newaudiopad.html From p.useldinger at myrealbox.com Thu Sep 11 14:20:22 2003 From: p.useldinger at myrealbox.com (Patrick Useldinger) Date: Thu, 11 Sep 2003 20:20:22 +0200 Subject: mod_python installation Message-ID: Hi, I have the following configuration: - Apache 2.0.47 (win32) - mod_python 3.0.3 win32 - python 2.3 I have added the loadModule command for mod_python: "LoadModule python_module modules/mod_python.so", and the file is there. Apache won't start anymore. No error message is in Apache's log file. Uncommenting the loadModule command makes apache start correctly. Where can I get more information regarding the origin of the problem? -PU From rjc at tampabay.rr.com Thu Sep 25 09:38:05 2003 From: rjc at tampabay.rr.com (Robert Clayton) Date: Thu, 25 Sep 2003 13:38:05 GMT Subject: Packages and PyKyra Message-ID: <1dCcb.11020$Of2.520042@twister.tampabay.rr.com> In the PyKyra example programs what does the statement: "from PyKyra import *" I now assume that this represents a Package hierarchy and not the file "PyKyra.py" as there is none but for Windows 2000 I am unable to determine whereor how the path is represented (registry, environment, etc.). Any suggestions? Thanks, Bob From ajsiegel at optonline.net Mon Sep 1 01:33:17 2003 From: ajsiegel at optonline.net (Arthur) Date: Mon, 01 Sep 2003 01:33:17 -0400 Subject: artificial intelligence Message-ID: <000501c3704a$8c58da70$0c02a8c0@Arts> >Maybe there was some notice about using Python in >geophysic and the symposium book in one journal, so there was a sudden >spat of, say, three people who bought both. You would think the parameter for a statistically significant sample size would be a fundamental concept in this kind of thing. And no action taken before one was determined to exist. OTOH, the concept of "coincidence" must necessarily be ruled out in AI, I would think. *Our* intelligence seems to give us a read as to where on the bell curve a particular event may lie, or a least some sense of when we are at an extreme on the curve. Which we call coincidence. AI would probably have a particularly difficult time with this concept - it seems to me. Spam filtering software must need to tackle these kinds of issues. Art From essai1 at mci.local Sat Sep 6 04:17:57 2003 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Sat, 6 Sep 2003 10:17:57 +0200 Subject: just curious References: Message-ID: Hi ! In def g(a,b): a=a+b a new object "a" is create ; but it's a local object, who are not the "a" global. In python, variables are "pointer to object". If you try : def g(a,b): global a a=a+b You obtain : "name 'a' is global and local" @-salutations -- Michel Claveau From fgeiger at datec.at Tue Sep 23 01:44:58 2003 From: fgeiger at datec.at (F. GEIGER) Date: Tue, 23 Sep 2003 07:44:58 +0200 Subject: Mailbox cleaner on an IMAP basis? References: <3f6f2cfb@news.swissonline.ch> Message-ID: <3f6fdd8e@news.swissonline.ch> Well, John, I've stopped here, because I could not figure out how to get at the ids of mails with attachments. And if I had that missing link, I'd run into the next hindrance: How can I delete a single message? IMAP4::delete() deletes a whole mailbox, not just a single mail. So my code really is only a few lines so far: i = IMAP4(myDomain) i.login(myUser, myPassword) i.select() # Select INBOX r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])") # Check 1st mail Seems I have to get a book about IMAP and how to use it... Kind regards Franz "John Roth" schrieb im Newsbeitrag news:vmuhsrr68tlj27 at news.supernews.com... > > "F. GEIGER" wrote in message > news:3f6f2cfb at news.swissonline.ch... > > Hi all! > > > > As I saw Alex Martelli's post about a mbox cleaner based on POP3, I > thought, > > it could be possible to do that based on IMAP too. That way I could ask > the > > server for mails having attached EXE files and delete all those mails on > the > > server. This would save me a lot of traffic over my phone line connection. > > > > But I'm missing one important thing: How do I get the server to tell me > > about attachments. > > > > What I've found out so far is how to get at the fields: > > > > r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])") > > > > Alas, there's no such thing like 'filename' or 'attachments'. > > > > And > > > > r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS (Content-type)])") > > > > doesn't show a file name either. > > > > Any hints? > > Right now, I'd simply like something that would clean out an > IMAP mailbox on a regular basis. Most of the worm generated > garbage is going into one of two boxes on my server, and I get maybe > one legitimate e-mail in those two boxes every couple of weeks. > I can stand to lose that level of e-mail, I can't stand to exceed my disk > quota and lose lots of legitimate mail every few hours. > > Could you post the code you've got so far? > > Thanks. > > John Roth > > > > Best regards > > Franz GEIGER > > > > > > > > > > > > From edho at nospam.stanford.edu Tue Sep 2 02:19:13 2003 From: edho at nospam.stanford.edu (Edmond Ho) Date: Mon, 1 Sep 2003 23:19:13 -0700 Subject: curses! trouble with pads and panels Message-ID: Hi, I'm having trouble with a small curses program. I'm associate a pad with a panel. As I understand, a pad is supposed to be just a window with an arbitrary size. That seems to imply that a pad can be treated like a normal window when working with panels. I have this code: #!/usr/bin/env python import curses import curses.panel curses.initscr() curses.cbreak() curses.noecho() pad = curses.newpad(100, 100) win = curses.newwin(1, 80, 0, 0) padp = curses.panel.new_panel(pad) winp = curses.panel.new_panel(win) curses.panel.update_panels() curses.doupdate() pad.getch() curses.endwin() If you comment out the line 13 (where padp is declared), the program is fine, albeit useless. But with the line 13, I get this error: Traceback (most recent call last): File "pad.py", line 13, in ? padp = curses.panel.new_panel(pad) _curses_panel.error: curses function returned NULL So, what am I doing wrong? cheers, ed From newsgroups at jhrothjr.com Fri Sep 19 15:43:03 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 19 Sep 2003 15:43:03 -0400 Subject: How do I learn operator overriding? References: Message-ID: wrote in message news:mailman.1063995987.26144.python-list at python.org... > Hi- > > > I need to make a class for quartlerly dates. I need to be able to compare > two quarterly dates and get the number of quarters between them. For > example: > > >>> 2001q1 = qDate(year=2001, quarter=1) > >>> 2001q4 = qDate(year=2001, quarter=4) > >>> 2001q4 - 2001q1 > 3 > > The only problem is that I have no idea how to override operators in > python. Can anyone give me a few trivial examples of how it is done? Operators are special methods that start and end with two underscores. Look in either the library or the language manual; you'll find all you need to know there. For example, generic compares use the __cmp__() method. There are also extended compares. > And, on a completely unrelated note, I am getting a truly amazing amount > of spam today. Anyone else? A new mass mailer worm hit the net at about 9:00 PM EST last night (at least, that's when I started getting the spam from it.) It seems to be using a really old hole in Windows, meaning that if you've kept up to date with your patches, you should be safe from infection. At least, that's the information I have to date. I put my "junk" folder on auto delete to protect my mailbox, and that's it. Also of note is that one of the addresses in the header *isn't* spoofed, so there's a clear back track to the infected machines. I haven't verified this myself, though. John Roth > > > Thanks for the help. > From tonym1972/at/club-internet/in/fr Mon Sep 15 03:58:50 2003 From: tonym1972/at/club-internet/in/fr (Anthony McDonald) Date: Mon, 15 Sep 2003 09:58:50 +0200 Subject: problems with threaded socket app References: Message-ID: <3f656f76$0$20942$7a628cd7@news.club-internet.fr> "Gordon Messmer" wrote in message news:pan.2003.09.14.23.17.52.205571 at dragonsdawn.net... > I've been working on a threaded daemon application to filter email. The > source for the program is here: > > http://phantom.dragonsdawn.net/~gordon/courier-patches/courier-pythonfilter/ > > The daemon loads individual filters as modules and hands the names of the > message and control files to each module in turn for processing. One of > the modules (filters/dialback.py) checks the address of the sender, > connects to the MX servers for the senders domain, and validates that the > sender address is valid. In order to implement a timeout on the dialback, > each message is processed by two threads. The first thread creates an > SMTP object and then starts a second thread to do the lookup using that > SMTP object. If the lookup takes too long, the first thread closes the > SMTP object's socket and collects the failure from the second thread. > > During testing, that all works fine. However, in real world use, the > program eventually deadlocks. When it does so, there are several dialback > threads in process, and the first of each pair seems to be reading from > the status pipe. I cannot connect a debugger to the second of the pair to > see what state it's in. > > I'm running this application on python2-2.2.2-11.7.3 under Red Hat Linux > 7.3. > > Does anyone have any suggestions for where I can start looking for the > problem? > if rpipe not in ready_pipes[0]: # Time to cancel this SMTP conversation smtpi.close() # The dialback thread will now write a failure message to # its status pipe, and we'll need to clear that out. os.read( rpipe, 1024 ) continue The code creates a "race" condition. To work correctly it requires the worker thread to raise and handle an exception, and to write that result onto the pipe BEFORE your main thread attempts to read the pipe. If the worker thread loses the race, the next MX result you process will recieve the last MX's results 400 error code, and your left with 1 thread at the end of the sequence which can't terminate as it stays active until what its written to the pipe is read from the pipe. Simple enough to fix, just add a select call between closing the SMTP connection and reading the expected 400 error response. Anthony McDonald From edreamleo at charter.net Tue Sep 30 04:29:27 2003 From: edreamleo at charter.net (Edward K. Ream) Date: Tue, 30 Sep 2003 03:29:27 -0500 Subject: A startup puzzle References: Message-ID: > Fair enough, but it's not just a matter of style... using something like > > import leoGlobals as g > > would probably have avoided this problem... True! However, I must then change every reference x to a function in leoGlobals to g.x. This is what I want to avoid. Being able to go from app().x to app.x is a very small improvement: I want to avoid a corresponding very small step backwards. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From tanzer at swing.co.at Fri Sep 19 03:18:40 2003 From: tanzer at swing.co.at (Christian Tanzer) Date: Fri, 19 Sep 2003 09:18:40 +0200 Subject: was: Re: looking for MOP documentation In-Reply-To: Your message of "Thu, 18 Sep 2003 12:40:11 EDT." <3F69DFEB.5B05CED8@engcorp.com> Message-ID: Peter Hansen wrote: > Alan Kennedy wrote: > > > > Peter Hansen wrote: > > > Key phrase: "Metaobject protocols are interfaces to the language > > > that give users the ability to incrementally modify the language's > > > behavior and implementation...". Near as I can tell, part of the > > > whole character of Python is that a user *cannot* do either of > > > those things. > > > > Hmm, does this rephrasing hold any truth? > > > > "Metaclasses are interfaces to the python language > > that give users the ability to incrementally modify the language's > > behavior and implementation...". > > > > Isn't modifying standard behaviour the whole purpose of metaclasses? > > But it doesn't really modify the *language's* behaviour in the way > implied by a simplistic reading of the above phrase. That is, the > "obvious" interpretation is that syntax and grammar are being affected, > not just the behaviour of one small slice of the language, specifically > how classes behave. In some languages the two things are not so > separate, but in Python they seem to be. Are you sure? Python 2.2.3 (#1, Jun 18 2003, 15:54:07) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Nasty(type) : ... def __new__(cls,name,bases,d): ... return 1 ... >>> class Surprise(object): ... __metaclass__ = Nasty ... >>> Surprise 1 >>> type(_) >>> Ducks-and-runs, -- Christian Tanzer tanzer at swing.co.at From jim-usenet at jimdabell.com Wed Sep 3 11:04:02 2003 From: jim-usenet at jimdabell.com (Jim Dabell) Date: Wed, 03 Sep 2003 16:04:02 +0100 Subject: Code complete electronic version ? References: Message-ID: <-aOdndgss-MVnsuiRVn-vg@giganews.com> A.M. Kuchling wrote: > On Wed, 03 Sep 2003 13:40:48 +0100, > Jim Dabell wrote: >> If it's too much, buy it second-hand. It's a good book, and although >> plenty of it is just common sense, it's the type of common sense that's >> easy to miss :) > > Isn't it mostly concerned with C, though? Ah, forgot which group I was in for a minute :). It does give plenty of examples in C, and a lot of the issues discussed don't apply to Python, but then again, there are plenty that are universal, like good coding habits, project management, and so on. > McConnell's _Rapid Development_ is pretty good, though, and examined the > development process more than language-related things. In a similar vein, if you want to focus on the project management side, Peopleware and the Mythical Man-Month are good reads, and if it's more software architecture you are after, then go for Design Patterns, Refactoring or Antipatterns. -- Jim Dabell From tad at tadland.net Mon Sep 8 23:34:12 2003 From: tad at tadland.net (Tad Marko) Date: 8 Sep 2003 20:34:12 -0700 Subject: PyGTK and fonts Message-ID: Howdy! I'm pretty new to both Python and PyGTK (about 10 hours at this point), so please forgive me if this question has already been answered somewhere. Basically, I've got a small program with a GtkTextView and I'd like to change the font to a monospaced font. Preferably the default monspace font for Gnome 2. Can anyone show me the steps necessary to programatically change the font on the text view? Thanks for any help! Tad From cookedm+news at physics.mcmaster.ca Sun Sep 21 18:29:08 2003 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Sun, 21 Sep 2003 18:29:08 -0400 Subject: Server-side programming References: <3F6DCCEA.763D17C6@hotmail.com> Message-ID: At some point, Alan Kennedy wrote: > Timo Virkkala wrote: >> I'm creating a system with Python CGIs, that connect to a database. I'm >> wondering about input validation. Of course I will check the length of >> the passed parameters, to (hopefully) prevent any DOS attacks. What else >> do I need to check? Do I need to remove any SQL from the inputs? >> Anything else I might have overlooked? > > You might not need to remove SQL from your field values. Doing so > would probably be a non-trivial string parsing exercise. > > Most "SQL injection" attacks would be where a cracker hopes that you > are going to embed the contents of "username" and "password" fields > right into a string containing an SQL query, like so > > mySQLString = """ > select * > from users > where uname = "%s" and password = "%s" > """ % (username, password) > > If the query returns a non-zero number of rows, then that > username/password combination is deemed to be valid. > [snipped useful info on doing SQL injections] > AFAIK, the most effective way to prevent such attacks is to disable > any quote characters that may be present in the password, so that they > are treated as a part of the password string, not as delimiters in the > SQL query string. For example > > import re > password = re.escape(password) > > Which for the values given above would now give an SQL query of > > select * > from users > where uname = "alan" and password = "\"\ or\ 0\=0\ or\ password\=\"" > > Does anyone know of a more effective approach to preventing SQL > injection attacks? The problem is you're trying to create the entire query string. This means that *you* must be sure what is valid and what's invalid; what needs quoting, and what doesn't. Are you sure the above using re.escape will work properly for SQL queries, since it was designed for regular expressions? Are all corner cases covered? etc. The best way to do this is to allow the database module to do the quoting; this is explicictly supported by Python's DB-API v2 specificiation (available as PEP 246 [1]). Most (if not all that you'll probably use...) database modules for python conform to this. Here's a concrete example using PySQLite: [untested code] import sqlite db = sqlite.connect('database.db') cursor = db.cursor() cursor.execute('''select * from users where uname = %(uname)s and password = %(password)s''', {'uname' : uname, 'password' : password}) row = cursor.fetchone() if row is None: print "Access denied" Note how the parameters are passed as separate arguments to cursor.execute; the sqlite module takes care of escaping them. Note that not all database modules support this style of quoting; check out PEP 249 and the documentation of your specific module. [1] http://python.org/peps/pep-0249.html -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From hjwidmaier at web.de Wed Sep 17 06:51:34 2003 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: 17 Sep 2003 03:51:34 -0700 Subject: testing the data-type of a stream References: Message-ID: <6e990e29.0309170251.27ed85de@posting.google.com> David Bear wrote in message news:... > I'm writing a filter and would like to be able to do what the Linux > 'file' command does, i.e. look at a couple of bytes to see what kind of > data I'm dealing with, the branch based on the type. > [...] > any recommendations? You might want to take a look at 'magic' http://www.demonseed.net/~jp/code/magic.py> Reading a few bytes from a file and passing them on is considered trivial and left as an exercise. ;-) Hans-J. From eppstein at ics.uci.edu Sun Sep 21 14:13:47 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 21 Sep 2003 11:13:47 -0700 Subject: None??? References: <3F6D68AA.9070603@aon.at> Message-ID: In article <3F6D68AA.9070603 at aon.at>, Gregor Lingl wrote: > >>def compute(income, percent): > >> result = income*percent/100 > >> print result > > > Additionally please notice, that your program will produce > incorrect and probably at first irritating results: ... > This comes from using integer-constants together with > inputting integers, which causes the /-operator to > perform integer division. Arguably, any code that uses / with integer arguments is now buggy, because it will produce different results in different Python versions. You should either use // (integer division) or force floating point division (e.g. by changing the expression to income*percent/100.0). -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From creedy at mitretek.org Thu Sep 25 17:20:17 2003 From: creedy at mitretek.org (Chris Reedy) Date: Thu, 25 Sep 2003 17:20:17 -0400 Subject: Fastest way to get thousands of db records to client in 3 tier? In-Reply-To: References: Message-ID: <3f735cb8$1_6@corp.newsgroups.com> R. Alan Monroe wrote: > Subject says it all... what's the fastest way to get many thousands of > records to the client? > > I'm trying to sketch out a traditional 3 tier client-server system. > Multiple clients would make requests to the server. The server should > execute sql select commands against a server-side database, then > return the results to the client. > > I tried the standard xmlrpclib and SimpleXMLRPCServer tools that came > with Python. I liked the simplicity, but it was about 30-35 times > slower than executing the sql directly from the client... > > I intend to write both client and server in Python, and my main goal > in the first cut is speed. Suggestions? > > Alan I suspect that it will be difficult for you to match the speed of using sql to do direct record retrieval from the client. People who build databases spend a lot of time and effort making this work as fast as they can because of its impact on overall database performance. My suggestion: You need to think harder about your performance versus functionality trade-offs. E.g., if you're not moving too many records and the server isn't heavily used, you shouldn't care about the extra overhead. On the other hand, if you're moving a lot of records _and_ the server is heavily used, then you're trying for bleeding edge performance and you should either expect to spend a lot of time making ugly compromises in order to meet your requirements or to spend money buying a bigger server and more communications bandwidth. Chris -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From davecook at nowhere.net Wed Sep 17 07:25:04 2003 From: davecook at nowhere.net (David M. Cook) Date: Wed, 17 Sep 2003 11:25:04 GMT Subject: GTK help References: Message-ID: In article , ads wrote: > I use PYGTK 2.0.0 for python 2.3 and GTK Runtime 2.2.4 under windows98 It's works here under win98 with python 2.2, pygtk 1.9.16 and Tor Lindquist's 2.2.3 package. So maybe there's an issue with python2.3 and the latest version of pygtk. I suggest posting the problem to the pygtk mailing list, or making a bug report at bugzilla.gnome.org: http://www.daa.com.au/mailman/listinfo/pygtk http://tinyurl.com/nnsn Dave Cook From logistix at cathoderaymission.net Mon Sep 15 15:08:39 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 15 Sep 2003 12:08:39 -0700 Subject: Win32 Com + ADO: How to compare the result of a recordset to 'nothing' References: Message-ID: <3c91a864.0309151108.5597753d@posting.google.com> "Felix McAllister" wrote in message news:... > Hi, > When using win32com.client, how do you test for a 'nothing' com object as you can in VB? I have an example here when using ADO to loop over multiple recordsets returned from a query. I get the following error: > > Traceback (most recent call last): > File "C:\dev\python\MySamples\dbtest.py", line 14, in ? > rs.MoveFirst() > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 460, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: .MoveFirst > > I'm assuming that after the result of rs.NextRecordSet is invalid somehow (it shouldn't be, BTW, as a similar loop runs fine in VB). > > In Perl, I'd just use : if (defined($rs).... > > Any help appreciated, > > Felix. > > The code is as follows: > ###########################3 > import win32com.client > conn = win32com.client.Dispatch("ADODB.Connection") > conn.ConnectionString = "Driver={SQL Server};Server=(local);Database=Test;Trusted_Connection=yes;" > conn.Open() > rs = conn.Execute("TestSPXML")[0] > xmlString = "" > while rs != None: > rs.MoveFirst() # FAILS HERE ON THE SECOND ITERATION OF THE LOOP > while not rs.EOF: > xmlString = xmlString + rs.Fields[0].Value > rs.MoveNext() > rs = rs.NextRecordSet() > print xmlString > conn.Close() Recordsets have a .BOF property that is similar to .EOF, but indicates that your cursor is before the first record. If both .BOF and .EOF are true, you have a null recordset. So something like: if not(rst.BOF and rst.EOF): rst.MoveFirst() should work. From bh at intevation.de Mon Sep 29 08:48:54 2003 From: bh at intevation.de (Bernhard Herzog) Date: Mon, 29 Sep 2003 14:48:54 +0200 Subject: extension call backs and the GIL References: Message-ID: <6q4qyvep55.fsf@salmakis.intevation.de> Robin Becker writes: >>You need to reacquire the GIL prior to making the callback. > So does calling an extension release the GIL? No. It would be very inconvenient if it did because what most functions do first is to call one of the PyArg_ParseTuple functions which could execute arbitrary python code. I think it would help if you described a bit more what the actual problem is or what the user does. I looked briefly at the sources and assuming tha the accelerator in question is lib/_rl_accel.c and the callback whatever has been assigned to _SWRecover, could it be that the problem is that your user tries to use different callbacks in different threads? _SWRecover is a global after all and shared by all threads. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ Thuban http://thuban.intevation.org/ From p-abel at t-online.de Thu Sep 11 15:35:03 2003 From: p-abel at t-online.de (Peter Abel) Date: 11 Sep 2003 12:35:03 -0700 Subject: Debug python programs References: Message-ID: <13a533e8.0309111135.65b01408@posting.google.com> Jeremy Jones wrote in message news:... > * York (yorklee70 at yahoo.com) wrote: > > Hi, anybody, > > > > Would you please recommend some good softwares/methods for > > tracking/debugging python codes. > > > > Thanks, > > York > > You've got lots of options. > > 1) Your standard insertion of "print" statements throughout the code. A > lot of times, this is good enough to get the job done. I typically set an > instance variable named DEBUG for each class that I create (in __init__, > set self.DEBUG = 0 or 1). Then I have lots of > if self.DEBUG: > print "whatever" #insert debug statements here > It's not the most elegant thing, but man, has it come in handy when you > don't need a full-blown debugger. (Segue into number 2) > > 2) Python comes with a pretty good debugger built in. Here are the docs: > http://www.python.org/doc/current/lib/module-pdb.html > > 3) pychecker. I know, I know, I know - it's not a debugger. But if you > point it at your code, it'll inspect it and can help you uncover some > mistakes that can bite you in the rear. > > 4) trace.py. Never used it, but it's in the standard distribution now > under Tools/scripts. (I'm including this line item since you mentioned > "tracking". I guess this is what you mean?) > > HTH > > > Jeremy Jones Try boa: http://boa-constructor.sourceforge.net/ At the moment it is "Project of the month: Boa Constructor" at http://sourceforge.net/potm/potm-2003-08.php Regards Peter From newsgroups at jhrothjr.com Tue Sep 9 19:33:45 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 9 Sep 2003 19:33:45 -0400 Subject: virtual inner classes in python? References: <3F5E54DF.8ED73922@engcorp.com> Message-ID: "kasper graversen" wrote in message news:opru88weos5j9jb9 at news.tiscali.dk... > On Tue, 09 Sep 2003 18:31:59 -0400, Peter Hansen wrote: > > > now, since you are confused(?) with my code posting, how should I go about > posting python code the next time I want to do so? Use spaces, not tabs. A fairly large number of newsreaders do not handle tabs correctly. The general python recommendation is to always use spaces for indentation, never tabs and absolutely never mixtures of spaces and tabs. Most python aware editors can be set up to use spaces conveniently. John Roth > > -kasper From tjreedy at udel.edu Wed Sep 17 10:17:56 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Sep 2003 10:17:56 -0400 Subject: why pass statement? References: Message-ID: "JCM" wrote in message news:bk9oel$4mu$1 at ginger.mathworks.com... > M-a-S wrote: > > Why is there the pass statement? I think, the expression statement would be enough: > > > class C: > > None > > > while True: > > None > > Because emacs python-mode knows to dedent the next line after a pass :) Nice. pass is the guaranteed-to-do-nothing identity statement (function operating on the interpreter state). def f(): pass generates a *miminal* function object with a *minimal* code object. This is at least potentially useful for testing or investigating the implementation. The alternative of an expression statement adds code to the code body. The alternative of a doc string generates a string object attached somewhere to the no-longer-minimal function or code object. Indeed, the way to test the effect of either alternative is to start with the minimum and then define f2 and look for the difference -- as one of the earlier posters in this thread did do (using dis module to 'look') for the None expression. Terry J. Reedy From newsgroups at jhrothjr.com Wed Sep 17 10:52:59 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 17 Sep 2003 10:52:59 -0400 Subject: Graphic python debugger References: <20030917120146.3c5202e2.max@fr.fm> Message-ID: "Maxime Biais" wrote in message news:20030917120146.3c5202e2.max at fr.fm... > Hello, > > I'm looking for a graphic debugger for python on linux like DDD or GVD. > I tried pdb and pdb-mode for emacs, but I would use a more gvd-like > debugger. >From the description: GNU DDD is a graphical front-end for command-line debuggers such as GDB, DBX, WDB, Ladebug, JDB, XDB, the Perl debugger, or the Python debugger. ^^^^^^ John Roth > > -- > Maxime Biais From stephan.diehl at gmx.net Thu Sep 4 12:24:58 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Thu, 04 Sep 2003 18:24:58 +0200 Subject: basic language question Message-ID: Once in a while, I get bitten by the fact, that mutating list methods such as 'append' or 'extend' return None instead of the (mutated) list itself. Is there a compelling reason for that? I googled around, but didn't find anything about this. Thanks Stephan From bogus at invalid.tld Tue Sep 23 01:22:44 2003 From: bogus at invalid.tld (Jules Dubois) Date: Mon, 22 Sep 2003 23:22:44 -0600 Subject: "Protected" property in Python? Message-ID: <1rgll5pslncci.1iu0qs9ekf45q.dlg@40tude.net> I'm want to create a superclass with nothing but attributes and properties. Some of the subclasses will do nothing but provide values for the attributes. (I'd also like to make sure (1) that the subclass provides actual values for the attributes and (2) that no "client" module adds or removes attributes or properties, but I don't know how to do those.) I don't understand what I'm doing wrong, or maybe what I want to do is impossible. Here's a stripped down version of the code: ---------------------------------------------------------------- #! /usr/bin/python class SuperClass(object): def __init__(self): self.__statusCode = "value bound in SUPERCLASS" getStatusCode = property(lambda self: self.__statusCode) class SubClass(SuperClass): def __init__(self): # SuperClass.__init__(self) self.__statusCode = "value bound in SUBCLASS" if __name__ == "__main__": s = SubClass() print s.getStatusCode ---------------------------------------------------------------- If I run this program, I get an exception (output wrapped by hand): Traceback (most recent call last): File "./xxx.py", line 14, in ? print s.getStatusCode File "./xxx.py", line 5, in getStatusCode = property(lambda self: self.__statusCode) AttributeError: 'SubClass' object has no attribute \ '_SuperClass__statusCode' Why is the lambda function attempting to access the superclass' attribute and not the subclass' attribute? Can I make it not do that? If I replace "__statusCode" with "_statusCode", the output is value bound in SUBCLASS as I want. However, "_statusCode" is then visible from the outside, as I don't want. Am I missing something about how Python works? Is my problem more fundamental, like not understanding OO programming? I'm able to RTFM if someone would provide a pointer. From stephane at harobed.org Mon Sep 1 18:28:41 2003 From: stephane at harobed.org (Harobed) Date: Tue, 02 Sep 2003 00:28:41 +0200 Subject: error when xml.dom parse file encoded in ISO-8859-15 Message-ID: >> Harobed writes: >> I have a xml file encode in ISO-8859-15. When xml.dom parse this file, it >> send this error : xml.parsers.expat.ExpatError: not well-formed (invalid >> token): line 9, column 46 >> >> Line 9 content some accent char. I would like solve this error. >You should correct the error in your XML file, by adding an xml header >to it. >Regards, >Martin I've adding this line to my xml file source. Now, the parser work perfectly. Thanks you From davecook at nowhere.net Wed Sep 17 05:23:31 2003 From: davecook at nowhere.net (David M. Cook) Date: Wed, 17 Sep 2003 09:23:31 GMT Subject: GTK help References: Message-ID: In article , ads wrote: > I need some help, whe trying to run some gtk examples, show below > messages: [...] > store = gtk.ListStore(StockItemInfo) > TypeError: could not get typecode from object > It show up when I run pygtk\examples\pygtk-demo\demos\stock_browser.py Which versions of pygtk and gtk are you using? Dave Cook From ken at perfect-image.com Wed Sep 17 10:50:19 2003 From: ken at perfect-image.com (Ken Godee) Date: Wed, 17 Sep 2003 07:50:19 -0700 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) In-Reply-To: <6ee58e07.0309170543.354e65b0@posting.google.com> References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> Message-ID: <3F6874AB.9030301@perfect-image.com> Lothar Scholz wrote: > "John Dean" wrote in message news:<3f65f7e6$0$10993$fa0fcedb at lovejoy.zen.co.uk>... > >>Hi >>I would like to announce, for real this time, the release of BlackAdder >>V1.0.0. We have just finished our weekly conference during which I was give >>specific instructions by Shawn Gordon to make this announcement >> >>I have uploaded the demos to http://www.rygannon.com and to >>http://www.totalrekall.co.uk > > > How about a useable trial version instead of demos. > > As long as i can't try it out for 30 days in real work (saving files) > i will never consider buying it. I downloaded the demo and as far as I can tell it's fully fuctional Here's a quote from the opening screen...... "Thank you for trying out Black Adder. This, demo, version is fully functional but can only be run for a short period of time. Please consider buying a copy - you will be supporting the development of a great tool!" Just what you asked for I believe, "useable trial". Saves files,etc. and works great, nice tool. From peter at engcorp.com Wed Sep 24 14:31:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 24 Sep 2003 14:31:13 -0400 Subject: pprint and ">>>" References: Message-ID: <3F71E2F1.62CFB8D3@engcorp.com> Shu-Hsien Sheu wrote: > > Sometimes, it is find of nice using: > print >> my_file_object, my_variabels > than using the standard f.write. > However, it cannot be done with pprint.pprint. I suspect you are looking for either the second argument to pprint(), or pprint.pformat() instead. pprint.pprint(my_variables, my_file_object) or print >>my_file_object, pprint.pformat(my_variables) -Peter From duncan at NOSPAMrcp.co.uk Mon Sep 8 09:31:49 2003 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 8 Sep 2003 13:31:49 +0000 (UTC) Subject: Read file that starts with '\xff\xfe' References: <3F5BD4DD.57D90AF5@alcyone.com> <3F5BFC19.D098115B@alcyone.com> <6.0.0.22.0.20030908054530.03c42dd8@66.28.54.253> <3F5C7270.1020001@ghaering.de> Message-ID: Bob Gailer wrote in news:mailman.1063025195.15280.python-list at python.org: > That's a good start. I presume I need to use codecs.open(filename, > mode[, encoding[, errors[, buffering]]]) to read the file. What is the > actual value of the "encoding[" parameter for "Little-endian UTF-16 > Unicode character data, with CR line terminators" Try: myFile = codecs.open(filename, "r", "utf16") If the file starts with a UTF-16 marker (either little or big endian) it will be read correctly. If it doesn't start with either marker reading from it will throw a UnicodeError. -- 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 jjl at pobox.com Mon Sep 22 06:57:41 2003 From: jjl at pobox.com (John J. Lee) Date: 22 Sep 2003 11:57:41 +0100 Subject: Passing data out of a Sax parser References: <878yohajyc.fsf@pobox.com> Message-ID: <87vfrlt7iy.fsf@pobox.com> "Andrew Dalke" writes: > Me: > > > if name == "spam": > > > self.count += 1 > > John J. Lee: > > Works, but integers aren't mutable. > > I assume you refer to the snippet I posted above? > > Since it works, I don't understand the need for > your comment. [...] It was just a nit: you said (indirectly) that integers are mutable: | Either that or have startDocument create the mutable object, as [...] | self.count = 0 [...] | self.count += 1 [...] John From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 10 09:59:43 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 10 Sep 2003 14:59:43 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? Message-ID: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> I have in the past suggested that Python functions could use some kind of modifier token for parameters to indicate pass-by-reference, so that immutable items in particular could be modified (or more accurately replaced) by the function, with that modification affecting what the caller sees. In case I'm explaining this badly, here is how Python currently works... >>> def Inc(p) : ... p += 1 ... >>> x = 1 >>> Inc(x) >>> x 1 ... and here is (roughly) what I'd like to be able to do... >>> def Inc(ref p) : ... p += 1 ... >>> x = 1 >>> Inc(x) >>> x 2 There are good reasons why this is not supported in Python at present, which have been explained to me in the past. However, I've been learning C# just recently, and I've just been struck by a blinding flash of the obvious. C# has a rather similar issue - some types are 'value types' (as opposed to 'reference types') and comparable to immutables in Python in many ways, yet there is still a need (on occasion) to pass them by reference. While C# has static typing and could have done exactly the same thing as Pascal or as C++, it actually did something different. The C# solution uses a modifier keyword, but that keyword must be specified in both the function definition *and* the call. For instance... ... public static void Inc (ref int p) { p++; } ... int i = 1; Inc (ref i); ... The rationale for this in C#, I assume, is mostly about clarity and maintainability - the caller can't be surprised when value type parameters are changed in a function as he had to explicitly allow it. It also allows both a by-reference and a by-value version of the same function to be defined using overloading (though that seems much less useful to me). However, it occurred to me that this approach could also be used to solve the main implementation problem with adding a call-by-reference scheme to Python. In Python, the compiler cannot adapt the calling convention to different types of functions because it cannot refer back to the declaration of the function at compile time - the function being called is not always knowable until run-time (e.g. using a variable can be assigned a function object, lambda can create anonymous functions, etc). At first sight, it appears that supporting call-by-reference would require a big run-time overhead as the run-time engine queried the function object to determine which parameters to pass by reference and to adapt the call appropriately. Because the C# approach indicates which parameters are by reference in the call, however, this overhead can be avoided - the compiler doesn't need to refer to information in the declaration to determine which parameters to pass by reference. Basically, when a function or method is declared with 'ref' modifiers on some parameters, Python could use a variant of the function type which supports a new call mechanism and knows which parameters need to be passed by reference. Similarly, when a call uses 'ref' modifiers, Python can do a consistency check with the function type being called and use the new call mechanism. Performance with functions that don't use call-by-reference would be unaffected... 1. If a call with ref-modifiers is attempted on a non-ref function, this would be rejected in the same way as any attempted call on a non-callable object - the required behaviour wouldn't exist for conventional function objects. 2. If a call without ref-modifiers is attempted on a function with ref modifiers, it would again be rejected as the new function type wouldn't support the required behaviour for conventional calls. 3. A conventional call to a conventional function would operate exactly as it does now. In short, only calls using call-by-reference would incur any overhead (to validate that the correct parameters are by-reference or not, and to implement the new calling convention). Even that validation in the call overhead could probably be avoided (by having a large number of function-class variants), leaving only the implementation of the calling convention as a problem. I would then be able to write... >>> def Inc(ref p) : ... p += 1 ... >>> x = 1 >>> Inc(ref x) >>> x 2 Obviously the implementation would not be trivial, but i think this would be a very useful feature. Any thoughts? From danielk at aracnet.com Sun Sep 28 00:29:12 2003 From: danielk at aracnet.com (Daniel Klein) Date: Sat, 27 Sep 2003 21:29:12 -0700 Subject: IDE with a specific feature Message-ID: I don't want to get into a 'which IDE is the best' conversation. I'm looking for an IDE that has the ability to view 2 (or more) methods/functions within the same module simultaneously. I've looked at the screen shots for Komodo, Wing, BlackAdder, etc and it is not obvious that any of them have this feature. This is something I got use to in Smalltalk and have found it quite useful when working on several methods that work closely together. Daniel Klein From BjornPettersen at fairisaac.com Fri Sep 26 15:01:18 2003 From: BjornPettersen at fairisaac.com (Pettersen, Bjorn S) Date: Fri, 26 Sep 2003 14:01:18 -0500 Subject: Reduce need of backslash Message-ID: <1DAECE9E8F34E04AA0E5699AF7D9FF0907B599B7@stpmsg00.corp.fairisaac.com> > From: John Roth [mailto:newsgroups at jhrothjr.com] > > "Nicolas Fleury" wrote in message > news:MI_cb.75294$PD3.4794043 at nnrp1.uunet.ca... > > Peter Otten wrote: > > > > > Nicolas Fleury wrote: > > > > > > > > >>I was wondering if the need for \ could be reduce in the > > >>language. For example, could a line ending with = or + > > >>could be automaticly considered incomplete? > > > > > > > > > Did you know about (...)? > > > > Actually, no. But it's still not what I'm looking for. > > It's just that I'm used to languages where I can put my > > code on multiple easily to make lines shorter. "I know that long lines are bad, help me do it more conveniently in Python?" . Seriously though, long lines are a sure sign that you're doing too much per line. The obvious solution is to pull out subexpressions and assign them to meaningful temporary variable names until you're within 25x80. When someone wants to fix a bug in your code a year from now it will also be easier for them to figure out what you were trying to do (potentially saving you time :-) > > As John pointed, it's possible to add () to print. I > > just discovered that it can be done with return also. I > > wonder how to remove the need for \ in that example: > > > > parser.StartElementHandler = \ > > lambda name, attrs: \ > > GenericParser.handleElementStart(self, name, attrs) > > How about: > > parser.StartElementHandler = (lambda name, attrs: > GenericParser.handleElementStart(self, name, attrs)) A lambda that doesn't fit on one line is way to obscure... It needs a comment to justify it's existence, so might as well do it right : def startElementCallback(tagname, attrs): GenericParser.handleElementStart(self, tagname, attrs)) parser.StartElementHandler = startElementCallback No contortions, I'm explicitly saying what the purpose of the funciton is, I can add comments/asserts/logging without spending time on code "layout" issues, and I can write tests explicitly for 'startElementCallback' without considering the rest of the fn's functionality (it might be trivial here, but code grows... ;-) -- bjorn From glc at well.com Fri Sep 12 11:00:25 2003 From: glc at well.com (Greg Chapman) Date: Fri, 12 Sep 2003 15:00:25 GMT Subject: Opposite of yield? References: <3F5F7E35.B5DA4669@easystreet.com> Message-ID: On Wed, 10 Sep 2003 12:40:37 -0700, achrist at easystreet.com wrote: > >The yield statement looks to be a big step toward some kind of >lightweight concurrency-oriented programming in python. Is there >any similarly nice way to do the opposite of yield, just sit around >(perhaps in the middle of a loop) and wait until some other routine >(unknown to the waiting module) hurls a value in? > >If this is not implemented now, is there any chance that it's on the >list of things to come? > You can use a generator as the body of a function. That is, the generator is only ever accessed through the function, and the function and the generator have some agreed on way to pass parameters. I.e.: def getline(output): '''getline accumulates text until it has a complete line (signaled by either a newline (\\n) or a null (\\0)). It then passes the line (without trailing \n) to output''' genargs = [None] def callgen(text): genargs[0] = text return gennext() def gen(): line = '' while True: text, = genargs if text: lines = text.splitlines(True) if line: lines[0] = line+lines[0] for line in lines[:-1]: output(line[:-1]) line = lines[-1] if line[-1] in '\n\0': if line[-1] == '\n': line = line[:-1] output(line) line = '' yield None gennext = gen().next return callgen def printer(text): print text lineprinter = getline(printer) lineprinter('hello') #nothing output lineprinter(' world\n') #prints 'hello world' --- Greg Chapman From jerf at jerf.org Thu Sep 4 22:44:51 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 05 Sep 2003 02:44:51 GMT Subject: htmllib.py and parsing malformed HTML References: <873cfeyhqw.fsf@pobox.com> <09J5b.203$MD.41@bignews3.bellsouth.net> Message-ID: On Thu, 04 Sep 2003 11:50:07 -0400, KC wrote: > As with most organizations, > changing *our* code is much more acceptable to the powers that be, than > bringing in a third-party product that will have to be evaluated and have > countless meetings over its approval. For many of us, business and policy > decisions often forge the direction for technology usage within our > organizations. If you are having real problems with poor HTML, HTMLTidy may be worth going to bat over. If you can find a simple solution that works on the HTML you are processing, great, go with it, and it's worth researching in your situation first. But HTML can go bad in more ways then you can imagine (which is in fact part of the problem); if you are getting HTML that's bad in a lot of little ways, you'll find the "apply a hack to fix this file, apply a hack to fix that file" will start stepping on its own toes. HTMLTidy represents a ***lot*** of grunt work and a ***lot*** of functionality that you can *not* replicate in a reasonable amount of time; it's one of those packages that isn't so much a program that "does something" as a program that represents many, many man-years of "knowledge acquired". I'm not trying to push anything, since I don't know your situation, but HTMLTidy is one of those rare projects that you really shouldn't allow NMH to scuttle unless you *really* need to. (Again, I mention if there's some simple way you can characterize the bad HTML coming out of one single program, go ahead and try to fix it; maybe you'll get lucky and a regex will be enough.) From adalke at mindspring.com Tue Sep 30 00:22:45 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Tue, 30 Sep 2003 04:22:45 GMT Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: Christos TZOTZIOY Georgiou: > Safe wisdom: mv (move, ren for old DOS) would be better, right? Sure. I know that *now*. :) > If 'inst same' wasn't enough, then that should have been a really old > version of Irix... :( > -- A Personal Iris running 3.0.4, in 1990 Andrew dalke at dalkescientific.com From prabhura at caip.rutgers.edu Tue Sep 2 06:58:37 2003 From: prabhura at caip.rutgers.edu (Prabhu Raghavan) Date: Tue, 2 Sep 2003 06:58:37 -0400 (EDT) Subject: (no subject) Message-ID: <200309021058.GAA18860@caip.rutgers.edu> Hi, You have reached prabhura at caip.rutgers.edu. This address is no longer being read by the owner. If you are sending junk (which is what I suspect) please stop. If you are sending useful mail, you should know a better address to send to. As for this message re:Re: Thank you!, I'm going to do my best to ignore it. Incidently, apart from an automatic reply, this is being redirected to /dev/null. Cheers. From peter at engcorp.com Tue Sep 23 09:22:21 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 23 Sep 2003 09:22:21 -0400 Subject: References: <3f6f32b9@post.newsfeed.com> Message-ID: <3F70490D.6EC57C01@engcorp.com> "Lonnie, SRC employee" wrote: > > *** post for FREE via your newsreader at post.newsfeed.com *** > > I can figure out how to set the standalone attribute in the version="1.0 ?> tag eg Simplest approach might be to manually munge the tag as you write the output to a file. You could do a simple re.sub() or something like this, which we've used from time to time with no ill effects to date (pseudo-code, not executable as-is): xml = '' xmlEnd = xml.find('?>') + 2 file.write('' + xml[xmlEnd:]) In other words, find the end of the original tag, strip it, substitute your own, continue on with life. Simplest thing that could possibly work... -Peter From letbetter at ti.com Fri Sep 26 09:21:51 2003 From: letbetter at ti.com (Letbetter, Jason) Date: Fri, 26 Sep 2003 08:21:51 -0500 Subject: Is there an extension library? Message-ID: I'm creating Python extensions for several c/c++ components. I'm using swig to create the extensions. The biggest challenge so far is working with the c args between Python and the Python extension. Is there a 3rd party library of extension helpers that assist in representing c-types between Python and c? Are there any tips and tricks? Here are some specific scenarios I am running into. 1) Refrencing and derefrencing: For example, condsider this c api: void foo_alloc(void** handle_ptr); void foo_use(void* handle); In c &handle. How to get pointer to pointer in Python? In c *handle_ptr. How to derefrence a pointer in Python? 2) Coercion: For example, suppose you want to initialize a char array in Python. buf = CharArray(100) for i in range(100): buf[i] = i The above results in: "TypeError: CharArray___setitem__() argument 3 must be char, not int" In c, buf[i] = (char)i, is implicit. How do I do it in Python. Why doesn't Python make this conversion implicitly? 3) It seems like I'm doing something unatural with my Python extension. It seems someone else may have already figured out the best way to transform c arguments between Python and Python extensions genericly. Thanks, Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From JoeyTaj at netzero.com Thu Sep 18 16:20:54 2003 From: JoeyTaj at netzero.com (Paradox) Date: 18 Sep 2003 13:20:54 -0700 Subject: win32comm References: Message-ID: <924a9f9c.0309181220.17bf6984@posting.google.com> "Alberto Vera" wrote in message news:... > Hello: > > Could you tell me How I can solve this problem? > > Regards > > import win32com.client > ImportError: No module named win32com.clieny > -- Perhaps you need to install the win32 extensions. http://starship.python.net/crew/mhammond/win32/Downloads.html From tim.one at comcast.net Fri Sep 12 13:23:56 2003 From: tim.one at comcast.net (Tim Peters) Date: Fri, 12 Sep 2003 13:23:56 -0400 Subject: Python / C: small runtime difference? In-Reply-To: Message-ID: [Martin Schneider] > I chose a simple bubblesort because I wanted to compare the > performance of handcoded Python with handcoded C. I know that the > internal sort() routine of Python will beat the living daylights out > of my bubblesort :-) Hey, I'm not proud -- if it turns out your bubblesort runs faster, let me know and I'll try to make an adaptive bubblesort out of it . python's-list.sort()-implementations-have-advanced-by-staring-at- useless-ideas-until-they-give-up-ly y'rs - tim From tzot at sil-tec.gr Fri Sep 5 07:53:05 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 05 Sep 2003 14:53:05 +0300 Subject: file object, details of modes and some issues. References: <3f57be21$1_2@mk-nntp-1.news.uk.worldonline.com> Message-ID: <0bpglv0qr8a3okmn3smcnp0q8diq4ao18p@4ax.com> On Thu, 04 Sep 2003 23:35:11 +0100, rumours say that simon place might have written: >could someone confirm ( or otherwise ) this bug. >manual says file.truncate leave the pointer unmoved, well it doesn't, and left >me with a bug in a program that took a bit of finding. > >>> f=file('test.dat','rb+') change the above to f=file('test.dat', 'wb') to make things easier > >>> f.write('1234567890') > >>> f.close() > >>> f=file('test.dat','rb+') > >>> f.read(5) >'12345' > >>> f.tell() >5L > >>> f.truncate() > >>> f.tell() >10L >( PythonWin 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on >win32. ) Seems it's a Windows only bug. On a 2.4.3 linux, libc-2.2.5 the final statement produces 5L (and the file is only 5 bytes long). Same on another 2.4.19 libc-2.2.5, and a 2.4.21 libc-2.3.1 Linux, all with a recent Python 2.4a0 . I did reproduce it on Windows. I believe you should post a platform-specific bug; meanwhile, you can assure that f.truncate() works correctly on Windows by issuing a f.seek(f.tell()) beforehand. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From jepler at unpythonic.net Tue Sep 30 16:39:20 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 30 Sep 2003 15:39:20 -0500 Subject: where are the "class variables"? In-Reply-To: <62e9c66e.0309301227.20505db6@posting.google.com> References: <62e9c66e.0309301227.20505db6@posting.google.com> Message-ID: <20030930203914.GD12344@unpythonic.net> On Tue, Sep 30, 2003 at 01:27:15PM -0700, Dominik Kaspar wrote: > maybe my question was badly formulated. i give it a new try: > why does the following program give the output "0 0" and not "1 0"? > why does it loop forever? and how could that problem be fixed? Because inside functions, an assignment to a simple name, like running = 1 refers to a local variable, unless there is a "global" statement in which case it refers to a module-level variable: global running running = 1 (this is still not what you want) You want to refer to Server.running, as suggested in another message: def run(self): Server.running = 1 jeff PS The first server.running might print 0 if the first line of Server.run hasn't executed the first statement yet, of course, but that's another story From vze4rx4y at verizon.net Tue Sep 23 19:28:43 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 23 Sep 2003 23:28:43 GMT Subject: Thoughts on PEP284 References: Message-ID: [Stephen Horne] > Running with this idea, how about... > > for i in int.backward [:n] : > ... I would support adding a iter_backwards() method to strings, lists, and xrange objects. for i in xrange(n).iter_backwards(): print i for i in range(n).iter_backwards(): print i for c in "flog".iter_backwards(): print c It could also be implemented for other sequence objects if there were compelling use cases and if the implementation wasn't too hairy (file objects for instance). Raymond Hettinger From newsgroups at jhrothjr.com Tue Sep 30 18:45:34 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 30 Sep 2003 18:45:34 -0400 Subject: PEP-0263 and default encoding References: <3f782aef-bdbbd6f1-a72a-4a6c-8b23-c4915b89a61f@news.szn.dk> Message-ID: "Martin v. L?wis" wrote in message news:m3k77qdkey.fsf at mira.informatik.hu-berlin.de... > Klaus Alexander Seistrup writes: > > > 2. You are writing new code, and you are annoyed by the encoding > declaration. Just save your code as UTF-8, using the UTF-8 BOM. The problem with the UTF-8 BOM is that it precludes using the #! header line under Linux/Unix. Otherwise, it's a great solution. John Roth > > Regards, > Martin From skip at pobox.com Wed Sep 10 11:07:58 2003 From: skip at pobox.com (Skip Montanaro) Date: Wed, 10 Sep 2003 10:07:58 -0500 Subject: OT: Americans love their guns In-Reply-To: References: Message-ID: <16223.15950.299463.959577@montanaro.dyndns.org> >> Counter-test: Imagine your seven-year-old son finding your gun and >> shooting and killing your five-year-old daughter while you're working >> in your study. Al> Impossible. The son had been taught safe gun handling on the pistol Al> range w/ a .22 starting at aged five, and would come and tell you Al> that firearm had not been safely stored. This sort of thing still happens (it hits the news whenever such a shooting occurs), so clearly all seven-year-olds who live in houses with guns are not being trained to handle and respect firearms. Skip From eriuhq24o8q7fgalwef at spamhole.com Tue Sep 30 18:41:34 2003 From: eriuhq24o8q7fgalwef at spamhole.com (pysim) Date: 30 Sep 2003 15:41:34 -0700 Subject: Using MVC when the model is dynamic Message-ID: Hi, I have a couple of general requests for pointers to python examples and design advice. I'm looking for examples of MVC-based GUI controls done in python (model-view-controller). Also, examples where something like a simulation model running in its own thread sends fast updates to a GUI in near real-time. The only examples I've seen, such as SimPy, wait until the model is finished running before outputting data. Most MVC controls I see in java for example are only designed for infrequent user-driven changes, like resizing a window or mouse clicks, not cases where the underlying model is changing itself over time. From google at elesi.org Wed Sep 10 16:54:10 2003 From: google at elesi.org (neeson) Date: 10 Sep 2003 13:54:10 -0700 Subject: Heisenberg strikes again! Message-ID: Alright, I'm fairly new to Python, and this one has got me stumped. I've just started to write a cli program that'll use readline, and I've attached the relevant bits. Here's the mystery: If I so much as /look/ at the list 'matches', readline stops working. Run the program, hit tab at the prompt, you'll get 'one', which is incorrect, as there are in fact four possible completions. Now comment out the line that I've marked (which, incidentally, does nothing). /Now/ it works. Is there some very strange side effect to accessing a list element that I'm unaware of? I've tried it in two different versions of Python. Any elightenment would be appreciated... Heath ps In terms of being useful, this program doesn't make any sense. I'm not trying to get it to work, I'm looking to understand why the commented line affects the rest of the code. #!/usr/bin/python import readline import sys commands = ["one", "two", "three", "four"] matches = [] def comp(text, state): if state == 0: matches = [] n = len(text) for cmd in commands: if cmd[:n] == text: matches.append(cmd) throwaway = matches[0] # <--- Comment out this line return commands[state] readline.set_completer(comp) readline.parse_and_bind("tab: complete") while 1: try: line = raw_input("> ") except EOFError: print "\n", sys.exit() print ": %s" % line From danielk at aracnet.com Mon Sep 15 10:51:19 2003 From: danielk at aracnet.com (Daniel Klein) Date: Mon, 15 Sep 2003 07:51:19 -0700 Subject: list of lists References: Message-ID: On Mon, 15 Sep 2003 15:59:56 +0200, Tom wrote: >I have a list that consists of lists. >E.g. T=[[1, 2, 3], [4, 5], [6]] >Is there a way to address the a specific component in the "inner" list >directly? >E.g. right now I want to get the second value of the first list. >Unfortunately I have to save it to a variable first and then read it. >a = T[0] >print a[1] > >That kind of sucks, becaus I have to read a lot of values from a lot of >lists! :-( >Is there a faster way than my saving it to a "help variable" first? >>> T=[[1, 2, 3], [4, 5], [6]] >>> print t[0][1] 2 Daniel Klein From adalke at mindspring.com Wed Sep 24 15:51:56 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 24 Sep 2003 19:51:56 GMT Subject: Pre-PEP: reverse iteration methods References: Message-ID: Stephen Horne: > To me, the reason to use a method (or property) is simply that most > types cannot be efficiently 'backwardised'. Which is why my function looks for an '__riter__' under the covers, so that an object can provide a specialized implementation, if possible. If it can't, I then proposed an implementation which will iterate in reverse through lists and list-like interfaces (things indexed by 0, 1, ... len(obj)-1). There is a problem though in that my attempt at a 'generic' reverse implementation will give strange errors in dictionary-like interfaces. > For instance, iterators in > general would have to be buffered into a list an then the resulting > list iterated backwards. That could be useful, but the overhead is > sufficient that I think explicitly writing 'list (x).backward ()' > rather than 'x.backward ()' would be a good thing. Those objects which implement a 'reverse_iterate' / 'backward' / whatever are identical to those which would implement a __riter__ accessed under the covers. My question is, what to do about objects which *don't* provide a special method. Should there still be a standard way to do a reverse iteration through them? The only two I can think of are: - assume for i in range(len(obj)-1, -1, -1): yield obj[i] works as a backup. It doesn't quite work because of dictionaries. - assume that storing all elements in a temporary list and doing a reverse on the temp list is okay. As you point out, it is the most generic but doesn't work if memory is a problem. (There's also a concern about proper destruction order if you want to delete elements from a list starting from the end.) - (There's a third, which is O(n**2). At every request, iterate through the list to find the last element.) If there is an acceptable solution (which needn't be perfect, just practicable) then it's a good reason to have it be a builtin over a special method. I still point out that there are many other ways of doing iteration and I don't see what makes reverse iteration so important to get its own method. Andrew dalke at dalkescientific.com From alanmk at hotmail.com Wed Sep 24 06:38:28 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 24 Sep 2003 11:38:28 +0100 Subject: string.rstrip References: <731fc603.0309221414.78a92789@posting.google.com> Message-ID: <3F717424.6C9503BD@hotmail.com> Matthew Wilson wrote: > What would be the best way to strip off the last "_asdf" from > "asdf_asdf_asdf"? I don't about "the best way" (define "best"), but here's another way #-------------- import re patt = re.compile('_asdf$') mystring = "asdf_asdf_asdf" print patt.sub('', mystring) #-------------------------- HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From fperez528 at yahoo.com Tue Sep 30 19:28:38 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 30 Sep 2003 17:28:38 -0600 Subject: Wavelet package available? References: <2ceb70f8.0309290136.118a856d@posting.google.com> Message-ID: google("python wavelets")[2] -> http://baypiggies.net/pipermail/baypiggies/2003-September/000236.html I saw the talk (well, the scipy'03 version), and I suppose if you contact Chad directly he may be willing to mail you a copy of the package (I don't have it myself, so don't ask me). I don't know anything about the internals of the package, but at the talk he did show some nice functionality, mainly oriented towards image manipulations. Cheers, f. From mwilson at sarcastic-horse.com Tue Sep 23 15:03:01 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Tue, 23 Sep 2003 15:03:01 -0400 (EDT) Subject: idle import problem In-Reply-To: <200309231952.43835.andy@wild-flower.co.uk> References: <49799.199.169.240.132.1064335411.squirrel@svr1.turboweb.net> <200309231952.43835.andy@wild-flower.co.uk> Message-ID: <64446.199.169.240.132.1064343781.squirrel@svr1.turboweb.net> Thanks - That's really useful. I know how to set PYTHONPATH in unix, but how to in windows? > On Tuesday 23 Sep 2003 5:43 pm, Matthew Wilson wrote: >> Hi- >> >> I'm trying to import a countylist.py file in idle, and it isn't working. >> What am I doing wrong? >> >> >>> os.listdir(os.getcwd()) >> >> ['4dcountylist.txt', 'CBP90KY_TXT.htm', 'CBP90OH_TXT.htm', >> 'CBP90PA_TXT.htm', 'CBP90WV_TXT.htm', 'countylist.py', 'geocode.txt', >> 'mvsales.xls', 'mvsalesbyfirm.xls', 'production_in_4d.xls', >> 'USSalesSummary0308-1.xls'] >> >> >>> import countylist >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> import countylist >> ImportError: No module named countylist >> >> >> Any ideas? > > > Python doesn't import from the current directory; it uses sys.path, unless > the > cwd is on sys.path... > > if you want to temporarily put it on the path, do: > > import os,sys > sys.path.append(os.getcwd()) > > but a better solution is to either put your module into a directory tha > *is* > on sys.path, or modify your python path setting directlty by setting your > environment var PYTHONPATH accordingly. > > hope that helps > -andyj > From __peter__ at web.de Tue Sep 23 04:27:09 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Sep 2003 10:27:09 +0200 Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale related?)) References: Message-ID: Duncan Booth wrote: > Note that if anyone proposes this seriously, it should generate a 3-tuple > (mapping(item), index, item) rather than the 2-tuple you suggest. > > This is because the mapping function could reasonably be used to impose an > ordering on objects that have no natural order, so you need to be sure > that the comparison never falls through the the original object even where > the mapping compares equal. It also has the side effect of making the sort > stable (although if stability is a goal you might want another option to > reverse the sort which would use '-index' as the second element and call > .reverse() on the result). So my demo implementation was faulty :-( Let me try again: def sort(self, cmpfunc=None, mapfunc=None): if mapfunc: list.sort(self, lambda x, y: cmp(mapfunc(x), mapfunc(y))) else: list.sort(self, cmpfunc) Seriously, if sort() were to be thus extended, the dsu pattern would rather act as a performance enhancement under the hood. I prefer plain C struct { PyObject *decorator; int index; /* iff stability is not guaranteed by the sort algorithm */ PyObject *data; } over n-tuples and would hope to reuse the sorting infrastructure already there in listobject.c to compare only the decorators. I am not familiar with the C source, so be gentle if that is not feasible. > FWIW, I think something like this belongs in the standard library rather > than as a method on lists or a new builtin. If you think of the comparison as a two-step process, (1) extract or calculate an attribute (2) wrap it into a comparison function consider the following use cases: (a) lambda x, y: cmp(y, x) (b) lambda x, y: cmp(x.attr.lower(), y.attr.lower()) All code following the latter pattern could be rewritten (more clearly, I think) as alist.sort(mapfunc=lambda x: attr.lower()) and would automatically benefit from dsu (which could even be turned off transparently for the client code for very large lists, where the memory footprint becomes a problem). The litmus test whether to put it into a utility function or into an already existing method that needs only a minor and completely backwards-compatible interface change would then be: Are (b)-style comparison functions nearly as or more common than (a)-style functions. Peter PS: You and Alex Martelli dismissed my somewhat unfocused idea faster than I could sort it out. I hope you will find the above useful, though. From yaipa at yahoo.com Wed Sep 10 03:57:03 2003 From: yaipa at yahoo.com (yaipa h.) Date: 10 Sep 2003 00:57:03 -0700 Subject: Disagree with proposed 2.4 behavior for %x formatting of signed i nts References: <47sqlvo64vf5tk93qmmo2fi9pvt5ijbno2@4ax.com> Message-ID: <6e07b825.0309092357.3a983b50@posting.google.com> bokr at oz.net (Bengt Richter) wrote in message news:... > On Tue, 09 Sep 2003 20:11:09 +0200, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: > > >Tim Roberts wrote: > > > >> You do not understand correctly. This is what will happen: > >> > >> > >>>>>print "0x%08X" % -1041053949 > >> > >> 0x-3E0D38FD > > > >Actually, what *will* happen is > > > >-0x3E0D38FD > > > Really? In that case, would > > print "@#%08X" % -1041053949 > > produce > > -@#3E0D38FD > ?? Sorry, but that sucks. --alan > > > >Indeed. You can still do all binary manipulations that you want to do. > > > But reasonably? > > Regards, > Bengt Richter From achrist at easystreet.com Wed Sep 3 17:02:02 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Wed, 03 Sep 2003 14:02:02 -0700 Subject: quick and smart way for parsing a CSV file? References: <731fc603.0309031242.4e5493ce@posting.google.com> Message-ID: <3F5656CA.519ABADF@easystreet.com> Hank wrote: > > Hi, > > I have a CSV file from excel that looks like this (simplified): > > name,description,type1,type2,name,filename > test1,this is a test,0.000,1.000,, > test2,another test,1.000,0.000,newname,filename > test3,this is a test,0.000,1.000,, > test4,this is a test,0.000,1.000,, > test5,this is a test,0.000,1.000,, > test6,this is a test,0.000,1.000,, > > what i want at the end is a dictionary like > > dict1[name] = test1 > dict1[description] = "this is a test" > . > . > . > dict2[name] = test2 > dict2[description] = "another test" > import csv dicts = [] inputFile = open("SomeDurnFileName.csv", "rb") parser = csv.reader(inputFile) firstRec = True for fields in parser: if firstRec: fieldNames = fields firstRec = False else: dicts.append({}) for i,f in enumerate(fields) dicts[-1][fieldNames[i]] = f From tim.one at comcast.net Thu Sep 11 17:40:30 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 11 Sep 2003 17:40:30 -0400 Subject: metaclasses for type comparison In-Reply-To: Message-ID: [David Eppstein] > I don't have 2.3 yet, so haven't used sets yet, but what happens if > you try to sort a list of sets? > > I found a message > tml> from Guido wondering about this but didn't see what the response > was... It was resolved as suggested there: an explict cmp() applied to two Sets raises an exception. Set1.__lt__(Set2) returns true iff Set1 is a proper subset of Set2. list.sort() uses only __lt__ (when it can), so sorting a list of Sets won't raise an exception (at least not just because __cmp__ raises an exception -- __cmp__ is never called because __lt__ exists), but it's hard to say something useful about the result. For example, >>> from sets import Set >>> x = [Set([i]) for i in range(10, 0, -1)] >>> x.sort() >>> x [Set([10]), Set([9]), Set([8]), Set([7]), Set([6]), Set([5]), Set([4]), Set([3]), Set([2]), Set([1])] >>> "x < y" returns false for each distinct pair of sets x and y in that list, so any permutation of the list is as good an answer as any other. It so happens that the 2.3 list.sort() implementation first asks x[i] < x[i-1] for each relevant index position i. They all say "no", so list.sort() "deduces" (via assumed trichotomy) that x[i] >= x[i-1] everywhere, so ends up believing the list is already in sorted order, and leaves it alone after that one pass over the data. From peter at engcorp.com Mon Sep 22 19:19:39 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 22 Sep 2003 19:19:39 -0400 Subject: Calling functions before that are def'ed References: <944840ff.0309221318.35d2f9cd@posting.google.com> Message-ID: <3F6F838B.588965D5@engcorp.com> Daniel Dittmar wrote: > > Charles Larry wrote: > > Is there a way to define functions after the main part of a Python > > script? > > > > Example: > > > > #!/usr/local/bin/python > > > > # this code yields a NameError > > > > print_message("hello world") > > > > def print_message(msg): > > print msg > > #!/usr/local/bin/python > > def main (): > print_message("hello world") > > def print_message(msg): > print msg > > if __name__ == "__main__": > main () > > def statements are really executable statements and not declarations, so > the order is important. Note that the above slightly changes the behaviour of the code when globals are involved. Putting the original code directly under the __main__ part at the end, however, does not. (This example is too simple to exhibit any difference in behaviour, but the following is the "safer" method for the unwary newbie, even if it's not as clean in the long run.) def print_message(msg): print msg if __name__ == "__main__": print_message("hello world") -Peter From yeung_too at yahoo.com.hk Fri Sep 5 11:24:26 2003 From: yeung_too at yahoo.com.hk (yeung_too) Date: Fri, 05 Sep 2003 11:24:26 -0400 Subject: Why python??? Message-ID: <3335321.1062775466@dbforums.com> Dear all, My college used C for beginner course and use Java to demostrate OO concept. Anyway, I tried python and found that it is a very good language. I think many people spend time on Java and university uses Java because Sun Microsystem spends much money to promote and develop the Java language. I just feel that our world spends most time on promote things, rich company can promote computer language very well. Open source without huge money support, people may dislike their product. What do you think, But i really like open source ideas, it improves our world, not just $$$. an university student (reflect my feeling) -- Daniel Chan Posted via http://dbforums.com From fuerte at sci.fi Tue Sep 16 23:22:19 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Wed, 17 Sep 2003 06:22:19 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <20030916211148.GD29089@unpythonic.net> References: <3F632226.2010607@earthlink.net> <5CH9b.81$2k.16@reader1.news.jippii.net> <20030916211148.GD29089@unpythonic.net> Message-ID: <3F67D36B.80709@sci.fi> Jeff Epler wrote: >On Tue, Sep 16, 2003 at 08:22:41PM +0300, Harri Pesonen wrote: > > >>It is more efficient to have one process and several threads, than >>several processes each having one thread. >> >> > >If it's easier to code "several processes each having one thread", then >I'll sure do it. I've accepted a 2x-100x speed hit by using Python, so >if it's a 25% difference in efficiency, I won't sign up to wait for code >that doesn't exist yet. > > But wouldn't it be better if Python had real multitasking? Comments like the above mean that you accept Python as it is, fine. But usually people want to make things better when they see that something can be improved. If my roof is leaking, I have two choices: fix it or accept it. If I am able to fix it, then I'll probably do it. The old code base really is the problem here. If Python threads really run at the same time in the future, how many current applications stop working because they depend on the fact that only one thread runs at any given time, and do not acquire and release locks as needed? On the other hand, my suggestion probably means that we couldn't have a threading module compatible with thread or threading anyhow (we could have freethreading, with specific functions for inter-thread communication). Harri -------------- next part -------------- An HTML attachment was scrubbed... URL: From newsgroups at jhrothjr.com Wed Sep 17 21:51:46 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 17 Sep 2003 21:51:46 -0400 Subject: Module to generate OpenOffice Writer documents References: Message-ID: "Ellinghaus, Lance" wrote in message news:mailman.1063843345.7931.python-list at python.org... > Has anyone created a module to generate the XML formatted files for > OpenOffice? >From what? What's the input? John Roth > > Lance > > Lance Ellinghaus > EDS - TWAI Operations > Phone: 214-922-5454 > Cell: 940-597-4755 > > > From amk at amk.ca Tue Sep 2 18:45:51 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 02 Sep 2003 17:45:51 -0500 Subject: Python REST framework? References: Message-ID: On 2 Sep 2003 14:52:05 -0700, Will Stuyvesant wrote: > I'm interested. But I have been looking at the discussion on the rest > mailing list at http://groups.yahoo.com/group/rest-discuss/ and it > seems they haven't found a solution for the user:password thing yet. > Using SSL is a must, but then what? Create some unguessable URI? I'm not on the rest-discuss list and therefore don't know what this is referring to? What's wrong with returning an HTTP 401 Unauthorized error to make the user provide a username and password? --amk From jacek.generowicz at cern.ch Wed Sep 17 07:18:42 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Sep 2003 13:18:42 +0200 Subject: looking for MOP documentation References: Message-ID: Anthony Baxter writes: > Erm, what's "MOP" mean? Meta Object Protocol. From oren-py-l at hishome.net Tue Sep 16 14:12:47 2003 From: oren-py-l at hishome.net (Oren Tirosh) Date: Tue, 16 Sep 2003 14:12:47 -0400 Subject: Duck Typing In-Reply-To: <3gG9b.12137$3Y2.2543@news2.central.cox.net> References: <221d8dbe.0309160101.4a09f2ad@posting.google.com> <3gG9b.12137$3Y2.2543@news2.central.cox.net> Message-ID: <20030916181247.GA78164@hishome.net> On Tue, Sep 16, 2003 at 03:47:11PM +0000, Steve Holden wrote: > "Oren Tirosh" wrote ... > > On Tue, Sep 16, 2003 at 02:01:18AM -0700, srijit at yahoo.com wrote: > > > Hello All, > > > I have been seeing this term "duck typing" for quite sometime now. It > > > will be nice if one of us can give an example in Python demonstrating > > > duck typing and/or link to some Python references. > > > > class Duck: > > def quack(self): > > print "Quack!" > > > > class MeWearingSillyDuckOutfit: > > def quack(self): > > print "ummm... Quack!" > > > > def make_it_quack(obj): > > obj.quack() > > > > a = Duck() > > b = MeWearingSillyDuckOutfit() > > make_it_quack(a) > > make_it_quack(b) > > > > exquacktly [ducks and runs] class Run: def quack(self): print "QUACK!" ducks = [Duck() for i in range(10)] runs = [Run() for i in range(10)] apply(make_it_quack, ducks+runs) Oren From sross at connectmail.carleton.ca Tue Sep 23 10:40:30 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 23 Sep 2003 10:40:30 -0400 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <63gvmvcf6iakbs8pgll7u8ogblkbqld6fp@4ax.com> <6EQbb.1770$PT3.279727@news20.bellglobal.com> <8vovmvgmb5c677ii8a43l8l0o1sjbosre2@4ax.com> Message-ID: Here's a quick hack of an int class that supports iteration using the slice notation, plus simple iteration on the class itself (for i in int: ...). This can certainly be improved, and other issues need to be addressed, but I just wanted to see what Stephen's idea would look like in practice. (Not bad. Actually, pretty good.) # using python 2.2.2 from __future__ import generators class xint(int): class __metaclass__(type): def __iter__(cls): return cls.__getitem__() def __getitem__(cls, index=None): if hasattr(index, "start"): for i in range(index.start, index.stop, index.step): yield i elif isinstance(index, int): yield index elif index is None: i = 0 while True: yield i i += 1 else: raise Exception __getitem__ = classmethod(__getitem__) print "iteration on int" for i in xint: if i >= 10: break print i print "\niteration on int slice" for i in xint[0:22:2]: print i # # OUTPUT # iteration on int 0 1 2 3 4 5 6 7 8 9 iteration on int slice 0 2 4 6 8 10 12 14 16 18 20 From peter at engcorp.com Thu Sep 25 15:53:13 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 25 Sep 2003 15:53:13 -0400 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: <3F71B857.2D1E3268@engcorp.com> <3F720759.34D7BD3E@engcorp.com> <3F720D28.83C3E99@engcorp.com> <3F731B17.61C17B3A@engcorp.com> Message-ID: <3F7347A9.216B8EE@engcorp.com> Dominic wrote: > > Besides with Pyrex it's 2-4 lines to access > PyThreadState_SetAsyncExc from Python :-) Posting those 2-4 lines would be helpful to those searching the archives at a later date. ;-) -Peter From tjreedy at udel.edu Sun Sep 14 11:26:11 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 14 Sep 2003 11:26:11 -0400 Subject: referencing in cmd string References: Message-ID: "Kali K E" wrote in message news:ab5a234a.0309140638.e81fbab at posting.google.com... > Hi, > > I wanted to grep a file for a pattern. The pattern is a dynamic one > stored in the string "rec". I tried to do it as follows: > > cmd = "grep -c rec filelist2 > grepdata" > os.system(cmd) I believe you want the value of the string named 'rec', and not 'rec' itself, inserted in your command string. If that value does not itself need to be quoted within the command string, then this should work. "grep -c %s filelist2 > grepdata" % rec If your pattern has chars that make it necessary to be (double?) quoted, then maybe 'grep -c "%s" filelist2 > grepdata' % rec will work. (The command quoting rules depend on your OS and shell.) Terry J. Reedy is what you From jepler at unpythonic.net Sat Sep 20 10:43:48 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 20 Sep 2003 09:43:48 -0500 Subject: bizarre behavior using .lstrip In-Reply-To: <200309192243.27913.j_k_wd@bellsouth.net> References: <681f9321.0309191607.4e8b858a@posting.google.com> <3F6B9B44.9EAD3CF9@engcorp.com> <200309192243.27913.j_k_wd@bellsouth.net> Message-ID: <20030920144342.GA10939@unpythonic.net> On Fri, Sep 19, 2003 at 10:43:27PM -0400, Jeremy Dillworth wrote: > As an alternative you could use re.sub() > > >>> import re > >>> s = 'chg cbonn_fee' > >>> print re.sub('chg ', '', s) > cbonn_fee I'd recommend avoiding regexes if this is all you're doing. Instead, you can write a function to do it: def remove_prefix(prefix, s): """remove_prefix(prefix, s) -> str If s starts with prefix, return the part of s remaining after prefix. Otherwise, return the original string""" if s.startswith(prefix): return s[len(prefix):] return s >>> for s in ("chg conn_fee", "something else", "chg x", "chg", "chg "): ... remove_prefix("chg ", s) ... 'conn_fee' 'something else' 'x' 'chg' '' Jeff From __peter__ at web.de Wed Sep 3 11:38:50 2003 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2003 17:38:50 +0200 Subject: Invisible function attributes References: <51809ae4.0309030715.7706cadb@posting.google.com> Message-ID: def foo(): try: foo.a += 1 # executed every time you call the function except AttributeError: foo.a = 1 # set to one if it's not already there foo.b = 1 # executed once print vars(foo) # function body not yet called {'b': 1} for i in range(3): foo() print vars(foo) Loop output is {'a': 1, 'b': 1} {'a': 2, 'b': 1} {'a': 3, 'b': 1} That is all perfectly sane as code in the function body is never executed unless you call the function, whereas code on the module level is executed immediately as the module is imported. So put foo.attr = ... into the function body iff you want it to execute every time the function is invoked; otherwise put it into the module startup code, i. e. do not indent it. Peter From claird at lairds.com Mon Sep 1 09:24:58 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 01 Sep 2003 13:24:58 -0000 Subject: Python Documentation? References: Message-ID: In article , Larz wrote: >claird at lairds.com (Cameron Laird) wrote in news:vl6dmm8jutl140 >@corp.supernews.com: > >> Python already has a structure--and much content!--for >> comparable collaboration in > www.python.org/cgi-bin/moinmoin/ >. Moreover, as several >> follow-ups have explained, Python developers have differ- >> ent work practices than PHPers, and a different relation >> to documentation. In particular, it's hard to overempha- >> size how much working Python programmers depend on >> interactive introspection: use of the interpreter's >> built-in help, pydoc, and related facilities to discover >> and confirm details that, in PHPonia, are regarded as >> matters for online documentation. > >Yes, I agree that a lot of python programmers think differently. >Even though, I sense a general consensus, especially among beginning >Pythoneers, that the community lacks a great tool, like the one PHP has. >Of course I am not just thinking about the documentation itself, which you >could get with pydoc/help(), but also experience, pointers, pitfalls that >other people ran in to. That's what makes it a community ;) > >Anyway, I am pretty sure we're going to fill a much needed niche, and if >not, we're certainly going to meet our own needs ;) . . . Larz, my own career has been almost entirely an exploration of the relation between meeting my own needs and filling much-needed niches; any words of support would be only superfluous. I fear, though, that I didn't write clearly. I made *two* observations; not only do Pythoneers rely on introspection, but we *already* have a vehicle for sharing code examples, commentary, and related matters: the Wiki (complementing, incidentally, the Cookbook). -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From llothar at web.de Sat Sep 20 06:53:11 2003 From: llothar at web.de (Lothar Scholz) Date: 20 Sep 2003 03:53:11 -0700 Subject: Webware and RAM! References: Message-ID: <6ee58e07.0309200253.e7a6d90@posting.google.com> JZ wrote in message news:... > How much memory WebKit should normally take??? As I can see, every > WebKit daemon takes over 40MB (sic!) of RAM. WebKit lauches 10 daemons > during startup, so I need over 400MB for WebKit alone! Is it > normal or I have something wrong configured? Are you sure that you count only the really used memory. I haven't used Linux in the last two years but i remember that some tools display wrong sizes (adding all dynamic libraries and even the XFree Graphic card memory). The basic memory consumption of webware on Windows is around 5 MB. From mpeuser at web.de Thu Sep 18 15:26:51 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 18 Sep 2003 21:26:51 +0200 Subject: How to pass parameter to a module? References: Message-ID: "M-a-S" > I thought about the third module. It doesn't sound good. > I hoped there're some tricks with __dict__, frames and > other __...__ objects. > Well, there are some tricks ;-) myVariable='great surprise' import x ....... "This is modul X" import sys print sys.modules['__main__'].myVariable But generally the namespace of a module is ... the module. Kindly Michael P From zanesdad at bellsouth.net Tue Sep 2 11:59:40 2003 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 2 Sep 2003 11:59:40 -0400 Subject: Docs on speeding up Python code? In-Reply-To: ; from a.neudecker@uni-bonn.de on Tue, Sep 02, 2003 at 05:17:41PM +0200 References: Message-ID: <20030902115940.A18621@cerberus.liberty> * Andreas Neudecker (a.neudecker at uni-bonn.de) wrote: > Hi. > > I have seen some discussions going on about making Python code faster > and several measures looked fairly 'esoteric' to me (i.e.: you need to > know a lot of background things to even KNOW about these possibilities). > > Is there anywhere a concise Howto, article, PEP, whatever that describes > possible measures to make Python code faster (and probably 'cleaner', > too)? And possibly in a way, that a beginner or intermediate Python user > can understand? ;-) > > If you know of any such docs, I would be happy if you could post some links. > > > Regards > > > Andreas One link that has helped me out is http://manatee.mojam.com/~skip/python/fastpython.html. I got a considerable performance boost on a parser that I wrote by following his suggestions (specifically doing things over and over and the use of the profiler). HTH Jeremy Jones From fperez528 at yahoo.com Mon Sep 8 02:55:06 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 08 Sep 2003 00:55:06 -0600 Subject: negative indices for sequence types References: Message-ID: dan wrote: > I was recently surprised, and quite shocked in fact, to find that > Python treats negative indices into sequence types as if they were > mod(length-of-sequence), at least up to -len(seq). > > This fact is *deeply* buried in the docs, and is not at all intuitive. Very deeply indeed: section 3.1.4 of the beginner's tutorial: http://www.python.org/doc/current/tut/node5.html#SECTION005140000000000000000 Of all places, this is the section on lists: >>> a = ['spam', 'eggs', 100, 1234] [... snip ...] >>> a[-2] 100 >>> a[1:-1] ['eggs', 100] > Can anyone explain why this anomaly exists, and why it should continue > to exist? Because this 'anomaly' is incredibly useful in many contexts, as many others have already pointed out. Rest assured that it will continue to exist, probably for as long as the language is around. Better get to like it :) Cheers, f. From martin at v.loewis.de Thu Sep 11 14:15:15 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 11 Sep 2003 20:15:15 +0200 Subject: Building Imaging-1.1.4 on Solaris 9 References: Message-ID: "Mark Nelson" writes: > Imaging -ljpeg -lz -o build/lib.solaris-2.9-sun4u-2.2/_imaging.so > Text relocation remains referenced > against symbol offset in file > 0x14c libImaging/libImaging.a(Unpack.o Recompile Unpack.o with -fPIC. Regards, Martin From aleax at aleax.it Fri Sep 26 13:29:13 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 17:29:13 GMT Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> Message-ID: David Abrahams wrote: ... > Also, the idea of denying tuples the ability to reverse iterate seems > arbitrary and capricious. Sure, but so is denying them, e.g., non-mutating methods such as .index() and .count(). At least we're _consistently_ arbitrary and capricious!-) Alex From rudy.schockaert at pandora.be Sat Sep 20 06:26:16 2003 From: rudy.schockaert at pandora.be (Rudy Schockaert) Date: Sat, 20 Sep 2003 10:26:16 GMT Subject: SMTPlib Emailing Attachments In-Reply-To: <4fd6e92.0309191333.20114e3@posting.google.com> References: <4fd6e92.0309170849.287e86b6@posting.google.com> <4fd6e92.0309190518.3b226735@posting.google.com> <4fd6e92.0309191333.20114e3@posting.google.com> Message-ID: <3F6C2B3F.3060207@pandora.be> Bill wrote: > Karl Scalet wrote in message news:... > >>Bill wrote: >> >> >>>[...] >>>path = 'C:\\YourPath\\YourFile.txt' >>>filename = 'YourFile.txt' >> >>is this correct? Shouldn't path contain the directory only? >>Otherwise what's the content of YourFile.txt then. >> >>Karl > > > Well I believe you need the file as well b/c the mimetypes function > checks the extension to see what type of file it is. I am sure you can > modify it to be more efficient. But it works as is. Path and filename are two distinct items. The first points to the physical file, the other is the name the attachment will get in the mail. This way you also have the flexibility to name the file once attached different than the version on disk. From Ian.Sparks at etrials.com Tue Sep 30 08:54:46 2003 From: Ian.Sparks at etrials.com (Ian Sparks) Date: Tue, 30 Sep 2003 08:54:46 -0400 Subject: Package question. Message-ID: <41A1CBC76FDECC42B67946519C6677A9C59AB7@pippin.int.etrials.com> This makes sense, thanks. -----Original Message----- From: Scott David Daniels [mailto:Scott.Daniels at Acm.Org] Sent: Monday, September 29, 2003 7:43 PM To: python-list at python.org Subject: Re: Package question. Ian Sparks wrote: > ... On Windows, I want to set up a package structure like : > Fred\ > Bob\ > test.py > So I can say : > from Fred.Bob import * > To do this I need to put the package on the python path. > So I drop this into my python root in a file called Fred.pth : > C:\Fred\ > Now to make sure that Fred and Bob both look like packages with > empty __init__.py files like so : > C:\Fred\ > __init__.py > C:\Fred\Bob\ > __init__.py > test.py > so : > C:\python.exe -c from Fred.Bob import * > OK! But this is a lucky accident. If you do: import sys for number, name in enumerate(sys.path): print number, repr(path) You'll see (I suspect) that '' is on your path, and the Fred.pth value is irrelevant (it adds an entry for 'C:\\Fred\\', which allows you to import from Bob, not Fred. You Fred.pth file should list the directory _containing_ Fred (in this case, 'C:\\', not 'C:\\Fred\\'). Note, you'll still be surprised soon, because I suspect you think that after: from Fred.Bob import * you can freely use: test.somefunction() -Scott David Daniels Scott.Daniels at Acm.Org -- http://mail.python.org/mailman/listinfo/python-list From john at rygannon.com Thu Sep 4 18:23:02 2003 From: john at rygannon.com (BadJake) Date: Thu, 4 Sep 2003 22:23:02 GMT Subject: ANN: Rekall V2.1.0 beta1 Message-ID: <3f57bb6b$0$206$fa0fcedb@lovejoy.zen.co.uk> Rekall 2.1.0 Beta1 is out The following is a list of new features new in this release *Macros Rekall 2.1.0 introduces macros, in the same sense as another well known database front end. Like python scripts, macros can be stored either in separate macro objects. Macros are intended to provide a quick and easy way to provide basic automation without needing a knowledge of the python programming language. Beta1 has a basic set of macros, to be extended. *Printing Report data view now features a drop-down page selector for quick navigation where your report has a large number of pages. There is also a print this page button. Also (under KDE) you can control the printing DPI, to handle some obscure situations (like running Rekall/KDE under Gnome). *Wizards At last! Wizards. Initially wizards will be available to handle database connection setup, and form and report creation (Beta1 has rather basic connection and form wizards) *Printing Under KDE3.1 (not 3.0) report data view has a page-selection tool and print-page button. You can also set the DPI to handle situations like running Rekall under Gnome, which uses a different resolution. *Copier The copier can now use rekall-level queries as a data source, and also XML in a restricted format. Column name information can be passed from the source to the destination. *Dumper and Loader Rekall now comes with database dumper and loader functions, which can be used to dump a database to a set of files, and to reload from the files. Note that this is primarily intended for use with databases created with rekall, and should not be viewed as a substitute for the RDBMS tools. *Bugs A whole bunch of bugs have been fixed (and, no doubt, a few more slipped in). Please report the new ones! Please visit http://www.rygannon.com for more information and to download a copy of the demo Best Regards John From newsgroups at jhrothjr.com Mon Sep 22 21:47:05 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 22 Sep 2003 21:47:05 -0400 Subject: Thoughts on PEP315 References: Message-ID: "Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in message news:oalumvopu9afuhno85tbp2erl52rk9hht1 at 4ax.com... > > PEP315 (Enhanced while loop) suggests a syntax as follows... > > do: > ... > while condition: > ... I've snipped the rest of your lengthy analysis because I think the problem is much deeper, and is essentially insoluble given the structure of Python. The difficulty is that there is no clear and obvious way of distinguishing subordinate groupings from the main grouping. Consider the if statement: if something: blah blah elif something_else: blither else: bletch If we look at this, without knowing the syntax of the if statement, it looks like three primary statements. There is no a priori way of knowing, from the lexical structure of the language, that elif and else cannot occur by themselves, but must be preceeded by a specific statement. You need the additional layer of the syntactic relationships. Consider the same structure in Ruby: if something blah blah elsif something_else blither else bletch end The thing that makes all the difference is the "end" statement which closes the if. The elsif and the else are clauses within the if statement, and there is no way of missing that fact even if you don't know the exact syntax of the if structure. If we now go back to the loop suggestion, it becomes rather obvious what needs to be done: do: bibbity bobbity boo while condition # note the lack of a colon! This is at least unambiguous as to what is going on. I don't, by the way, think that we need this particular piece of syntactic sugar, regardless of the syntax we dress it up in. John Roth > > > -- > Steve Horne > > steve at ninereeds dot fsnet dot co dot uk From martin at v.loewis.de Thu Sep 4 15:53:18 2003 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Thu, 04 Sep 2003 21:53:18 +0200 Subject: xml.dom.minidom - bug ? future ? In-Reply-To: References: Message-ID: Roman Yakovenko wrote: > Hi. What I don't understand is why I dump to xml string that contains > new - lines and when I read it from xml new lines replaced by spaces. > May be I do something wrong? You should not use new line characters in attribute values. According to the XML specification, the XML processor must replace them with white space, see http://www.w3.org/TR/REC-xml#AVNormalize Regards, Martin From vze4rx4y at verizon.net Tue Sep 23 20:30:31 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 24 Sep 2003 00:30:31 GMT Subject: Pre-PEP: reverse iteration methods Message-ID: Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ------------------------------------------------------------- PEP: 323 Title: Add Reverse Iteration Methods Version: $Revision: 1.1 $ Last-Modified: $Date: 2003/03/11 04:49:44 $ Author: Raymond Hettinger Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 23-Sep-2003 Python-Version: 2.4 Post-History: 23-Sep-2003 Abstract ======== This proposal is to extend the API of several sequence types to include methods for iterating over the sequence in reverse. Motivation ========== For indexable objects, current methods for reverse iteration are error prone, unnatural, and not especially readable:: for i in xrange(n-1, -1, -1): print seqn[i] One other current approach involves reversing a list before iterating over it. That technique wastes computer cycles, memory, and lines of code. Also, it only works with lists (strings, for example, do not define a reverse method):: rseqn = list(seqn) rseqn.reverse() for elem in rseqn: print elem Reverse iteration is much less common than forward iteration, but it does arise regularly in practice. Proposal ======== Add a method called iter_backwards() to sequence objects that can benefit from it. The above examples then simplify to:: for i in xrange(n).iter_backwards(): print seqn[i] for elem in seqn.iter_backwards(): print elem The new protocol would be applied to lists, strings, xranges objects, and possibly other sequence objects as well (depending on use cases and implementation issues). It would not apply to unordered collections like dicts and sets. No language syntax changes are needed. Open Issues =========== * Should tuples be included? In the past they have been denied some list like behaviors such as count() and index(). * Should file objects be included? Implementing reverse iteration may not be easy though it would be useful on occasion. * Should enumerate() be included? It would only provide reverse iteration whenever the underlying sequence supported it. Copyright ========= This document has been placed in the public domain. From grante at visi.com Fri Sep 5 11:55:34 2003 From: grante at visi.com (Grant Edwards) Date: 05 Sep 2003 15:55:34 GMT Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> Message-ID: <3f58b1f6$0$155$a1866201@newsreader.visi.com> In article , John Roth wrote: > > "Grant Edwards" wrote in message > news:3f58a2bd$0$156$a1866201 at newsreader.visi.com... >> In article , John Roth wrote: >> >> > Technically, it would be possible to make "self" a reserved >> > word, and not have to put it in the method declaration. >> > However, there are a lot of people who use something other than >> > the word "self," so that would break existing code. >> >> It would also make the language more complex and irregular. > > How? 1) It would add a reserved word. 2) It would mean that there's some sort of difference between a function and a method. -- Grant Edwards grante Yow! I have a TINY BOWL in at my HEAD visi.com From xavim at fqingenieria.es Thu Sep 25 05:39:46 2003 From: xavim at fqingenieria.es (=?iso-8859-1?Q?Xavier_Mart=EDnez?=) Date: Thu, 25 Sep 2003 11:39:46 +0200 Subject: getting a value from a web-page References: Message-ID: <002801c38348$f638afe0$0102a8c0@xavim> > > Is it possible to get a row from a text-file? This text-file is located > > in a web page. > > I'm not sure exactly what it is you are trying to achieve, but you > might be able to use the urllib() module to download the file. I > recall the existence of a module which can efficiently extract > specified rows from a text file - but, alas, I don't recall its name. > But it wouldn't be strictly necessary, anyway. Have a look at 'linecache' module. This will only work with a local file, though, so you need to retrieve the file, see urllib.urlretrieve() at: http://www.python.org/doc/current/lib/module-urllib.html See also: http://www.python.org/doc/current/lib/module-linecache.html and: http://gnosis.cx/TPiP/chap1.txt (a chapter of David Mertz's book 'Text Processing in Python'). From martin at v.loewis.de Sun Sep 28 16:03:45 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 28 Sep 2003 22:03:45 +0200 Subject: unicode 3 digit decimal conversion In-Reply-To: References: Message-ID: <3F773EA1.4010802@v.loewis.de> Rune Hansen wrote: > Stalker told me to send the letter "?" as \248 or as xf8 (notice the > missing "\"). At this point I'm sending > quoteattr(unicode('string',"iso-8859-1).encode("utf-8")) which is > neither of the above.(..?). Correct: UTF-8 works differently. I find it surprising that anybody actually proposes to send non-ASCII characters using xHH, as this byte sequence my coincidently happen in ASCII text as well. > Anyway, the server is still happy, and the data views correctly in the > web interface. It is relatively easy to recognize UTF-8 in the input; it is unlikely that "real" data look like UTF-8 by coincidence (unlike \-escaping or x-escaping). So it might be that the server studies the input to guess the encoding. This is bad style, of course - the protocol should be clear about encodings (this protocol couldn't be published in an IETF RFC). > Stalker provides a perl and java API for the telnet server. I don't > read perl code very well, and the java API is distributed as .class > files(nothing new there, it's java after all) so I really don't know how > Stalker is handling it. Even then, you could only find out what the perl and java clients do - you couldn't tell, from that, what other options the server might support. Regards, Martin From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 12:31:08 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 17:31:08 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <_9Vbb.105320$hE5.3711223@news1.tin.it> Message-ID: On Tue, 23 Sep 2003 14:29:44 GMT, Alex Martelli wrote: >I'd rather >have the missing upper bound be an error in this case (and rely on >itertools.count for very explicit building of infinitely looping >iterators) than "easily create infinities" in response to typos;-). I probably agree - convenience is nice, but easy-to-make errors are somewhat less nice. A compulsory upper bound is probably a good idea. Though maybe explicitly recognising the strings "+inf" and "-inf" in slice.stop would be reasonable? -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From FBatista at uniFON.com.ar Fri Sep 12 10:35:54 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 12 Sep 2003 11:35:54 -0300 Subject: read from file Message-ID: #- read? I don't want to re-read the entire file, because that #- is a whole #- lot of data!! You can open the file, seek to the last position read, read to the end of the file, save this position for the next time, and so on... I'm more concerned about blocking. . Facundo From FBatista at uniFON.com.ar Thu Sep 25 09:43:20 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 25 Sep 2003 10:43:20 -0300 Subject: "for" with "else"? Message-ID: #- Is this to be expected? #- (python 2.2.2) The else after the for is always executed, except when you break the for: >>> for i in range(3): print i else: print "done" 0 1 2 done >>> for i in range(3): print i if i > 1: break else: print "done" 0 1 2 >>> . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rebel at removethis.rebel.com.au Thu Sep 4 22:53:58 2003 From: rebel at removethis.rebel.com.au (Chris) Date: Fri, 05 Sep 2003 02:53:58 GMT Subject: Embedded Perl or Python (XPost) Message-ID: Hi I am posting this on both the perl and python groups My intention is not to start a war or anything else, I would just like some pragmatic advice. My apologies to the python group I am not very conversant with Python at this stage. that could change soon though. OUTLINE I am developing a software project where a major portion of it is to enable script access to c++ classes The idea is to extend the basic functionality of the program by allowing third parties to write add ons that are called by my c++ classes as virtual functions. So if I call vfunction(); and an add on has been written that redefines this function (and possibly calls the base c++ function) that it is called correctly. I have chosen perl and python as my preferred languages because of the large developer base for add ons The interpreter will only have a subset of the standard funtionality, for example sockets will be removed. QUESTION Given the above which interpreter is most likely to fit my bill with the smallest footprint ? Thanks in advance Chris From bgailer at alum.rpi.edu Fri Sep 19 12:47:56 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri, 19 Sep 2003 10:47:56 -0600 Subject: \r for newline in readlines function In-Reply-To: References: Message-ID: <6.0.0.22.0.20030919104658.03a0b9b8@66.28.54.253> At 10:37 AM 9/19/2003, Leeds, Mark wrote: >I did more investigation into my previous problem >and what happens is that my text file has \r for representing >a new line instead >of a \n. is there a way to tell the readlines >function that the symbol for a newline is \r rather >than \n ? right now the readlines function reads >the\r as another item in the list and just puts >everything into one big list because it >doesn't find any new line characters. > thanks. i'm really stuck because >i can't read my data right now. bigList = foo.readlines() niceList = bigList.split('\r') Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From mwh at python.net Mon Sep 1 08:28:51 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 1 Sep 2003 12:28:51 GMT Subject: super question References: Message-ID: <7h3k78s3dc3.fsf@pc150.maths.bris.ac.uk> Gon?alo Rodrigues writes: > Hi, > > Ok, now I'm really confused. What is supposed > > super(, ) > > to do? My *guess* (and it is very much a guess) is that super(, ) is intended to be used in classmethods. Cheers, mwh -- Wise frogs would take sanctuary in the cool moistness of the cat's milk-dish, from where they would watch you. It's worrying being watched by a milk-dish. -- Tanuki the Raccoon-dog, asr From dave at pythonapocrypha.com Thu Sep 18 15:49:11 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 18 Sep 2003 13:49:11 -0600 Subject: mutex? protecting global data/critical section In-Reply-To: <3F6B5491.9020907@sympatico.ca> References: <3F6B5491.9020907@sympatico.ca> Message-ID: <200309181349.11516.dave@pythonapocrypha.com> On Friday 19 September 2003 01:10 pm, Brian Alexander wrote: > Hello; > > I am trying to protect some global data, which may, in the future, be > accessed by threads. I'm not sure how to implement a locking mechanism > in python. Here is the idea I'm trying to express: > > class resourceManager(object): > def __init__(self): > self.__resources = 100 > > def getResource(self): > BEGIN CRITICAL SECTION HERE > if self.__resources > 0: > self.__resources -= 1 > * other related state information adjusted, too * > else: > emergencyCode() > END CRITICAL SECTION HERE > > How is this accomplished? Does anyone know of a simple example? The basic idiom is to create a lock object somewhere: lock = threading.Lock() ... and then your critical section looks like: lock.acquire() try: dostuff finally: lock.release() -Dave From tzot at sil-tec.gr Fri Sep 5 12:13:21 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 05 Sep 2003 19:13:21 +0300 Subject: How do I match this with re References: <1ED4ECF91CDED24C8D012BCF2B034F13031B74D2@its-xchg4.massey.ac.nz> Message-ID: On Fri, 5 Sep 2003 11:54:56 +1200, rumours say that "Tony Meyer" might have written: [snip: my mentioning of the usefulness of the redemo.py script] >For those that like a more GUI sort of thing, I highly recommend kodos: > > > >Basically the same thing but with a GUI. All in Python, of course. I browsed the kodos home page and it seems interesting, but you do know that redemo.py is a Tkinter program and already has a GUI, don't you? Because "basically the same thing but with a GUI" should be changed into "basically the same thing but with a QT-based GUI". -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From jdhunter at ace.bsd.uchicago.edu Wed Sep 17 16:07:36 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 17 Sep 2003 15:07:36 -0500 Subject: Money data type In-Reply-To: ("Batista, Facundo"'s message of "Wed, 17 Sep 2003 15:28:34 -0300") References: Message-ID: >>>>> "Batista," == Batista, Facundo writes: Batista,> Can't find it. I mean something like: This has come up a few times before. Check google groups -- search for money group:comp.lang.python John Hunter From john at rygannon.com Mon Sep 15 12:09:09 2003 From: john at rygannon.com (John Dean) Date: Mon, 15 Sep 2003 17:09:09 +0100 Subject: Could somebody please explain what is happening .... References: <3f657f95$0$10968$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <3f65e28b$0$11003$fa0fcedb@lovejoy.zen.co.uk> John Dean wrote: > Hi > > I have been reading quite a lot of Python source code recently and I have > come across a particular construct which I don't understand. I would be > grateful if somebody could explain the reason for including the following > lines of code. I have seen it only at the beginning of a module:- > > global sys > import sys > > global os > import os > > .... > .... > > I know what global means and I know what import means but what is the > reason for making an imported module global? > Thank you to all who posted an answer. I was begining to think I was going nuts or something. Even though I am new to Python I knew something was wrong --- Best Regards John From fuerte at sci.fi Tue Sep 16 14:43:37 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Tue, 16 Sep 2003 21:43:37 +0300 Subject: [Python-Dev] Making python C-API thread safe (try 2) In-Reply-To: <007a01c37c7f$c5fc6850$21795418@dell1700> References: <007a01c37c7f$c5fc6850$21795418@dell1700> Message-ID: <3F6759D9.6030304@sci.fi> Brian Quinlan wrote: >>There is no object-level locking in my proposal. Just independent >>free-threaded interpreters, which don't see the objects of other >>interpreters at all. >> >> >OK, but this is useless to the average Python programmer. It is only >useful to people embedding Python interpreters in multithreaded >applications. I would imagine that this represents <1% of Python users. > No, all Python developers who create threads would benefit as well. It's probably another 1%. >>There could be an extra global interpreter state for shared-memory >>object access. Accessing this would always be synchronized, but only >>this. Python would automatically copy data from this state to >>thread-local state and back when needed. This would require a special >>syntax for variables in global state: >> >> > >So now you want to change the language definition for the benefit of a >small minority of users? > > No, change the language definition (if needed) for the benefit of real multitasking. Harri -------------- next part -------------- An HTML attachment was scrubbed... URL: From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Sep 22 23:39:14 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 04:39:14 +0100 Subject: Thoughts on PEP315 References: Message-ID: On Mon, 22 Sep 2003 21:47:05 -0400, "John Roth" wrote: > >"Stephen Horne" <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> wrote in >message news:oalumvopu9afuhno85tbp2erl52rk9hht1 at 4ax.com... >> >> PEP315 (Enhanced while loop) suggests a syntax as follows... >> >> do: >> ... >> while condition: >> ... > >I've snipped the rest of your lengthy analysis because I think >the problem is much deeper, and is essentially insoluble given >the structure of Python. > >The difficulty is that there is no clear and obvious way of >distinguishing subordinate groupings from the main grouping. > >Consider the if statement: > >if something: > blah blah >elif something_else: > blither >else: > bletch > >If we look at this, without knowing the syntax of the >if statement, it looks like three primary statements. >There is no a priori way of knowing, from the lexical >structure of the language, that elif and else cannot >occur by themselves, but must be preceeded by >a specific statement. You need the additional layer >of the syntactic relationships. I disagree. You seem to saying that the *only* relevant aspect of the lexical structure is the use of indentation and colons. I say the use of distinctive keywords for continuation-of-same-block-structure such as 'elif' or 'else' is easily sufficient clarification. The PEP315 system of... do: ... while condition : ... is IMO broken simply because there is no lexical indicator in that 'while' line that it is a continuation rather than a new structure. It isn't a distinctive keyword because 'while' can obviously be the start of a loop. 'break if :', however, is lexically clear at the point where it is written - the 'break' on itself isn't distinctive, but the 'if' following straight after makes it unambiguous that this is a continuation of an existing loop rather than a separate break statement. >Consider the same structure in Ruby: > >if something > blah blah >elsif something_else > blither >else > bletch >end > >The thing that makes all the difference is the "end" >statement which closes the if. The elsif and the else >are clauses within the if statement, and there is no >way of missing that fact even if you don't know the >exact syntax of the if structure. If you don't know the syntax of such fundamental things as the basic block structures in the language, you really shouldn't be reading or writing code IMO. Especially when these are such common concepts among languages that you should be able to understand it even if you've never used Python, simply from experience of virtually any other imperitive language. >If we now go back to the loop suggestion, >it becomes rather obvious what needs to be >done: > >do: > bibbity > bobbity > boo > while condition # note the lack of a colon! Yuck!!! This is really no different to the following, which is quoted in the PEP as something to move away from... while True : ... if condition : break ... The fundamental problem is that the exit point is not obvious because it is 'hidden' in the detail of the loop - it is a statement within the loop body instead of being lexically a part of the loop. Imagine if the if statement with an else clause were written... if condition : statement; statement; statement; else; statement; statement; statement; That is basically the situation with break at the moment - it is a feature of the loop, but it is not lexically related to the loop. It is IMO useful in terms of readability to make the exit point lexically a part of the loop - to write it at the same indent level and to add on the colon. This is somewhat novel - I can't think of a language that does that. Ada does have 'exit when' but it treats it as if it were any other statement in lexical terms. Of course Ada programmers are free to put the 'exit when' at any indentation level they like, and the approach of matching it to the indent level of the start-of-loop line is in my experience far from unusual. Anyway, the thing is that just because it is unconventional doesn't mean that it's wrong. Treating 'break' and 'continue' as just another statement is IMO a mistake. There is an advantage - being able to break out of the loop from a nested structure (such as an if) but if the break is conditional anyway, that justification mostly disappears. >This is at least unambiguous as to what is >going on. I don't think 'break if' would be unambiguous. I think it would be less unambiguous than your suggestion, in fact, for two reasons... 1. Your suggestion is distinct from having an inner while loop *only* because it lacks a colon at the end of the 'while' line. That, IMO, is a recipe for confusion. 2. Your suggestion has the 'while' line as a standard statement, and thus at the same indentation level as any other statement. When reading code it would be very easy to miss this loop exit point. >I don't, by the way, think that we need this >particular piece of syntactic sugar, regardless >of the syntax we dress it up in. You may be right - but the PEP still exists, has been around since April without being rejected, and claims to be scheduled for inclusion in 2.4. Syntactic sugar is basically what high level languages are about - readability and maintainability being the key benefits (though you are free to write machine code directly in hex - to avoid the syntactic sugar called assembler - if you really want) - but the syntax currently described strikes me more as syntactic vinegar. An alternate syntax proposal seems to me more of a positive way forward. Though my record in these matters is somewhat less that 100% (around 0% in fact) so feel free to call me an idiot. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From raizor at rtcwonline.com Sat Sep 6 14:49:52 2003 From: raizor at rtcwonline.com (raizor at rtcwonline.com) Date: 6 Sep 2003 18:49:52 -0000 Subject: Unreachable Message-ID: <20030906184952.24153.qmail@amerihosting.com> This email address is unreachable. It has been closed. From vze4rx4y at verizon.net Thu Sep 18 01:18:25 2003 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Thu, 18 Sep 2003 05:18:25 GMT Subject: Where's UserList.ListMixin? References: <3a8e83d2.0309172019.74d6fca9@posting.google.com> Message-ID: [Matthew Barnes] > This may be a naive question, but since Python 2.3 added a handy > little DictMixin class to its UserDict module it seems to me like > UserList.ListMixin and maybe even UserString.StringMixin should have > followed (although I'm not sure how useful a StringMixin class would > really be). Use cases have to come first. Do you see modules in the library or in common applications where this has immediate use? When I developed DickNixon, er, DictMixin (not the former President), there were immediate applications in shelve, dumbdbm, and some of my own apps. As a starting point, look in calendar.py to see whether your idea would have helped implement _localized_day and _localized_month. I think these classes are typical of objects that try to dynamically simulate list behavior. > Should I submit a patch? It is best to start by submitting a recipe to the ASPN Cookbook. There, the idea can be refined, use cases established, and a fan club formed. At that point, it could be a candidate for inclusion in Py2.4. It may be best to start which an easier challenge like TupleMixin and then add mutuable behaviors to a ListMixin subclass. An even easier start is to build a RichComparisonMixin that transforms == and < into <=, >, >=, and !=. If you want to show-off your agile programming skills, develop the unittest cases before you write your code. The most important part of the design is thinking out which methods should be the primitives and whether there should be multiple levels so that the most natural overrides get used by higher levels (see the DictMixin code if you don't know what I'm talking about here). Try to keep your thinking grounded in reality by examining real modules which would benefit from subclassing the mixins. Also, I'm curious as to how you would implement the sort() method without actually manifesting the whole virtual list; otherwise, you might as well use list(iterable) and get a real list (which, BTW, is what _localized_day does using a list comprehension). Good luck with your project, Raymond Hettinger From peter at engcorp.com Thu Sep 18 09:24:54 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 18 Sep 2003 09:24:54 -0400 Subject: ASN.1 source reader References: <3F69B497.CEF764ED@siemens.com> Message-ID: <3F69B226.FB267166@engcorp.com> Tomas Kukosa wrote: > > does anybody know any way how to read ASN.1 source into Python? > I can not find any ASN.1 parser. Which pages in http://www.google.ca/search?q=python+asn.1 were not helpful for you, and why? -Peter From aleax at aleax.it Fri Sep 26 06:49:39 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 10:49:39 GMT Subject: __init__ return value References: <16241.58373.833630.615370@montanaro.dyndns.org> <6.0.0.22.0.20030924124805.0346ed20@66.28.54.253> Message-ID: <7RUcb.124463$hE5.4246449@news1.tin.it> Skip Montanaro wrote: > > >> No, __init__ method return values are always ignored. > > Bob> Oh? > > >>>> class A: > Bob> ... def __init__(self): > Bob> ... return 'asdf' > Bob> ... > >>>> A() > Bob> Traceback (most recent call last): > Bob> File "", line 1, in ? > Bob> TypeError: __init__() should return None > > My apologies. It is checked and an exception raised if it's not None. > That's an implementation detail, not a property of the language. Actually...: >>> import this The Zen of Python, by Tim Peters [snip] Errors should never pass silently. Unless explicitly silenced. I _would_ call this "a property of the language". Returning not-None from __init__ is most likely an error: ignoring that error silently by default would be very un-Pythonic indeed. As a point of contrast, look at Ruby -- a pretty neat language with a semantic level and application niche QUITE close to Python's, but most definitely NOT having "errors should never pass silently" as a property of the language. Most fundamental errors, say indexing an array with an index outside of the array's bounds, DO pass silently in Ruby -- returning nil (like Python's None) for indexing-reads out of bounds, silently and implicitly padding the array with nil's for indexing-writes out of bounds. I think this language property and its practical implications make an ENORMOUS difference to the approach one takes when programming in the two different languages... Alex From petitmermet at mat.ethz.ch Fri Sep 19 07:41:19 2003 From: petitmermet at mat.ethz.ch (Marc Petitmermet) Date: Fri, 19 Sep 2003 13:41:19 +0200 Subject: utf-8 encoding issue Message-ID: The line below looks up the name "?ttinger" (with the German umlaut) of an author using the mysql console: mysql> select author from records where author like '%Öttinger%'; This successfully finds all entries in the records database where "?ttinger" is the author or the co-author. In a web form, the user enters "?ttinger" and wants to search with this search string. My idea is now to convert the search string (which also could be e.g. some cyrillic text) into unicode and then to utf-8: unicode(search_string).encode('utf-8') This gives me the utf-8 encoded version of the string but not yet in the correct representation. How can I get the correct one (is this the hex version? I don't know the correct terminology.)? In short: how do I e.g. convert a sting containing a "?" into a string containing a "%Ö"? Regards, Marc From newsgroups at jhrothjr.com Mon Sep 22 15:03:30 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 22 Sep 2003 15:03:30 -0400 Subject: Mailbox cleaner on an IMAP basis? References: <3f6f2cfb@news.swissonline.ch> Message-ID: "F. GEIGER" wrote in message news:3f6f2cfb at news.swissonline.ch... > Hi all! > > As I saw Alex Martelli's post about a mbox cleaner based on POP3, I thought, > it could be possible to do that based on IMAP too. That way I could ask the > server for mails having attached EXE files and delete all those mails on the > server. This would save me a lot of traffic over my phone line connection. > > But I'm missing one important thing: How do I get the server to tell me > about attachments. > > What I've found out so far is how to get at the fields: > > r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS])") > > Alas, there's no such thing like 'filename' or 'attachments'. > > And > > r, d = i.fetch(1, "(BODY.PEEK[HEADER.FIELDS (Content-type)])") > > doesn't show a file name either. > > Any hints? Right now, I'd simply like something that would clean out an IMAP mailbox on a regular basis. Most of the worm generated garbage is going into one of two boxes on my server, and I get maybe one legitimate e-mail in those two boxes every couple of weeks. I can stand to lose that level of e-mail, I can't stand to exceed my disk quota and lose lots of legitimate mail every few hours. Could you post the code you've got so far? Thanks. John Roth > > Best regards > Franz GEIGER > > > > > From uwe.schmitt at procoders.net Mon Sep 8 08:10:12 2003 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 8 Sep 2003 12:10:12 GMT Subject: Ternery operator References: Message-ID: Andrew Chalk wrote: > Is there a python equivalent of the C ternery operator? > I.e.: > fred = (x == 1) ? 12 : 15 > If not, what's the best way to construct the same logic? fred = ( x==1 and [12] or [15])[0] or fred = [ 12, 15] [not x==1] Further hints / explanations at http://www.procoders.net/tutorials/boolean Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt http://www.procoders.net schmitt at procoders.net "A service to open source is a service to mankind." From rjc at tampabay.rr.com Tue Sep 30 13:02:47 2003 From: rjc at tampabay.rr.com (Robert Clayton) Date: Tue, 30 Sep 2003 17:02:47 GMT Subject: import _XXXXXX Message-ID: When a Python program declares import _XXXX. What form is XXXX when the underbar is included (_XXX)? Thanks From alanmk at hotmail.com Tue Sep 23 13:58:50 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Tue, 23 Sep 2003 18:58:50 +0100 Subject: Executing a python script from an HTML link? References: <1t%bb.407$Q44.601209120@newssvr11.news.prodigy.com> Message-ID: <3F7089DA.EB6E9969@hotmail.com> [Andrew Chalk] > I want to run the script on the server. Then you will need to figure out how to run the script on the server ;-) If you're not aware of how to do this, then it's probably best for you to read up on CGI, which is way of getting web servers to execute scripts (in any language) when the scripts URL is requested. > The problem is that I don't > have an html page as an HREF. Viz: > > Fred > What replaces Fred.htm to invoke a server-side script? Whatever is the URL of your script on your server. Examples include http://www.mydomain.com/cgi-bin/myscript.py http://www.mydomain.com/cgi-bin/myscript.cgi http://www.mydomain.com/cgi-bin/myscript.py?paramA=v1¶mB=v2 Your python script should then generate (i.e. print out) an HTML page when it is run (actually it can generate anything, images included, but HTML is a good place to start). The server takes the output of your script and sends it to the requesting browser. The browser has no way of knowing that the HTML did not come from a static file. You can read about Python and CGI here:- http://starship.python.net/crew/davem/cgifaq/faqw.cgi?req=index There are other "linkage mechanisms" by which you can cause the execution of scripts on a server, e.g. mod_python, but none is conceptually as simple as CGI. Also, CGI tends to be more portable between different server software, and is almost always supported by hosting providers. HTH, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From and-google at doxdesk.com Thu Sep 25 17:24:58 2003 From: and-google at doxdesk.com (Andrew Clover) Date: 25 Sep 2003 14:24:58 -0700 Subject: CGI Redirect to another page References: <09a3d6364c.tim@worthy.demon.co.uk> <2c60a528.0309240338.1e4dd261@posting.google.com> <87zngu14jn.fsf@pobox.com> Message-ID: <2c60a528.0309251324.109d4af5@posting.google.com> John J. Lee wrote: > I know I don't like them "on principle", but what practical problems > do they cause? Do proper HTTP redirects avoid the "back button trap", > maybe? Yes, they do. They are also more widely supported by robots (including search engine spiders) and older and non-desktop browsers (as well as newer browsers which can have meta-refresh and/or JavaScript disabled). An HTTP redirect is an unequivocal statement that a resource is elsewhere, at a transport level. It can be understood and acted on by agents with no knowledge of HTML or JavaScript (for example Python's urllib), and can potentially be used to automatically update links. Meta-refresh (or, less commonly used, Refresh as an HTTP header) was designed for re-fetching pages that update themselves, such as webcams. It's still useful for this, although it has yet to be standardised. Using meta-refresh or JavaScript for a redirect is really a misuse, and is needed only: a. When you need to set a cookie at the same time as doing a redirect. Some browsers will not allow a cookie to be set in anything but a '200 OK' response. b. When your web hosts are exceedingly crappy and don't allow you to do proper redirects through server config or CGI. In these cases I prefer to use JavaScript's location.replace() method (which also avoids the back button trap), combined with a short-delay meta-refresh as backup and a plain HTML link in the returned page as backup for the backup (for robots etc). Alan Kennedy wrote: > It is claimed that search engines treat meta-refresh with suspicion. > I don't know if this is true or not. It's not easy to tell, but Google is known to have 'anti-cloaking' measures for detecting search engine abuse. Since meta-refresh is commonly used for sending browsers to a different page than engines, it is possible that a meta-refresh - likely combined with other indicators Google could find suspicious - might result in a PR0 block. More importantly, many robots won't follow a meta-refresh at all. (After all, they don't want to end up following an infinitely refreshing webcam page.) So a backup link should always be included. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From jjl at pobox.com Fri Sep 5 15:32:53 2003 From: jjl at pobox.com (John J. Lee) Date: 05 Sep 2003 20:32:53 +0100 Subject: OT: best book in years References: <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <3F5868BA.85F506B4@engcorp.com> Message-ID: <87znhjkp3u.fsf@pobox.com> Peter Hansen writes: [...] > Perhaps, but I would have been happier to see a bunch of > suggestions for Mr. Useldinger to read, without the negative > comments about others' suggestions. Just doesn't feel right > to me. Call me mildly ticked, is all. Why? Honestly, I don't understand. You do understand our negative responses to weren't meant as a personal attack?? I certainly consider both positive and negative comments about books (or whatever) to be useful, especially when they come from from people (like you!) whose opinion I respect or when they give an illuminating argument. And, in fact, even when they don't even deign to give any reasons -- since that may tell you something in itself ;-) Sorry for ticking, but certainly not sorry for expressing an opinion. John From nav+posts at bandersnatch.org Sun Sep 7 09:01:39 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 07 Sep 2003 09:01:39 -0400 Subject: OT: best book in years References: <3F57861C.CE4C2AA9@engcorp.com> <87ptigcp7p.fsf@pobox.com> <3F57A9F5.F579219D@engcorp.com> <3F5868BA.85F506B4@engcorp.com> Message-ID: Patrick Useldinger writes: > Did I mention that it was *nothing* serious (unless the surgeon runs > into an uncatched exception...) :^) My comment was only half-serious. Maybe GEB looms in my memory because I was pretty young when I read it, I think I was in junior high school. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From dave at pythonapocrypha.com Sun Sep 7 19:23:28 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 7 Sep 2003 17:23:28 -0600 Subject: Eureka! (Re: Comments on Python Redesign) In-Reply-To: References: Message-ID: <200309071723.28316.dave@pythonapocrypha.com> On Monday 08 September 2003 10:43 am, Aahz wrote: > In article , > > Graham Fawcett wrote: > >Rather than throw stones, I have created a *brand new design* design for > >Python.org. I am certain that will satisfy both the technical users and > >the suit-wearing investigators. It borrows the time-honoured stylings of > >the old Python site, and blends them with some upscale business moxy. > > > >Take a look: > > > >http://tinyurl.com/mlcv > > Many people, me included, won't follow tinyurl links; please provide a > standard URL, too. Why? Are you worried that he'll redirect you to kiddie porn or something? From skip at pobox.com Fri Sep 5 10:35:39 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 5 Sep 2003 09:35:39 -0500 Subject: How to override distutils install? Message-ID: <16216.40763.547694.321664@montanaro.dyndns.org> I would like to override the distutils install class. It doesn't look like it was designed for that. Do I have to import distutils.command and overwrite its install attribute? I didn't see anything about this sort of thing in the distutils docs. Thx, Skip From mark at hahnca.com Mon Sep 1 12:57:23 2003 From: mark at hahnca.com (Mark Hahn) Date: Mon, 1 Sep 2003 09:57:23 -0700 Subject: I need a text editor written with text draw calls Message-ID: I am using wxPython (wxWindows) and need a simple non-styled text control with an arbitrary image background. Since wx does not support transparent colored backgrounds on controls, I'm being forced to use a simple pane with a bitmap loaded and write the text directly over the bitmap with text drawing calls. Does anyone know of any existing python code that implements the logic of a text control with direct calls to painting text on any canvas? I am not looking forward to writing this from scratch in this day and age. I toyed around for a while with the idea of implementing an off-screen control to a memory buffer and then converting the background color to a mask to blit onscreen, but then I realized controls only work onscreen. Then I thought of trying to use printing, but then found out controls can't go to a printer. Somebody somewhere in control heaven made the decision that controls would be forever only present on monitors with opaque backgrounds. Talk about an assumed design decision somewhere... From __peter__ at web.de Fri Sep 26 16:57:30 2003 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Sep 2003 22:57:30 +0200 Subject: Still need more feedback Re: Successful installation of mod_python on Apache on Win2k? References: Message-ID: Rolfe wrote: > Thank you. I have rechecked my config (shown below) - but I still > can't get the script (also shown below) to run in mod_python. I've > tried it in both the /cgi-bin/, and in /htdocs/test/: (just guessing) 1 The LoadModule path looks suspicous, on windows I would expect mod_python.dll rather than mod_python.so 2 Did you restart the apache after changing the config file? Peter From aahz at pythoncraft.com Sun Sep 7 15:54:50 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2003 15:54:50 -0400 Subject: Comments on Python Redesign References: Message-ID: In article , David Eppstein wrote: > >Lots of people have been rightly jumping all over the design. But >there's something else that I think is very important in the current >python.org front page and missing from the proposed redesign: the text >"Welcome to the official website for the Python language." Don't worry -- some people think that's redundant, but Guido has Prounounced that it will stay. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From gmuller at worldonline.nl Thu Sep 4 15:59:18 2003 From: gmuller at worldonline.nl (GerritM) Date: Thu, 4 Sep 2003 21:59:18 +0200 Subject: best book in years References: Message-ID: "Patrick Useldinger" schreef in bericht news:opruzmelopdd8opo at news.vo.lu... > Hi All, > > I am going to stay in hospital for a week or so (nothing serious), and am > trying to find a book or two to read there. As I have not come across > anything spectacular recently (except Python in a Nutshell), I would like > to know what *you* consider to be the best book you have read in the last > few years, about Python or IT in general. > > -Patrick During the holidays I have been reading Michael Crighton's book "Airframe". This is a nice thriller at the one hand, but I also liked it from professional perspective: the design of very complex, software intensive, systems. Unfortunately I don't know how much of the story is the authors fantasy and how close other parts might be to reality. regards Gerrit -- Gaudi systems architecting webpage: www.extra.research.philips.com/natlab/sysarch/ From harry.g.george at boeing.com Tue Sep 9 03:15:39 2003 From: harry.g.george at boeing.com (Harry George) Date: Tue, 9 Sep 2003 07:15:39 GMT Subject: Codesample for xml/xslt transforming References: Message-ID: "Thomas Guetttler" writes: > Am Tue, 09 Sep 2003 14:45:54 +0200 schrieb Axel Straschil: > > > Hello! > > > > Im fouling around with xml/xslt and zope. > > Now, im seraching for a simple codesample or link > > for a simple xslt-tranformation in python and libxml > > or 4Suite. > > I've test.xml, test.xsl or two vars with the code > > and wan't to transform it. > > Google just helped me for C ... > > 4suite contains examples and tests. You could see how they work. > > BTW, I used to waste a lot of time with xslt. > I think you are most of the time quicker with SAX for > parsing XML and "print" to create XML. > > thomas > I came to the same conclusion. XSLT's declarative paradigm runs out of gas just when the problem gets interesting. E.g., when the topology of the incoming data does not match that of the outgoing data. From there on in, you are tangled in xml-based procedural code. What I'd like to see is a good pattern or even code to help set up the SAX and print code given a neutral representation of the incoming and outgoing formats. The neutral reps should be generated from SQL, XSchema, RELAX/NG, csv headers, etc. Anything like that out there? -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From smory at ptdprolog.net Mon Sep 1 00:41:14 2003 From: smory at ptdprolog.net (Daniel R. Smorey Jr.) Date: Mon, 01 Sep 2003 00:41:14 -0400 Subject: Python Documentation? Message-ID: I'm looking for a good place for Python documentation. I'm really lost on why it's so hard to find anything when it comes to me looking up a particular function in Python. My example would be the split() function of the string module. Why can't I just go to www.python.org and click on Search and then type in split and it bring me to the split() function of the string module? Why does it have to be so hard? This is what I get when I search for split on www.python.org... http://search.python.org/query.html?qt=split&col=ftp&col=python&col=peps&col=starship Most of those hits are for the re module, not the string module (which in my opinion should be part of python and not a module, but I digress). Why would it not bring up the split function of the string module first and foremost? If I do a search right now on www.perldoc.com for split, I get... http://www.perldoc.com/cgi-bin/htsearch?words=split&restrict=perl5.8.0 Right there, the top hit is the slit function, how convenient. If I go to www.php.net and type in split in the function list search, I get... http://www.php.net/manual/en/function.split.php I don't even get a hit list, it goes right to the split() function. Even more convenient. I'm trying to learn Python because we're doing some work on the Zaurus and there are so many supporting python modules for the Zaurus, that I'd like to use it. I love learning new languages also. It just gives me a bad taste in my mouth when I even think of searching for anything in Python. Am I searching the wrong place? Am I choosing the wrong checkboxes on the Search page? I'm at a loss. Is it really that hard to find documentation on the python.org site? Thanks for hearing my rant and I'm hoping I'm just doing something wrong. I really can't imagine such an organized programming language having such a horrible search on their website. From bgailer at alum.rpi.edu Wed Sep 24 10:33:58 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 24 Sep 2003 08:33:58 -0600 Subject: Try/except vs. if/else In-Reply-To: <3F706279.9000203@bu.edu> References: <3F70598E.8020500@bu.edu> <3F706279.9000203@bu.edu> Message-ID: <6.0.0.22.0.20030924082607.0340e008@66.28.54.253> At 09:10 AM 9/23/2003, Shu-Hsien Sheu wrote: >Hi, > >In my understanding, using try/except rather than if/else is more pythonic. If/else and try/except are both Pythonic. In many cases you don't even get to choose. >However, sometimes it is difficult to use the later. >For example, I want to search for a sub string in a list composed of >strings. It is considered "possitive" if there is a match, no matter how many. > >my_test = ['something', 'others', 'still others'] > >case 1: try/except > >hit = 0 >for i in my_test: > try: > i.index('some') > hit = 1 > except ValueError: > pass > > > >case 2: if/else > >hit = 0 >for i in my_test: > if 'some' in i: > hit = 1 Consider breaking out of the loop at the first success for i in my_test: if 'some' in i: hit = 1 break else: hit = 0 Iist comprehension can also be an alternative: hit = [i for i in my_test if 'some' in i] >It seems to me that in a simple searching/matching, using if might be >better and the code is smaller. Try/except would have its strengh on >catching multiple errorrs. However, problems occur if the criteria is >composed of "or" rather than "and". For instance: > >if (a in b) or (c in b): > *do something > >try: > b.index(a) > b.index(c) > *do something >except ValueError: > pass > >The above two are very different. > >Am I right here? AFAIAC its a mater of style. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From mcherm at mcherm.com Tue Sep 9 08:26:38 2003 From: mcherm at mcherm.com (Michael Chermside) Date: Tue, 9 Sep 2003 05:26:38 -0700 Subject: Ternery operator Message-ID: <1063110398.3f5dc6fe94f18@mcherm.com> Uwe Schmitt writes: > Normaly[sic] you should simulate "C ? T : F" > > either by > [T,F][not C] > > or > > (C and [T] or [F])[0] > > in the first case T and F are evaluated[sic] allways[sic], > the latter solution does short circuit evaluation, > which is according to the C/C++ semantics of the > ternary operator. NOT TRUE! NEITHER of your options does short-circuit evaluation. That's part of why many people (myself included) wanted to have a conditional expression (more accurate term than "ternary operator"). If you want short-circuit evaluation (and sometimes you DO need it), then use this: if C: x = T else: x = F If you are writing a lambda expression, or are in some other location where an expression would be simpler and clearer than a 4-line statement, then too bad. There DO exist alternatives, but they are even more obscure than Uwe's examples above, and should NOT be used unless you are writing an obfuscated Python entry. -- Michael Chermside From mpeuser at web.de Thu Sep 4 15:55:44 2003 From: mpeuser at web.de (Michael Peuser) Date: Thu, 4 Sep 2003 21:55:44 +0200 Subject: quick and smart way for parsing a CSV file? References: <731fc603.0309031242.4e5493ce@posting.google.com> <3F5656CA.519ABADF@easystreet.com> Message-ID: schrieb im Newsbeitrag news:3F5656CA.519ABADF at easystreet.com... > Hank wrote: > > > > Hi, > > > > I have a CSV file from excel that looks like this (simplified): > > ......... > > > import csv > > dicts = [] > > inputFile = open("SomeDurnFileName.csv", "rb") > parser = csv.reader(inputFile) If you do not use Python 2.3 for some reason or other there is a third party CSV that is fast and workes fine with Python 2.2 (but uses a different interface of course) http://www.object-craft.com.au/projects/csv/ Kindly Michael P From buzzard at urubu.freeserve.co.uk Tue Sep 2 15:59:45 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 2 Sep 2003 20:59:45 +0100 Subject: artificial intelligence References: Message-ID: "Istvan Albert" wrote in message news:K66cnf-bsuHEdM6iU-KYvg at giganews.com... > Duncan Smith wrote: > > > What do Amazon use? My guess (unless it's something really naive) would be > > association rules. > > In my previous job I worked for a research group studying recommender > systems. We have our own, called MovieLens > > http://www.movielens.org > > among others we use a so called item-item recommender. > We compute similarities between items then look at a > given basket and based on it we choose to recommend the most > similar items no yet selected. The good thing about this method > is that item similarities are more static they don't need > to be recomputed as often. > > Istvan. > Thanks for the link. I'll check out some of the more likely looking papers on the publications page. Duncan From toby at rcsreg.com Sun Sep 14 21:24:34 2003 From: toby at rcsreg.com (Tobiah) Date: Mon, 15 Sep 2003 01:24:34 GMT Subject: No "side effect" assignment! In-Reply-To: <3F6511CD.EF0909CB@alcyone.com> References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> <75b7596ef938ab8af18b663ddd7eaf50@news.teranews.com> <3F6511CD.EF0909CB@alcyone.com> Message-ID: Erik Max Francis wrote: > Andrew Koenig wrote: > > >>How about this instead: >> >> def make_generator(func): >> while x = func(): > > ^^^^^^^^^^ > > Not too likely in Python :-). > Heh! My point exactly :) From adalke at mindspring.com Thu Sep 25 22:20:43 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 26 Sep 2003 02:20:43 GMT Subject: Bottleneck? More efficient regular expression? References: <3f7069db_4@corp.newsgroups.com> <3f71ad83_4@corp.newsgroups.com> <3f736cad_4@corp.newsgroups.com> Message-ID: <%nNcb.3635$RW4.47@newsread4.news.pas.earthlink.net> Tina Li: > The lag is *perceivable* (this is what I meant; sorry) by a human user so it's slower. Yup, that's what I meant. Too many people make theoretical arguments for why to choose one (complicated) approach over a simpler one on the basis of performance, when it turns out performance isn't the issue. My appreciation goes out to you for doing it the right way. You may also want to look at pyRXP from ReportLab. However, there seems to be some drastic problems on their site -- links on reportlab.com fail and reportlab.org goes to pair.com's site placeholder page. It's a very fast XML parser for Python. > I in fact tried that before but the over-limit error still happened. So it's > not just the non-greedy .*? that's causing the problem. Hmm. No, I don't think it is. The stack space increases by one for each ambiguity and the .*? should only produce one ambiguity. Usually there's a stack problem only if you have an ambiguity or empty match inside a repeat, and I didn't see that in your pattern. If you get really interested in tracking this down, you might look around for some of the GUI regexp debugging tools. There's one in ActiveState's product, as I recall. Err, but it's based on Perl's regexp parser and won't handle (?P<>) (I do have an experimental pure-Python regexp engine that I would offer for debugging, but it doesn't handle .*? yet and needs a rewrite before it does.) > It only handles tags without space because all tags are > guaranteed to be generated without space. Sure. All I was saying was that if you're going to code for a specific layout then you don't need to be as general. You might even consider using "[^\n]*\n{5}" if you just want to skip 5 lines. Andrew dalke at dalkescientific.com P.S. If you are doing anything open-sourceish, or using open source in bioinformatics, structural biology, and related fields, and will be at ISMB in Edinborough next year, you might consider attending the Bioinformatics Open Source Conference. From paulpaterson at users.sourceforge.net Fri Sep 19 01:24:21 2003 From: paulpaterson at users.sourceforge.net (Paul Paterson) Date: Fri, 19 Sep 2003 05:24:21 GMT Subject: No "side effect" assignment! References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> <1679b.687$Ie5.85963@news20.bellglobal.com> Message-ID: <9qwab.34045$KW1.8747@twister.austin.rr.com> "Martin Maney" wrote in message news:bkbfh1$8il$3 at wheel2.two14.net... > Sean Ross wrote: > > If you must use assignments in expressions, you might find the following > > recipes useful: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/202234 > > Did I forget about this one or is it in fact new? It is, as the author > says, an ugly hack at the implementation level, but that seems to be > its only drawback. I think that the other drawback is that it only works at the top level of a module. If you are inside a function or method then the locals() (f_locals) dictionary is still writeable but it has no effect on the namespace it represents. So ... import sys def set(**kw): assert len(kw)==1 a = sys._getframe(1) a.f_locals.update(kw) return kw.values()[0] def main(): A=range(10) while set(x=A.pop()): print x main() ... prints 0,0,0,0,0,0 etc instead of what you want. I guess you might call "a.f_locals.update(kw)" a no-(side)-effect assignment ;) Paul From aahz at pythoncraft.com Sun Sep 7 20:04:27 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2003 20:04:27 -0400 Subject: Comments on Python Redesign References: Message-ID: In article , Tim Parkin wrote: >Aahz: >> That said, there likely will be a subsection of python.org that is >> aimed at managers, with a more designed look and more graphics; >> someone trying to convince a specific manager could point zir into >> the subsection. > >Fernando: >> A visible 'corporate' link, along with a single-level url >> www.python.org/corporate, perhaps even aliased to >> corporate.python.org) can satisfy the PHBs with minimal effort. > >Please don't consider this, the majority of corporate users will find >the site themselves or through links in articles magazines, etc. so >they will still get first impressions from the main home page. If >anything we could provide a developer portal page which may be used >as a bookmark. Personally I think this is a bad idea also. What is >wrong with the information architecture / navigation on the page >proposal. Please could we move this discussion to one of the >appropriate lists aswell. I suggest python-marketing to begin with. No. If we're talking about the web site, it should be pydotorg-redesign (and the list you're referring to is marketing-python). Please don't clutter too many mailing lists. As I noted earlier, I'm the Lynx champion; I'm not looking at any designs until they're in HTML. I'm also not particularly inclined to look at every single design until we come up with some metrics for choosing. (You originally posted your design alongside a flood of others when I was busy -- website look is not one of my primary interests.) Finally, any design I vote for *will* be usable for a large cross-section of the community. It may include design elements that appeal to managers and/or corporate developers, but they will not have primacy over other groups. OTOH, I'm in agreement that managers won't be second-class citizens, either. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From ulope at gmx.de Mon Sep 22 05:30:07 2003 From: ulope at gmx.de (Ulrich Petri) Date: Mon, 22 Sep 2003 11:30:07 +0200 Subject: Problems with string and lists (searching and replaceing) References: Message-ID: "Colin Fox" schrieb im Newsbeitrag news:pan.2003.09.21.21.08.04.529981 at cfconsulting.ca... > Here's an alternative. I took out the 'if lg in word' logic, > since that doesn't take into account duplicates and therefore > would be misleading (ie 'jaguar','jaaaaa' would return 'x.....', > but there aren't 5 a's in the word). > > #!/usr/bin/env python > import string > > def wordcheck(word, guess): > outstr = [] > if len(word) != len(guess): > raise "Wrong number of letters in guess." > > for x in range(len(word)): > outstr.append( ['-','*'][(word[x]==guess[x])] ) > > return string.join(outstr,'') > > res = wordcheck('Colin','Coolo') > print res > Yeah your right, but with your code there is no indication of a right letter in the wrong position. I guess one has to use a decorate-undecorate thing... If i have some time later today i will test this... Ciao Ulrich From max at fr.fm Thu Sep 18 17:25:01 2003 From: max at fr.fm (Maxime Biais) Date: Thu, 18 Sep 2003 23:25:01 +0200 Subject: print and trailing white space Message-ID: <20030918232501.4f2ab362.max@fr.fm> Hello, I know how to print a string without the trailing newline with a coma like : print "hello word", but this example add a white space after the string :( Do you know how to avoid this white space without using write() -- Maxime Biais From arne at rfc2549.org Tue Sep 23 16:33:22 2003 From: arne at rfc2549.org (Arne Schwabe) Date: 23 Sep 2003 22:33:22 +0200 Subject: Pygtk, widget refreshing Message-ID: hi, I am using python and pygtk. In my program I want to realize a status thing with a DrawingArea. But my problem is that this area is not updated while my program is running. Is there a way I can force pygtk to refresh to widgets? Arne From aahz at pythoncraft.com Mon Sep 8 16:30:17 2003 From: aahz at pythoncraft.com (Aahz) Date: 8 Sep 2003 16:30:17 -0400 Subject: Making mock (was Re: "Python Redesign" (fwd)) References: <5XmdnSsEgZVGSsGiU-KYvw@comcast.com> Message-ID: In article <5XmdnSsEgZVGSsGiU-KYvw at comcast.com>, Terry Reedy wrote: >"Aahz" wrote in message >news:bjif13$ou8$1 at panix3.panix.com... >> In article , >> Terry Reedy wrote: >>> >>>What we were directed to was *not* a mockup (model), but an image of a >>>mockup. That mislabeling was a source of misunderstanding which >>>generated part of the criticism. Please let us keep the useful >>>distinction between a thing and an image of the thing. >> >> And I'll repeat that in addition to Peter's valid point about differing >> definitions of mockups, Tim was not the person who pointed "us" at it. > >So what? I neither said nor implied so. The identity of the original >pointer is irrelevant to the point I made. And so is repetition of a >correction of an error I did not make. It's not so much that the identity of the pointer is relevant as that the context in which "mockup" is used is important. I think it's certainly appropriate, for example, to use "mockup" to describe the whiteboard of a proposed design during a brainstorming session. That's why I made my comment. >In any case, Parkin also used (and today defended) the word himself in >his subsequent posts. Leaving dictionaries aside, the use of the >disputable word 'mockup' instead of the accurate word 'image' lead to >unfulfilled expectations and criticisms based thereon. Indeed, Parkin >himself deflected such criticisms several times by saying 'its just an >image' [and not the html mockup some thought it was]. You yourself are now using the phrase "html mockup" as a specific kind of mockup. That's an accurate phrasing. >Do you really think inexact words that lead to misunderstanding are as >useful as exact words that do not? Do you really think the >distinction between object and image is useless? These are the >questions I raised and gave my answer to. The distinction isn't useless, but neither do I think this was an example of inexact language *in* *context*. If I specifically wanted to refer to a non-image mockup, I'd say "working mockup" or something like that, perhaps "HTML mockup" as you did if I were referring to a web page. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From rolfedh at hotmail.com Mon Sep 29 18:39:00 2003 From: rolfedh at hotmail.com (Rolfe) Date: 29 Sep 2003 15:39:00 -0700 Subject: Still need more feedback Re: Successful installation of mod_python on Apache on Win2k? References: Message-ID: > 1 The LoadModule path looks suspicous, on windows I would expect > mod_python.dll rather than mod_python.so > > 2 Did you restart the apache after changing the config file? > > Peter Hi Peter, I checked C:\Program Files\Apache Group\Apache2\modules and found mod_python.so there, so the LoadModule path was okay. When I made a plain vanilla default RE-INSTALLATION of Apache and mod_python (see instructions below) everything worked fine. I think I goofed something up in the previous installation file. RUNNING MOD_PYTHON/APACHE/WINDOWS2000 Hi, I struggled, and got mod_python running on Apache/Win2k. Follow these instructions verbatim and you shouldn't have any trouble. These instructions are based on "http://www.modpython.org/live/current/doc-html/inst-testing.html". I've added specific information such as Windows filepaths and filenames so there's no ambiguity on what you should do. I encourage you to copy and paste to avoid typing errors. Cheers, Rolfe INSTALLING MOD_PYTHON 1. Make a default installations of the latest/best version of Apache. 2. Make a default installation of the latest/best version of mod_python. 3. Open C:\Program Files\Apache Group\Apache2\conf\httpd.conf in Notepad. 4. In httpd.conf, just below the line "#LoadModule ssl_module modules/mod_ssl.so", copy and paste the following section: #Start of section pasted in by YOURNAMEGOESHERE LoadModule python_module modules/mod_python.so AddHandler python-program .py PythonHandler mptest PythonDebug On AddHandler python-program .py PythonHandler mptest PythonDebug On #End of section pasted in by YOURNAMEGOESHERE (NOTE: Don't mess around with the other configuration settings in httpd.conf, - leave good enough alone. Don't worry about the forward/backward slashes either - it doesn't matter.) 5. Save and close httpd.conf and wait a few seconds. 6. Restart Apache by clicking the Apache monitor icon in your systray and selecting Apache2=>Restart. PROCEDURE COMPLETED ##### TESTING MOD_PYTHON ####### 1. Create a directory called "test" in htdocs so you end up with "C:\Program Files\Apache Group\Apache2\htdocs\test" 2. Create a text file called mptest.py in "C:\Program Files\Apache Group\Apache2\htdocs\test" 3. Paste the following text into mptest.py: from mod_python import apache def handler(req): req.write("Hello World!") return apache.OK 4. Save and close mptest.py. 5. In your file browser, copy and paste mptest from "C:\Program Files\Apache Group\Apache2\htdocs\test" to "C:\Program Files\Apache Group\Apache2\cgi-bin". 6. Assuming your sitting at the same machine that's running Apache, enter the URL "http://localhost/test/mptest.py" in your web browser. The browser displays "Hello World!" and nothing else. This confirms that Apache can run cgi scripts in the /test/ directory. 7. Repeat step 6 using the URL "http://localhost/cgi-bin/mptest.py" instead. The browser displays "Hello World!" and nothing else. This confirms that Apache can run cgi scripts in the /cgi-bin/ directory. PROCEDURE COMPLETED - mod_python works! ######## NOTES ######### Remove either of the following sections (from ) in order to disable cgi scripts in a particular directory. I understand it is very poor security to run cgi scripts under htdocs, so I'd try getting rid of that one first. AddHandler python-program .py PythonHandler mptest PythonDebug On AddHandler python-program .py PythonHandler mptest PythonDebug On ######### ACKNOWLEDGEMENTS ########## Thank you, Steve Holden, for your guidance. I'm very much looking forward to your book, Python Web Programming. Thank you Peter Maas for your response on comp.lang.python From wt at nic.fi Fri Sep 19 19:43:41 2003 From: wt at nic.fi (Timo Virkkala) Date: Sat, 20 Sep 2003 02:43:41 +0300 Subject: [OT] New Play: SPAMELOT In-Reply-To: <3F6B7FE7.445FB3BF@alcyone.com> References: <3F6B7FE7.445FB3BF@alcyone.com> Message-ID: <0tMab.1173$1l5.741@reader1.news.jippii.net> Erik Max Francis wrote: > significant loads on mail servers. Unfortunately, running an intensive, > per-user customized spam filtering solution like Spambayes _increases_ > that load. I'm using Mozilla MailNews, which has a bayesian filtering system built-in. Works like a charm =) -- Timo Virkkala | wt at nic.fi "In the battle between you and the world, bet on the world." From tebeka at cs.bgu.ac.il Wed Sep 17 14:07:50 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 17 Sep 2003 11:07:50 -0700 Subject: texi2html in a cgi ? References: <8vL9b.30567$Hb.466972@news4.e.nsc.no> Message-ID: <33803989.0309171007.28ca7fda@posting.google.com> Hello ?ystein, > I get the file with urllib2. No problem. But how can I parse it and > display it? I see there is a file in the Python23/Tools/Scripts/ > directory called texi2html.py. How can I use the functions from this > file to genrate the webpage? I see two ways: 1. Write the texi file to disk (use tempfile.mkstemp) and run the script (using os.system) on it and send back the result 2. Import texi2html (make sure it's in sys.path) and use it (this is not tested...) ---- from texi2html import TexinfoParser, HTMLHelp from tempfile import mkdtemp from os.path import dirname, join def to_html(file): '''Convert texinfo to html. Return top html file''' outdir = mkdtemp() parser = TexinfoParser() parser.sethtmlhelp(HTMLHelp("","")) parser.setincludedir(dirname(file)) parser.setdirname(outdir) parser.parse(open(file)) return join(outdir, "%s.html" % parser.topname) Remeber to delete the directory from time to time ... HTH. Miki. > (Unexperienced Python programmer, who has just fallen in love with this > beautiful programming language.) The more you'll know the deeper you'll fall in love :-) From anthony_barker at hotmail.com Wed Sep 17 10:49:53 2003 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 17 Sep 2003 07:49:53 -0700 Subject: import on modules/files that don't have .py extension Message-ID: <899f842.0309170649.517e0bb9@posting.google.com> Is it possible to import modules/files that have something other than the .py extension? From jjl at pobox.com Thu Sep 11 13:33:37 2003 From: jjl at pobox.com (John J. Lee) Date: 11 Sep 2003 18:33:37 +0100 Subject: Newbie-question: Fetching web-address from the browser! References: Message-ID: <87pti7fcwe.fsf@pobox.com> dermoon at hotmail.com (dermoon) writes: > I want to fetch the address from the web-browser when it > visits a page on my web-server. [...] BTW, this isn't a Python issue, so this is really the wrong newsgroup. John From tjreedy at udel.edu Fri Sep 26 00:49:38 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2003 00:49:38 -0400 Subject: Turning Strings into Functions References: <46610d4e.0309251516.45a8eb01@posting.google.com> Message-ID: "Freddy" wrote in message news:46610d4e.0309251516.45a8eb01 at posting.google.com... > How do you turn a string into a callable function? If functions are defined as module scope, as is usual, an example: >>> def f(*args): print args ... >>> globals()['f'](*(1,'a')) (1, 'a') Or you can define your own dict mapping names to functions. Terry J. Reedy From mertz at gnosis.cx Sun Sep 7 03:56:47 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sun, 07 Sep 2003 03:56:47 -0400 Subject: OT: Americans love their guns References: Message-ID: Steve Lamb wrote previously: |No, that isn't the question. The question is when someone breaks |into my home which do I want more in my hand, a .45 (is a caliber, not a |quote) or a banana. I'll take the banana. I'd rather be out a stereo and a laptop than be dead in a gun fight (or even than harm someone else who merely wants my money). |Do this simple test [...absurd story of criminal pathos and bathos...] The VAST majority of gun violence (or any violence) is between people who know each other well: husbands, wives, children, parents, friends, etc. Loved ones without guns are many, many times less likely to kill each other. Well, actually, the majority is suicide--which roughly falls under the category described also. Sure it sounds gruesome to get struck by lightning at the moment you are getting run over by a railroad... but frankly, it ain't gonna happen. On the other hand, keeping poison out of reach of children, for example, seems like a sensible action, even if the much more likely resulting death wouldn't make for quite as colorful a story as the train/lightning thing. Yours, Lulu... From tim at remove_if_not_spam.digitig.co.uk Mon Sep 15 07:26:18 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Mon, 15 Sep 2003 12:26:18 +0100 Subject: stripping a string References: Message-ID: On Sat, 13 Sep 2003 16:15:06 -0600, Bob Gailer wrote: >import re >result = re.findall(r'(\D*)\d*', source)[0] > >will remove any number of trailing digits. That might give problems if the string could also contain embedded digits, for example "ANL1 LN32" -- it will truncate at the first digit. Spot on if it's what Mark wants, of course, but Jeff's solution gives what I thought he wanted. Funny how often when people can't work out how to do something it turns out that what they want to do isn't precisely specified, isn't it? :-) From wolof at freemail.hu Sun Sep 14 12:09:26 2003 From: wolof at freemail.hu (White Wolf) Date: Sun, 14 Sep 2003 19:09:26 +0300 Subject: Standards in Artificial Intelligence References: <3f61f9ce@news.victoria.tc.ca> Message-ID: Steve Holden wrote: > People who live in glass houses shouldn't throw stones. Your lazy > attitude to editing the newsgroups these posting were sent to means > that as a comp.lang.python reader I have toi listen you you bitching > and moaning about what's appropriate in comp.lang.c++? > > By all means try to keep posters of that group to the charter, but > DON'T subject others to your diatribes ;-) *PLONK* -- WW aka Attila From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Fri Sep 26 15:01:04 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Fri, 26 Sep 2003 20:01:04 +0100 Subject: Reduce need of backslash References: <3F745445.D9628351@engcorp.com> Message-ID: On Fri, 26 Sep 2003 13:34:22 -0400, Nicolas Fleury wrote: >What if the second line would be indented? Indentation is already used >to determine blocks, why not instructions? For example, the following >is not error-prone at all: > >a = 5 + > someFunc() > >Doesn't it stay with python minimalistic philosophy? I don't know the original rationale, but to me this mostly looks ugly. Maybe I'd get used to it if it happened a lot, but this is rarely an issue in practice. Basically, when I need to break an expression over multiple lines, the odds are that it already has parentheses anyway. And I wouldn't indent that way anyway, I'd do it as... a = ( firstitem + seconditem + ( thirditem * fourthitem ) ) ... ie using indentation to clarify the structure of the expression much as I would with block structuring - whether I was using Python or some other language. In a way I can imagine some value to putting a statement in parentheses. It would look very Lispy, but then some would say that's a good thing. Occasionally, I go through a phase of thinking semicolons should be used as compulsory statement terminators rather than as the rarely used separators they are now - in which case '\' would be completely redundant - but it really is a trivial issue, whereas the idea of changing such a fundamental piece of syntax - well, don't go there. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From faizan at jaredweb.com Sun Sep 21 16:41:04 2003 From: faizan at jaredweb.com (Fazer) Date: 21 Sep 2003 13:41:04 -0700 Subject: Twisted Matrix and Python Scripts Message-ID: <7b454334.0309211241.4fce86ff@posting.google.com> Hello, I am very interested in fooling around with Twisted Matrix's HTTP Web Server. I was thinking if .rpy scripts would run much faster than traditional CGI scripts? After looking how asynchronous Twisted's framework really is, I have been interested in it. Thanks, From alexander.dejanovski at laposte.net Mon Sep 8 06:16:21 2003 From: alexander.dejanovski at laposte.net (Alexander DEJANOVSKI) Date: Mon, 08 Sep 2003 12:16:21 +0200 Subject: pymqi for win32 Message-ID: <5.1.0.14.2.20030908121401.00ac6a60@194.214.207.101> I'm having troubles compiling pymqi under win32 with MinGw32( I haven't got VC++ ). Could anybody provide me an already built version for Windows 2000 ? Thanks. From ababo_2002 at hotmail.com Mon Sep 15 11:33:02 2003 From: ababo_2002 at hotmail.com (Daniel Pryde) Date: 15 Sep 2003 08:33:02 -0700 Subject: Multiple instances of modules Message-ID: Hi there. I'm currently trying to learn Python, my aim being to create my final year project at university using only Python instead of Java. I've run into a problem though while trying to make multiple instances of modules. For example, say I made a CD.py module which held details of an audio compact dic (album name, track names, etc..), and wanted my Python script to make a record collection using multiple CD's, I can't make them seperately. I tried using the 'import module as name' format, but any changes made to one instance affects the other. I assume this is because Python is simply referencing the one instance of CD.py rather than seperate ones. Is there a solution to this that doesn't involve using cPython or Jython? Any help would be greatly appreciated. From gherron at islandtraining.com Tue Sep 9 04:02:41 2003 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 9 Sep 2003 01:02:41 -0700 Subject: PyGTK and fonts In-Reply-To: References: Message-ID: <200309090102.41093.gherron@islandtraining.com> On Monday 08 September 2003 08:34 pm, Tad Marko wrote: > Howdy! > > I'm pretty new to both Python and PyGTK (about 10 hours at this > point), so please forgive me if this question has already been > answered somewhere. Basically, I've got a small program with a > GtkTextView and I'd like to change the font to a monospaced font. > Preferably the default monspace font for Gnome 2. Can anyone show me > the steps necessary to programatically change the font on the text > view? > > Thanks for any help! > > Tad I too have about 10 hours experience with PyGTK and GTK+ (but about 10 *years* experience with python). I just figured out the answer to your question yesterday. Here it is with the font name coming from the return value of a font selection dialog. fontName = fontDialog.get_font_name() pangoFont = pango.FontDescription(fontName) textView.modify_font(pangoFont) The fontName could be hardcoded rather than comming from a font selection dialog if you wanted. Here are some examples, the last two of which are mono-space fonts: Sans 12 Sans Italic 12 Sans Bold 12 Sans Bold Italic 12 Courier 12 Luxi Mono 12 Gary Herron From tina_li23AThotmailDOTcom Mon Sep 22 12:38:27 2003 From: tina_li23AThotmailDOTcom (Tina Li) Date: Mon, 22 Sep 2003 12:38:27 -0400 Subject: how to know the number of menu items in a cascade (sub) menu? Message-ID: <3f6f2742_4@corp.newsgroups.com> Hello, I have a menu, "Foo", and a cascade submenu under it, called "Bar", that has a number of menu items. If I want to delete all of the menu items under "Bar", but would like to keep "Bar" (i.e. an empty cascade menu with no items), how do I know how many items there are? I assume I should use deletemenuitems("Bar", 0, ???) It's the last parameter ("end") that I don't know what to put in. I tried to access "Bar" via self.menuBar.component("Foo-menu_Bar"), or to get the END index of "Bar" via self.menuBar.component("Foo")[1].index("end") (because Bar is the second submenu under Foo. I know, hard-coding is bad) but they don't work. Thanks much for your help!!! Tina -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From mikael at isy.liu.se Thu Sep 4 04:00:40 2003 From: mikael at isy.liu.se (Mikael Olofsson) Date: Thu, 4 Sep 2003 10:00:40 +0200 Subject: Writing solid code book In-Reply-To: References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> Message-ID: <20030904100040.535fdc39.mikael@isy.liu.se> On Thu, 04 Sep 2003 00:06:00 -0400 Roy Smith wrote: > How many votes does a language need to get to be elected Governor of > California? $ 10**7 ? /Mikael Olofsson Universitetslektor (Associate professor) Link?pings universitet ----------------------------------------------------------------------- E-Mail: mikael at isy.liu.se WWW: http://www.dtr.isy.liu.se/en/staff/mikael Phone: +46 - (0)13 - 28 1343 Telefax: +46 - (0)13 - 28 1339 ----------------------------------------------------------------------- Link?pings kammark?r: www.kammarkoren.com From fuerte at sci.fi Mon Sep 8 01:57:12 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Mon, 08 Sep 2003 08:57:12 +0300 Subject: Python documentation in Windows Help file format? Message-ID: Seems to be missing? It would be great, because it would contain an Index and Search features automatically. Now the search is very hard to do, and Index page in html format is too big. The full API and C reference would be great, but even the Quick Reference available here would be fine: http://www.brunningonline.net/simon/python/PQR.html Unfortunately the Windows compiled help in above seems to be broken. Here is another: http://www.orgmf.com.ar/condor/pytstuff.html But has version 2.2 only. Downloading at the moment. Harri From davecook at nowhere.net Sat Sep 13 20:02:20 2003 From: davecook at nowhere.net (David M. Cook) Date: Sun, 14 Sep 2003 00:02:20 GMT Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <17d520f6.0309130704.7944c876@posting.google.com> Message-ID: In article <17d520f6.0309130704.7944c876 at posting.google.com>, Ubaidullah Nubar wrote: > Don't they all (PyGTK, wxPython, etc.) use the underlying GUIs (e.g. > Windows API/KDE/Gnome, etc.)? So where does the better looking part > come from? Or do some of them recreate the whole GUI layer? Gtk does not use the native win32 controls. There's a theme that apparently does use the native controls, but I've heard that it's slow. So it's not the toolkit to choose right now if native look and feel is an overriding concern. > Reading some other threads on this ng, there are posts that mention > that gtk has issues running under Win32. Are these concerns still > valid or have they been resolved with the latest version? The latest version fixes some bugs, but the win32 port is still not very mature, and does not have as large a community of testers as the unix version. Dave Cook From Mike at DeleteThis.Geary.com Mon Sep 22 17:45:41 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 22 Sep 2003 14:45:41 -0700 Subject: Calling functions before that are def'ed References: <944840ff.0309221318.35d2f9cd@posting.google.com> Message-ID: Charles Larry wrote: > Is there a way to define functions after the main part of a Python > script? > > Example: > > #!/usr/local/bin/python > > # this code yields a NameError > > print_message("hello world") > > def print_message(msg): > print msg > > I know functions can be put in separate files and imported, but I want > everything in a single file. Am I stuck with defining all the > functions first? If so, how come at compile-time Python can't look > ahead in the program and discover the existence of functions referred > to but not yet defined? Function definitions are executable statements, so like any other statement they are executed in the order they are encountered. If you prefer the style of having functions after your main program, simply define a main function at the top of your script, and call it at the end. -Mike From eppstein at ics.uci.edu Sun Sep 7 15:17:34 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 07 Sep 2003 12:17:34 -0700 Subject: Comments on Python Redesign References: Message-ID: Lots of people have been rightly jumping all over the design. But there's something else that I think is very important in the current python.org front page and missing from the proposed redesign: the text "Welcome to the official website for the Python language." If one looks at the proposed redesign, it is difficult to tell whether Python is an application, a magazine, a business consulting partnership, or what. It is also unclear whether the site is run by the same people responsible for Python, whatever Python is. Certainly "official web site for programming language" is not the first thing that springs to mind. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From mfranklin1 at gatwick.westerngeco.slb.com Tue Sep 2 05:41:02 2003 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 02 Sep 2003 10:41:02 +0100 Subject: homebrew 2.3 install on RedHat9 not playing nice with Tkinter In-Reply-To: <200309020451.h824pgv9031012@localhost.localdomain> References: <200309020451.h824pgv9031012@localhost.localdomain> Message-ID: <200309021041.02665.mfranklin1@gatwick.westerngeco.slb.com> On Tuesday 02 September 2003 5:51 am, Anthony Baxter wrote: > >>> Martin Franklin wrote > > > > Red Hat Linux: Red Hat 9 built Python2.2 in UCS-4 mode and hacked > > Tcl to support it. To compile Python2.3 with Tkinter, you will > > need to pass --enable-unicode=ucs4 flag to ./configure. > > > > Which I did and now _tkinter.so is building of the box > > so in answer to OP read the README;-) > > Note that this will "work", but the resulting tk applications will leak > memory like a sieve. > Thanks Anthony, I looked at your site a few minutes after sending my reply.. Indeed if the OP wants to use tk 8.3 then he should use your RPM's I was kind of pushing him into updrading Tk at the same time as Python... Cheers, Martin From claird at lairds.com Thu Sep 4 17:33:25 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 04 Sep 2003 21:33:25 -0000 Subject: Drag and drop in Tkinter. How difficult is it? References: <4378fa6f.0309041125.49b13fc7@posting.google.com> Message-ID: In article <4378fa6f.0309041125.49b13fc7 at posting.google.com>, Marc wrote: . . . >1) If I want to have a moving object, and not just a cursor that >represents the moving object, do I need to continually pack and unpack >the widget that holds the object and redraw it to give it the >appearance of moving? I know sometimes the redrawing can cause . . . No! Just move the canvas object to follow the Motion events. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From tjreedy at udel.edu Tue Sep 16 22:56:54 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2003 22:56:54 -0400 Subject: None, False, True References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> <3f675ecd$0$97184$edfadb0f@dread12.news.tele.dk> <5MJ9b.13244$x21.9088@twister.southeast.rr.com> Message-ID: "M-a-S" wrote in message news:5MJ9b.13244$x21.9088 at twister.southeast.rr.com... > I mean what are None, False and True? Are they just identifiers? Are they > variables defined in __builtins__? Are they literals? Are they language "bricks" > like "for" and "1"? You are trying too hard ;-) They are currently names in the builtin namespace bound to PyObjects, just like all other builtin names. That means that they can be shadowed by global or local names, just like all other builtin names. There is a proposal to change the status of None, and possibly, True and False, sometime in the future. Hence the warning (also issued because reassignment of None is likely a mistake). Terry J. Reedy From CousinStanley at hotmail.com Wed Sep 24 21:43:25 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 24 Sep 2003 18:43:25 -0700 Subject: RELEASED Python 2.3.1 References: Message-ID: | Yes, you can still download the individual HTML files at: | http://www.python.org/ftp/python/doc/2.3.1/ Raymond .... Thanks for the reply .... I'd like to see the Docs as always a separate download from the standard distribution to provide a bit leaner download for those who don't program and aren't interested .... -- Cousin Stanley Human Being Phoenix, Arizona From bgailer at alum.rpi.edu Sat Sep 20 23:19:36 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 20 Sep 2003 21:19:36 -0600 Subject: What is the meaning of the astarisk in Python In-Reply-To: References: <3f6ce54f$0$10962$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <6.0.0.22.0.20030920211915.032fe780@66.28.54.253> At 06:13 PM 9/20/2003, John Roth wrote: >"John Dean" wrote in message >news:3f6ce54f$0$10962$fa0fcedb at lovejoy.zen.co.uk... > > Hi > > Below is a line taken from Andy Dustman's MySQLdb module: > > def Connect(*args, **kwargs): > > > > I would be grateful if somebody explain the meaning of the astarisks, >since > > I was under the impression that pointers are not used in Python and the > > above look very must like pointers to me > >One asterisk creates a list of all positional arguements, Do you mean tuple? >two asterisks creates a dictionary of all keyword arguements. >"All" means "not otherwise represented in the parameter list." Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From faizan at jaredweb.com Sat Sep 20 14:23:24 2003 From: faizan at jaredweb.com (Fazer) Date: 20 Sep 2003 11:23:24 -0700 Subject: Sending SMS... References: <7b454334.0309131130.59cf64fa@posting.google.com> <1063558054.822575@newsmaster-03.atnet.at> Message-ID: <7b454334.0309201023.6ee6842f@posting.google.com> Guenther Starnberger wrote in message news:<1063558054.822575 at newsmaster-03.atnet.at>... > Fazer wrote: > > hello, > > > Can anyone point me to a way on how to send a SMS message using Python? > > an alternative to the already suggested SMS-webgateway would be to use the > ICQ-SMS-gateway ('worldwide' SMSs, no advertisements). > > either use libicq2000[1] directly (but afaik there are no python bindings > yet), or setup a local jabber[2] server with an aim-transport[3] to which > you can connect with python by using jabberpy[4]. > > cu > /gst > > [1] http://libicq2000.sf.net/ > [2] http://www.jabber.org/about/overview.html > [3] http://aim-transport.jabberstudio.org/ > [4] http://jabberpy.sourceforge.net/ Wow, thanks for the reply! It was really helpful. Exactly what I was looking for. From rummanddan at hotmail.com Mon Sep 1 05:11:47 2003 From: rummanddan at hotmail.com (Dan Thrue) Date: Mon, 01 Sep 2003 11:11:47 +0200 Subject: Python Documentation? In-Reply-To: References: Message-ID: <3f530ea6$0$32489$edfadb0f@dread16.news.tele.dk> Daniel R. Smorey Jr. wrote: > I'm looking for a good place for Python documentation. I'm really lost > on why it's so hard to find anything when it comes to me looking up a > particular function in Python. My example would be the split() function > of the string module. Why can't I just go to www.python.org and click > on Search and then type in split and it bring me to the split() function > of the string module? Why does it have to be so hard? This is what I > get when I search for split on www.python.org... > > http://search.python.org/query.html?qt=split&col=ftp&col=python&col=peps&col=starship > > > Most of those hits are for the re module, not the string module (which > in my opinion should be part of python and not a module, but I digress). > Why would it not bring up the split function of the string module first > and foremost? > > If I do a search right now on www.perldoc.com for split, I get... > > http://www.perldoc.com/cgi-bin/htsearch?words=split&restrict=perl5.8.0 > > Right there, the top hit is the slit function, how convenient. > > If I go to www.php.net and type in split in the function list search, I > get... > > http://www.php.net/manual/en/function.split.php > > I don't even get a hit list, it goes right to the split() function. Even > more convenient. > > I'm trying to learn Python because we're doing some work on the Zaurus > and there are so many supporting python modules for the Zaurus, that I'd > like to use it. I love learning new languages also. It just gives me a > bad taste in my mouth when I even think of searching for anything in > Python. > > Am I searching the wrong place? Am I choosing the wrong checkboxes on > the Search page? I'm at a loss. Is it really that hard to find > documentation on the python.org site? > > Thanks for hearing my rant and I'm hoping I'm just doing something > wrong. I really can't imagine such an organized programming language > having such a horrible search on their website. > Hi Daniel, Me and a friend am about to finish a project in a couple of weeks, that maybe fits your needs. We are currently documenting the parts if python, we meet in our daily python development (Some gaming software where we mix native delphi with python. This mixture has surprised us a lot, we are indeed python fanatics now, hehe). The documentation takes contributions on example snippets, description, etc. so when the site is completely done and a base of documentation have been posted, im gonna post link in here, then maybe the community will help us to create a great documentation source :) And find the errors we might post :) Regards all, Dan From newsgroups at jhrothjr.com Fri Sep 5 13:44:02 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 13:44:02 -0400 Subject: in Ram database? References: Message-ID: "Andy Todd" wrote in message news:mailman.1062776296.7505.python-list at python.org... > John Roth wrote: > > > "John D." wrote in message > > news:mailman.1062728122.8678.python-list at python.org... > > > >>Does anyone know if there is an "in-ram" dictionary based database > >>for Python. > >> > >>I can see some applications where this can really be powerful in > >>applications requiring 10,000 records or less. > >> > >>Is such a database available? If so, who is working on it, > >>or where is it? > >> > >>I've heard that Python supports a stand-alone database. I looked > >>for it in the Docs, and see the "dbm" module. I haven't found > >>any examples of code, so don't know how to use them. I'm one > >>of those guys that learn through examples, and have very little > >>luck in figuring out how to use anything unless I can see examples > >>of their use. > >> > >>My idea is that ALL datums would be Python Dictionary objects, so > >>not only can you store data, but python objects as well. > >> > >>Storage to disk would be through pickled files, or through CSV > >>format, allowing easy import and export from other databases. > >> > >>I'm sure something like this exists, I just haven't found it yet, > >>and if not, then I'm well on my way of implementing one myself. > >> > >>I kinda like the idea of being able to define smaller tables as > >>"in-memory" types, and the really large massive ones in other forms > >>managed by mySQL, PostGres, or bsddb3 databases. > >> > >>Any leads you guys??? > > > > > > Look at Prevalyar. While it's a Java project, it might give > > you some ideas about what's possible if you forget "data base" > > and simply think "persistance." > > > > John Roth > > > >>JD > >> > > Or you could look at the Python port of Prevayler (well, thats how it > started out); > > http://www.orbtech.com/wiki/PyPerSyst Thanks for the reference. John Roth > > Regards, > Andy > -- > -------------------------------------------------------------------------- ------ > From the desk of Andrew J Todd esq - http://www.halfcooked.com/ > > > From peter at engcorp.com Wed Sep 24 11:29:27 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 24 Sep 2003 11:29:27 -0400 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: Message-ID: <3F71B857.2D1E3268@engcorp.com> Anthony Baxter wrote: > > On behalf of the Python development team and the Python community, I'm > happy to announce the release of Python 2.3.1 (final). The highlights mention the existence of a new API PyThreadState_SetAsyncEnc, which is "deliberately accessible only from C", that can interrupt a thread by sending it an exception. I can't find an online discussion of this, so I'm asking here. Why was this made accessible only from C? Is it dangerous? Experimental? Someone feels it will be used inappropriately if too readily available at the Python level? Presumably somebody will come up with a little extension module or other technique for calling this which will let anyone use it at will, so I'm unclear on why it should be made inaccessible from Python. -Peter From tzot at sil-tec.gr Wed Sep 24 19:22:30 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 25 Sep 2003 02:22:30 +0300 Subject: Pre-PEP: reverse iteration methods References: Message-ID: On Wed, 24 Sep 2003 20:46:16 +0200, rumours say that Peter Otten <__peter__ at web.de> might have written: > # let inifinite iterators identify themselves > assert not hasattr(obj, 'infinite') > >As infinite iterators are rare, it would not be too cumbersome to let them >identify themselves as such. This is an interesting idea. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From cygwin-announce-help at cygwin.com Thu Sep 4 21:29:25 2003 From: cygwin-announce-help at cygwin.com (cygwin-announce-help at cygwin.com) Date: 5 Sep 2003 01:29:25 -0000 Subject: confirm unsubscribe from cygwin-announce@cygwin.com Message-ID: <1062725365.2743.ezmlm@cygwin.com> Hi! This is the ezmlm program. I'm managing the cygwin-announce at cygwin.com mailing list. To confirm that you would like python-list at python.org removed from the cygwin-announce mailing list, please send an empty reply to this address: cygwin-announce-uc.1062725365.hckpipiiioigomjioddm-python-list=python.org at cygwin.com Usually, this happens when you just hit the "reply" button. If this does not work, simply copy the address and paste it into the "To:" field of a new message. I haven't checked whether your address is currently on the mailing list. To see what address you used to subscribe, look at the messages you are receiving from the mailing list. Each message has your address hidden inside its return path; for example, mary at xdd.ff.com receives messages with return path: -mary=xdd.ff.com at cygwin.com. Some mail programs are broken and cannot handle long addresses. If you cannot reply to this request, instead send a message to and put the entire address listed above into the "Subject:" line. --- Administrative commands for the cygwin-announce list --- I can handle administrative requests automatically. Please DO NOT SEND THEM TO THE LIST ADDRESS! If you do, I will not see them and other subscribers will be annoyed. Instead, send your message to the correct command address: To subscribe to the list, send a message to: To remove your address from the list, send a message to: To get messages 123 through 145 (a maximum of 100 per request), mail: To get an index with subject and author for messages 123-456 , mail: They are always returned as sets of 100, max 2000 per request, so you'll actually get 100-499. To receive all messages with the same subject as message 12345, send an empty message to: The messages do not really need to be empty, but I will ignore their content. Only the ADDRESS you send to is important. You can start a subscription for an alternate address, for example "john at host.domain", just add a hyphen and your address (with '=' instead of '@') after the command word: To stop subscription for this address, mail: In both cases, I'll send a confirmation message to that address. When you receive it, simply reply to it to complete your subscription. If despite following these instructions, you do not get the desired results, please contact my owner at cygwin-announce-owner at cygwin.com. Please be patient, my owner is a lot slower than I am ;-) --- Enclosed is a copy of the request I received. Return-Path: Received: (qmail 2738 invoked from network); 5 Sep 2003 01:29:25 -0000 Received: from unknown (HELO SUGO) (24.195.53.13) by sources.redhat.com with SMTP; 5 Sep 2003 01:29:25 -0000 From: To: Subject: Re: Details Date: Thu, 4 Sep 2003 21:29:30 --0400 X-MailScanner: Found to be clean Importance: Normal X-Mailer: Microsoft Outlook Express 6.00.2600.0000 X-MSMail-Priority: Normal X-Priority: 3 (Normal) MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="_NextPart_000_21830510" This is a multipart message in MIME format --_NextPart_000_21830510 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit See the attached file for details --_NextPart_000_21830510-- From aleax at aleax.it Fri Sep 5 11:11:20 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 05 Sep 2003 15:11:20 GMT Subject: safari (was Re: Writing solid code book) References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> Message-ID: post400 wrote: ... > yes Safari seems ok , you get a few days for free to browse but it's > not totally free.I think the electronic version should be free.Some safari is only free for two weeks; then, if you like the service it gives you, you can choose to continue a (paid) subscription. I'm not sure on what basis you intend your use of "should". Do you mean that you believe it would be in publishers' best interests to offer electronic versions free -- that it would enhance the sales of their paper versions producing a greater total profit than having online books as a for-pay service does? If so, then it would be interesting to understand on what basis you form that judgment. O'Reilly, in particular, publishes paper versions both of books that are also available for free download elsewhere, _and_ of books that are not thus avialable. Presumably, therefore, they have available very good historical data to convince them that their policies are in fact the best currently available to them -- knowing Tim O'Reilly's ideas, policies, and openness to novelty, you surely can't be accusing him of "persevering by sheer inertia" in his policies. Or is your "should" predicated on some ethical objection against such people as book authors and editors receiving compensation for their efforts? Speaking as a book author, I can confirm that the amount of money I earn from writing, divided by the number of hours I spend writing, is roughly comparable with legal minimum wage (depending on jurisdiction -- such minima may be higher in most of Europe than in the US), and *WELL* below the hourly income I can make by professional consulting. Were I to contemplate the possibility of would-be freeloaders trying to dictate what I "should" do (without deigning to mention WHY they think I should), it might perhaps anger me just enough to deter me from my former intention of making my next coming book freely available. So, I would appreciate some explanation of your assertion. > people offer their books for free , Bruce Eckel for example and his > Thinking in Java which seems to be a good book.Maybe more writers > should do the same ! "Thinking in Java" is indeed excellent, and no doubt the feedback from people who freely downloaded it helped Bruce make it so. However, I do notice that Bruce's long-planned "Thinking in Python" seems to be languishing without end. Perhaps this means that books addressing a huge market for which there are hundreds of competitors (Java, C++) _are_ indeed profitable to make freely downloadable (at least if only a minority of authors are so doing, assuming part of the profit comes from competitive considerations), but books addressing a smaller market, such as Python, aren't. As for me, I'm operating on a different assumption (which is not necessarily contradictory to the possibility outlined in the previous paragraph) as to what distinguishes books that are best made freely available online from those which are not; but I have as yet no experience to back me up (the only "free book" I have out on the net -- a primer on win32 API GUI programmin in C, in Italian -- is incomplete and not available in any for-pay form, only in the free online version). Several other authors have experience publishing both books that are also available for free, and ones that aren't. Hearing from them would be very interesting, at least to me. Alex From ceiesa at excite.com Sat Sep 27 21:10:21 2003 From: ceiesa at excite.com (Bruce Dickey) Date: Sat, 27 Sep 2003 19:10:21 -0600 Subject: [joke] Any tool to translate PHP to Python? In-Reply-To: <3f75f5b8$0$20650$626a54ce@news.free.fr> References: <3f75f5b8$0$20650$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Bruce Dickey wrote: > >> Hi, >> >> I have some PHP scripts I'm moving from my web server to the local PC. >> They just do file manipulation. >> >> Anybody know of a tool for translating PHP to Python? > > > Er... What about a programmer ?-) > > (sorry, could not resist) > Bruno > Heh heh. Point taken. I actually *was* assuming I would be the tool -- I've been around Python long enough to have seen most of the resources for desktop apps. But Python web scripting I have not gotten into or read much about. It appears to me that Python is increasing in popularity, not only on the desktop, but also on the web server. It seems to me that for folks migrating from PHP to Python, a translator would be a handy tool. Especially if they have a large site to convert. It would be a tool useful to a large number of people. Bruce From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Mon Sep 29 14:35:42 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Mon, 29 Sep 2003 19:35:42 +0100 Subject: embedding python and new-style classes References: Message-ID: On Mon, 29 Sep 2003 13:28:13 -0400, "mike" wrote: >If someone could tell me the proper >API calls for instantiating a new-style class, or point me to an example, >I'd really appreciate it. I'm relatively new at extending/embedding so I don't know if this has changed, but doing this recently I simply noted that Python class objects are callables and that calling them returns an instantiation. I use Boost.Python, but I imagine you can simply use PyObject_CallMethod with the class object. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From gh at ghaering.de Mon Sep 15 09:02:51 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 15 Sep 2003 15:02:51 +0200 Subject: caching the sql queries In-Reply-To: References: <606bmvkbbs2dup8slqnoueaq26moiq2e8n@4ax.com> Message-ID: <3F65B87B.1010802@ghaering.de> Syver Enstad wrote: > Gerhard H?ring writes: >>In my opinion, this sort of caching should really be done in the >>application layer, not in the database access layer. > > I didn't know that PHP programmers used layers at all :-) > > On a more serious note, Why do you think caching should be > implemented in the application layer (is this the same as the > domain/business layer) rather than the database access layer? Yes, a dozen different terms for the same thing ;) It's mostly gut feeling about what's the right approach, which has served me well quite often :-) If I needed to state reasons, I'd say that the business layer can assure data consistency, while with this simplistic approach, the database layer (*) cannot. -- Gerhard (*) "database access layer" may sound like something important, but in my projects, it's only a thin layer on top of DB-API/ADO.NET/... that provides shortcuts for the most common use cases and allows switching database backends more easily. From jjl at pobox.com Tue Sep 23 14:18:21 2003 From: jjl at pobox.com (John J. Lee) Date: 23 Sep 2003 19:18:21 +0100 Subject: problem using urllib2: \n References: <7cb14f9.0309230800.8d3a28b@posting.google.com> Message-ID: <874qz3cqs2.fsf@pobox.com> bmiras at yahoo.com writes: > I've got a problem using urllib2 to get a web page. > I'm going through a proxy using user/password authentification > and i'm trying to get a page asking for a HTTP authentification. > And I'm using python 2.3 > > Here is an exemple of the piece of code I use: > > import urllib2 > #Proxy handler > proxy_handler = urllib2.ProxyHandler({"http" : > "http://proxyuser:proxypassword at myproxy:8050"}) > > #Site auth handler > > site_auth_handler = urllib2.HTTPBasicAuthHandler(); > site_auth_handler.add_password( "This Realm", "www.mysite.com", > "siteuser", "sitepassword" ); > > > opener = urllib2.build_opener( site_auth_handler, > urllib2.HTTPRedirectHandler, urllib2.HTTPHandler , proxy_handler) > urllib2.install_opener(opener) Looks OK (but I don't use a proxy, nor basic auth very often...). Just as a BTW: you don't need to pass HTTPHandler or HTTPRedirectHandler in there: build_opener adds them whether you ask for them or not. > req = urllib2.Request('http://www.mysite.com/protectedpage') > page = urllib2.urlopen(req) > > I got a 401 error. So presumably your proxy is happy, but the site is not. Could you test that theory by urlopen()ing a URL that *doesn't* require any authentication? Just: # ...your code up to install_opener goes here... print urllib2.urlopen("http://www.python.org/").read() > Analyzing the request using 'strace' I can see the following request > sent to the proxy: > > GET http://www.mysite.com/protectedpage HTTP/1.0\r\nHost: > www.mysite.com\r\nUser-agent: > Python-urllib/2.0a1\r\nProxy-authorization: Basic > XXX\n\r\nAuthorization: Basic > YYY\n\r\n\r\n (You probably didn't want to post your usernames and passwords to a public newsgroup. They're reversibly encoded, so anyone can decode them. I've replaced them with XXX and YYY in the quote above.) > As you can see there is additionnal \n sent to the server just after > the Proxy-authorization and the Authorization fields. I think that in > this case the web server get only this part: > > GET http://www.mysite.com/protectedpage HTTP/1.0\r\nHost: > www.mysite.com\r\nUser-agent: > Python-urllib/2.0a1\r\nProxy-authorization: Basic > XXX\n\r\n > > and so send me back an error 401, since I'm not authenticated for the > site. Hmm. That \n does seem likely to be wrong, but I'm not certain. The urllib2 code appears to duplicate the code for base64 encoding for proxy basic authorization (in ProxyBasicAuthHandler and ProxyHandler), and the code differs between the two classes :-(. [It looks like PBAH responds to 407, and ProxyHandler always sends Proxy-Authorization if it's in the proxy's URL.] And in fact, only one of them does a .strip() on the base64 encoded string (they also differ in quoting). However, the Authorization: header appears to be generated only in one place (AbstractBasicAuthHandler.retry_http_basic_auth), which *does* strip, but you've got a \n there, too. So, I don't understand where that \n is coming from. I'd try sticking some print statements in there to find out what's going on. > I had a look in the urllib2.py . I think that base64.encodestring add > an \n at the end of the string. It's the case in the method > 'proxy_open': > > def proxy_open(self, req, proxy, type): > orig_type = req.get_type() > type, r_type = splittype(proxy) > host, XXX = splithost(r_type) > if '@' in host: > user_pass, host = host.split('@', 1) > if ':' in user_pass: > user, password = user_pass.split(':', 1) > user_pass = base64.encodestring('%s:%s' % > (unquote(user), > > unquote(password))) > req.add_header('Proxy-authorization', 'Basic ' + > user_pass) > host = unquote(host) > req.set_proxy(host, type) > ... > > I think it should be: > > user_pass = base64.encodestring('%s:%s' % (unquote(user), > unquote(password))).split() You mean strip, not split? Try debugging a bit, find out what's really going on. Just copy urllib2.py to your current directory (so it'll override the installed standard library's copy), and stick some print statements in there. > have you any other clue? [...] You could try sniffing what Mozilla sends, too. If you get this working, please look at the doc patch here http://www.python.org/sf/798244 test it, and post a comment to say whether or not it's correct (and which examples you tried -- preferably all of them ;). John From news_nospam at fuglum.net Sun Sep 21 07:32:44 2003 From: news_nospam at fuglum.net (Erlend Fuglum) Date: Sun, 21 Sep 2003 13:32:44 +0200 Subject: Trouble sorting lists (unicode/locale related?) Message-ID: Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text containing norwegian special characters ?, ? and ?. >>> liste = ["ola", "erlend", "trygve", "?rlige anders", "Lars", "?ksemorderen", "?sne", "Akrobatiske Anna", "leidulf"] >>> liste.sort() >>> liste ['Akrobatiske Anna', 'Lars', 'erlend', 'leidulf', 'ola', 'trygve', '\xc5sne', '\xc6rlige anders', '\xd8ksemorderen'] There are a couple of issues for me here: * The sorting method apparently places strings starting with uppercase characters before strings staring with lowercase. I would like to treat them them equally when sorting. OK, this could probably be fixed by hacking with .toupper() or something, but isn't it possible to achieve this in a more elegant way? * The norwegian special characters are sorted in a wrong way. According to our alphabet the correct order is (...) x, y, z, ?, ? ?. Python does it this way: (...) x, y, z, ?, ?, ? ? I would really appreciate any help and suggestions - I have been fiddling with this mess for quite some time now :-) From benkial at hotmail.com Sun Sep 28 21:59:52 2003 From: benkial at hotmail.com (Ben Kial) Date: Mon, 29 Sep 2003 01:59:52 GMT Subject: write a file "copy" program in Python for Unix and Windows... Message-ID: I need to write a program to "copy" files and preserved the files' atime, mtime, ctime, file permissions. I also need to have this program working in Unix and Windows, where the "Archive" attribute on the file also has to be preserved (any more Windows idiosyncrasies?). Any help will be very much appreciated. Thanks in advance. Ben From BoteDesSchattens at web.de Thu Sep 11 01:25:49 2003 From: BoteDesSchattens at web.de (Tobias Pfeiffer) Date: 11 Sep 2003 05:25:49 GMT Subject: FIFO problems References: Message-ID: Hi! Sorry, big mistake!! Tobias Pfeiffer wrote in news:bjp0sg$li4db$1 at ID-162581.news.uni-berlin.de: > these clients exists, no problem. But when the last process exists EXITS, not exists... Bye Tobias From peter at engcorp.com Thu Sep 4 09:24:18 2003 From: peter at engcorp.com (Peter Hansen) Date: Thu, 04 Sep 2003 09:24:18 -0400 Subject: Code complete electronic version ? References: <3f566672.342116427@news.blueyonder.co.uk> Message-ID: <3F573D02.1A1022A1@engcorp.com> Syver Enstad wrote: > > I agree that Code Complete is a very good book, but I also think it is > getting somewhat long in the tooth. For once it doesn't cover > object-orientation. On the topic of coding I wonder if people are not > better off buying Refactoring by Martin Fowler and Kent Beck. On the > topic of project managment and development practices I would think > that the XP white book would be more up to date. Although the XP white book (Kent Beck's) is quite out of date itself, at least relative to the state-of-the-XP. I'm not sure what I'd suggest as more current, unless it's to jump directly to the TDD book, but while that would teach some *very good* coding practices, it sort of gets away from the area covered by Code Complete enough to be a questionable response to the OP. -Peter From maney at pobox.com Thu Sep 18 01:23:45 2003 From: maney at pobox.com (Martin Maney) Date: Thu, 18 Sep 2003 05:23:45 +0000 (UTC) Subject: No "side effect" assignment! References: <0fbc28ebd2ba4810db3efef3a29f990a@news.teranews.com> <1679b.687$Ie5.85963@news20.bellglobal.com> Message-ID: Sean Ross wrote: > If you must use assignments in expressions, you might find the following > recipes useful: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/202234 Did I forget about this one or is it in fact new? It is, as the author says, an ugly hack at the implementation level, but that seems to be its only drawback. It doesn't use any hidden state that could be altered unexpectedly, and is only a minor eyesore; those who worry about accidentally writing an assignment in place of an equality test will consider that last to be a feature, of course. Perhaps it could be improved, slightly, by being renamed to "let"? > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66061 The hope of obliterating this recipie is IMO the strongest argument in favor of adding operator= to Python. I can think of no reason to prefer this to 202234 aside from the chance that the language implementation detail used in the latter's implementation could conceivably go away someday. Short form: 66061 Considered Harmful. What, you thought it was just a coincidence it had all those sixes in its number? -- People make secure systems insecure because insecure systems do what people want and secure systems don't. -- James Grimmelmann From cbrew at acm.org Thu Sep 4 15:24:38 2003 From: cbrew at acm.org (Chris Brew) Date: 4 Sep 2003 12:24:38 -0700 Subject: Comparing objects - is there a maximum object? Message-ID: <7bdbb1a6.0309041124.6801b755@posting.google.com> I've just been writing some code to merge items from a collection of streams, where each item has a key, and each stream is known to be sorted in ascending order of key. I read all the streams once, then pick the minimum element of the results, replace it with a new one read from the corresponding stream, and repeat. Thing is, what happens at end of file? I'd like to do it by making the streams that are finished return some object (call it endmarker) such that min(x,endmarker) always returns x. That way, when all the streams are returning endmarker, we would be done. And I'd like my code to work the same no matter what kind of thing the streams are returning, so I want endmarker to be a generic maximum object. The Python documentation says: The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily so (unless this has been superseded) it doesn't seem that there is such an object. Any suggestions? I notice that empirically max(x,None) seems to be always x, but again I suppose I shouldn't count on that. Chris From rparnes at megalink.net Wed Sep 10 20:55:51 2003 From: rparnes at megalink.net (Bob Parnes) Date: Thu, 11 Sep 2003 00:55:51 -0000 Subject: Trouble Learning Zope Message-ID: Greetings, I just installed zope, version 2.6.1-10 on a debian distribution, but I cannot get to second base. When I try to add the tutorial to a folder, I get an error message stating that an emergency user cannot own an object. So I clicked onto the help page and found the tutorial there. But I got the same error when I tried to follow it. Then I created a new user account and restarted zope. But it would not accept a login as the new user, only as the original, 'emergency' user. As things stand, I can bring up zope on my browser but cannot do anything in it. I have the online version of the Zope Book but could find no reference to an emergency user. What can I do to straighten things out. Thanks for any help. -- Bob Parnes rparnes at megalink.net From tzot at sil-tec.gr Mon Sep 29 19:09:15 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 02:09:15 +0300 Subject: Using TCP/IP References: Message-ID: On Mon, 29 Sep 2003 21:19:26 +0200, rumours say that jblazi might have written: >How do I find out my own IP number (using Pythoi of course). One way that works on most systems is: import socket socket.gethostbyname(socket.gethostname()) Basically, this way you request the IP address for your host name; so you depend on many variables: your system has a name that can be resolved locally by a file or DNS lookup or similar... >And how do I >send/receive data to/from andother TCP/IP socket (of known ip number)? >I mean: which module do I have to use for that? The socket module. Check the socket.socket class. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From CousinStanley at hotmail.com Wed Sep 3 13:04:47 2003 From: CousinStanley at hotmail.com (Cousin Stanley) Date: Wed, 3 Sep 2003 10:04:47 -0700 Subject: Polymorphism the Python way References: <3f550e2f.254030105@news.blueyonder.co.uk> Message-ID: | ... } I don't think that it has changed its meaning; | most people just use the term incorrectly. | ... Add to these the OFTEN confused terms accuracy and precision ... -- Cousin Stanley Human Being Phoenix, Arizona From newsgroupacc at yahoo.com Tue Sep 2 11:31:40 2003 From: newsgroupacc at yahoo.com (brian) Date: 2 Sep 2003 08:31:40 -0700 Subject: force gtk modal window to keep focus Message-ID: <3a6e51c8.0309020731.1870c3c@posting.google.com> Hi, I am beginner using Python 1.52, GTK 1.2.10, and Glade .0.6.2 to develop a gui which will kick off various scripts. After checking some configurations I would like to pop up a window warning the user of any problems and force them to respond to this window before returning to the main window. I use a modal dialog window and set the main window to be insensitive. This works fine but the way my window manager(MWM) is setup(in the .mwmrc) is to raise a window when clicked on. So if the dialog is up and the user clicks on the main window the dialog becomes hidden and nothing can happen. I can change this raise property on my machine but I don't know how a user's window manager will be setup. Is this a common problem? Does anyone have a nice solution? All I can think of is to try and disable events/signals for the mainwindow or add callbacks for when the focus is lost in the dialog window. I know my versions are out of date but it's what I have to work with. thank you. From mail at heikokoehler.de Thu Sep 11 22:19:30 2003 From: mail at heikokoehler.de (Heiko =?ISO-8859-15?Q?K=F6hler?=) Date: Fri, 12 Sep 2003 04:19:30 +0200 Subject: CUTE 0.2 released Message-ID: <3f612c9c$0$3270$9b4e6d93@newsread2.arcor-online.net> This version is beta software. CUTE is a QT and Scintilla based code editor, scriptable with python. CUTE is completely configured with python scripts. The python API allows to define new commands, which can be mapped to a shortcut or added to a menu. There is a handbook for CUTE, but this is still work in progress. The CUTE/python API is also documented. CUTE`s page is http://cute.sourceforge.net Regards, Heiko K?hler From martin at v.loewis.de Tue Sep 16 15:41:30 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 16 Sep 2003 21:41:30 +0200 Subject: py2exe & pyxml References: Message-ID: "Kathleen Kudzma" writes: > PROBLEM: When I try to create a classReader object I get an exception: > "SAXReaderNotAvailable: No parsers found". This only happens when I > run the .EXE; it does not happen if I run the .PY file. When I'm > running the .EXE this exception doesn't happen immediately. It > happens as soon as I try to create a classReader object. You have to explicitly ask py2exe to include pyexpat in the executable. RTFM. Regards, Martin From mpeuser at web.de Fri Sep 5 18:59:29 2003 From: mpeuser at web.de (Michael Peuser) Date: Sat, 6 Sep 2003 00:59:29 +0200 Subject: Why python??? References: Message-ID: Hello Alex, this is one of the most exciting topics to discuss, however _slightly_ off-topic. Generally I agree with your reasoning. However I disagree with some conclusions. We all know peace is the best possible state but there is war...... "Alex Martelli" schrieb im Newsbeitrag news:NO66b.30883$R32.926812 at news2.tin.it... > Michael Peuser wrote: > ... > > A very good reply! But I have an answer as well: The only reason why Linux > > got a market share is Moore's Law. Nobody of clear commercial thinking > > Moore's Law is working in favour of higher level languages even harder > than it's working in favour of free but highly efficient OS's. There are two aspects: (1) More power for same price - this works in favour of 'complex software' (2) Same power for less money - this works in favor of 'cheap software' > > > will pay $200 for an operating system when the hardware has the same > > Most Linux use of commercial significance is not happening on such > incredibly cheap systems, but rather on reasonably substantial servers > (or sometimes even mainframes -- IBM _has_ invested a lot in Linux:-). > The issue you mention MAY play a role in ensuring a nice for Lindows > (and other desktop-oriented versions of Linux), but the server side > is where Linux got its first foothold. This is just a scaling. The main argument is the same. The software related parts of the total cost of ownership have today become a major concern. [ Michael stated here the price of tools is of minor relevance, as he thougth of Python's "free" aspect] [Alex gave a comprehensiv explanation why 'complex software' has become possible.] > > > > So it comes to the question: What does the common programmer know? This is > > Not necessarily. If common programmers only knew machine language, > it would still be cheaper to use any available high-level language, > say COBOL, even if you needed to supply training for it (it's not > hard to teach COBOL to somebody who knows assembly, anyway -- the > reverse is harder). I am on your way; maybe they more probably would be trained for some "macro language". This is no 'paradigm change'. Most C++ programmers (I know what I say!) write C programs. > Similarly, using Python can lower costs even > if you factor in training costs (again, teaching Python to good > Cobol programmers is quite easy -- other higher-level languages may > not be _quite_ as cheap in these terms, admittedly, but still the > economics aren't _hugely_ different). This argument is valid for: - OOP ("Reuse will reduce costs") - RAD - XP - Design-for-testing - Rigid configuration control - state any new thing you like The fact that a better world is possible does not mean you get it. Python is by no means a "perfect" alternative to - lets say: DOT-NET and # - the advantages are difficult to see for persons in power or - I mentiones the tool costs - are of minor relevance. I should as well like to discuss your aspect of programmer's productivity. This is an important factor. However all investigations show that programmer's productivity is an unmeasurable quantity. It certainly has to do with what the programmer likes to do. If he or she would like to program in Python everething would be fine. However most or today's programmers like to do what is called "mainstream" (circular reasoning, I know) That is a little bit document driven development, some UML charts, Visual Studio, something inbetwen C and C++, C# and Java, and MS Office. This can only change if there is competition. Competition means a Killer Application that could be sold for half the price of the nearest competitor because the developing costs had been such low! Do it with Python then and show it to the world ;-) Kindly Michael P > > > Alex > From llothar at web.de Thu Sep 18 14:53:45 2003 From: llothar at web.de (Lothar Scholz) Date: 18 Sep 2003 11:53:45 -0700 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> <87r82e6yxg.fsf@pobox.com> Message-ID: <6ee58e07.0309181053.70facb64@posting.google.com> jjl at pobox.com (John J. Lee) wrote in message news:<87r82e6yxg.fsf at pobox.com>... > Ken Godee writes: > > John, is Ken right that buying the commercial BlackAdder license means > you don't have to pay for the TT license too? Certainly a good deal > if so. > Yes, please answer about this topic. This is one thing that would be great but there is also no clue on the website about it. From xnews at fredp.lautre.net Fri Sep 19 07:42:59 2003 From: xnews at fredp.lautre.net (Fred Pacquier) Date: 19 Sep 2003 11:42:59 GMT Subject: Anyone has "pyuploader.zip" from Parnassus ? Message-ID: Hi, For my education I'd like to take a peek at "CGI Uploader", an old script that can be found on Vaults Of Parnassus ( http://py.vaults.ca/apyllo.py? find=uploader ). Unfortunately that is hosted on Parnassus itself : http://www.vex.net/~x/python_stuff.html I can access the page itself, but no file linked there will actually download. I have notified VoP, but I'm fully aware this has got to be low- priority stuff ;-) In the meanwhile, if anyone happens to have a copy of this file lying around : http://www.vex.net/~x/archive.py/pyupload.zip ...I'd appreciate being mailed a copy (the return address in this post should work). TIA, fp -- YAFAP : http://www.multimania.com/fredp/ From dave at boost-consulting.com Mon Sep 29 08:15:41 2003 From: dave at boost-consulting.com (David Abrahams) Date: Mon, 29 Sep 2003 08:15:41 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <0acdb.128801$hE5.4391247@news1.tin.it> <1Xhdb.130593$hE5.4445587@news1.tin.it> <9tabnvgbc4etnpp1hm3oh5dkffkru9pv0d@4ax.com> <2tsbnvob1k6tt6bkb29cfc69a4ji0q4giv@4ax.com> <136envcoppkt546p8rhjhpeqkj380a3g40@4ax.com> Message-ID: I wasn't even going to post this to the list, because it's so full of static and other unpythonic stuff. But then, Stephen hides his email address, and there is one real Python-related issue at the bottom, so... Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: > It was my intention to explain the origins of my misunderstanding, > though certainly in a slightly less than serious way and with a big > dollop of its-not-all-my-fault-you-know. I didn't need to have an assignment of blame in order to find closure with this thread. I was just trying to be helpful. > I tend to screw this kind of thing up, and it seems I have done so > again here. Then I can't understand why you continue to charge about in the china shop.... > I never said, anywhere, that you said that "std::pair supports..." if > we are being that pedantic, but in the life of this thread neither of > us really has been that pedantic. Seems like you've started. > I quoted your exact words for the crucial point, which were... > > "you can in fact iterate on std::pair with the usual C++ iterator > protocol" > > Pedantically speaking, this is imprecise language. No, there is a common subset of all iterator requirements and that's what I was referring to. > Most significantly, there is no such thing as "the usual C++ > iterator protocol". An iterator may implement any one of five > different iterator protocols, and these protocols have surprisingly > little in common. All require an operator++ and all require a > dereference-style operator* and that is it. And that is the usual iterator protocol. I happen to know exactly what those protocols have in common. > Actually, even the operator* isn't as common as it seems - input > iterators only support read access, output ones only write access Actually it's subtler than that. You can have input/output iterators which support random access which aren't random access iterators because they don't support lvalue access. So what, though? > - so the practical commonality is limited to the operator++. You need operator* regardless. > But then you weren't writing a standards document, and I wasn't > reading it as a standards document. That's why I didn't understand why you were giving me such a hard time. Because it's informal speech I'm supposed to do quadruple duty to make sure you haven't misinterpreted me? I really was going out of my way to explain this stuff to you politely. > To most C++ programmers most of the time, the words "the usual C++ > iterator protocol" don't have the pedantic meaning set by the C++ > standard - they are not just about having an operator++ And operator*. > They have a somewhat more pragmatic meaning, which includes the > usual means of obtaining iterators from containers. std::pair *is* a > container in the general sense of containing other objects, even > though in the C++ standards document context it is not formally > considered a container. Then so is struct { int x, y; }; Also, so is char[4], and unsigned long is a container of at least 32 bits. This is getting ridiculous. It seems like you want to have a pedantic debate about terms whose meaning is going to be defined by your completely informal and subjective interpretation. > Of course there is room for misinterpretation in virtually any piece > of writing - criticism of your choice of words was certainly > intentional, but meant to be lighthearted. > > But if you really believe that I "read what [I] want to see into what > [you] posted" then I'm afraid you're wrong. I saw an implication which > you never intended, but that was right at the start when I had no > reason to "want to see" anything in particular. > > I do have a certain history in this kind of > minor-misunderstanding-gets-overblown storyline, as Alex Martelli I > think can confirm if he's still following the thread. Actually, > he'll probably say you should consider yourself lucky that it only > got this bad ;-) > > Anyway, I'm in no doubt that I'm primarily (probably entirely) > responsible for the 'overblown' part especially with my previous post. > I appologise for that. Thanks, I think. This is somewhat of a backhanded apology, but I'll take it. [If you had just stopped with the last message, I wouldn't even feel it mattered]. >>This whole discussion started out talking about what the Python >>protocol for manipulating iterators should be. The fact that >>iterators must themselves have an __iter__ method in Python may just >>be making this more confusing than it needs to be. > > We may think of '__iter__' as part of the iterator protocol but, > pedantically speaking, it is no more part of the Python iterator > protocol than 'begin' is part of the C++ iterator protocol. > > Iterators don't have to have an '__iter__' method in Python. Iterators > only have to have a 'next' method. It is the iterable object that > implements '__iter__'. And, as with getting C++ iterators from 'begin' > etc, even that is a convention rather than a requirement. Sorry, http://www.python.org/doc/current/lib/typeiter.html#l2h-149 Read it twice, carefully. > Sometimes iterators do have an '__iter__' method, but that normally > just returns self Always. > - it's a quick-fix convenience for when iterators > end up in a context where an iterable object is expected. > > I guess our mindsets aren't so different that we can't make similar > mistakes ;-) I'm afraid not. I never, ever make mistakes in the first place ;-> infallib-ly y'rs -- Dave Abrahams Boost Consulting www.boost-consulting.com From nomail at hursley.ibm.com Tue Sep 23 07:20:35 2003 From: nomail at hursley.ibm.com (Derek Fountain) Date: Tue, 23 Sep 2003 19:20:35 +0800 Subject: Factory function to generate a named class Message-ID: <3f702b3a$0$23594$5a62ac22@freenews.iinet.net.au> I have a situation where I have, in a string, the name of a class I want an instance of. I've written a factory function to generate the class for me: def controllerFactory( controllerRequired, model ): if controllerRequired == "ViewController": return ViewController( model ) elif controllerRequired == "FontController": return FontController( model ) elif controllerRequired == "ColourController": return ColourController( model ) else: raise TypeError Is there a way to generate an instance of a class given the class name at runtime? If so, what, in newbie terms, is it? From newsgroups at jhrothjr.com Tue Sep 23 21:54:20 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 23 Sep 2003 21:54:20 -0400 Subject: Pre-PEP: reverse iteration methods References: Message-ID: Overall impression: I like it. More comments interspersed. John Roth "Raymond Hettinger" wrote in message news:HA5cb.185$kD3.168 at nwrdny03.gnilink.net... > Here is a discussion draft of a potential PEP. > The ideas grew out of the discussion on pep-284. > Comments are invited. Dart throwing is optional. > > > Raymond Hettinger > > ------------------------------------------------------------- > > PEP: 323 > Title: Add Reverse Iteration Methods > Version: $Revision: 1.1 $ > Last-Modified: $Date: 2003/03/11 04:49:44 $ > Author: Raymond Hettinger > Status: Draft > Type: Standards Track > Content-Type: text/x-rst > Created: 23-Sep-2003 > Python-Version: 2.4 > Post-History: 23-Sep-2003 > > > Abstract > ======== > > This proposal is to extend the API of several sequence types > to include methods for iterating over the sequence in reverse. > > > Motivation > ========== > > For indexable objects, current methods for reverse iteration are > error prone, unnatural, and not especially readable:: > > for i in xrange(n-1, -1, -1): > print seqn[i] > > One other current approach involves reversing a list before iterating > over it. That technique wastes computer cycles, memory, and lines of > code. It also has the "returns None instead of an object" wart. > Also, it only works with lists (strings, for example, do not define > a reverse method):: > > rseqn = list(seqn) > rseqn.reverse() > for elem in rseqn: > print elem > > Reverse iteration is much less common than forward iteration, but it > does arise regularly in practice. Absolutely. > > Proposal > ======== > > Add a method called iter_backwards() to sequence objects that can benefit > from it. The above examples then simplify to:: > > for i in xrange(n).iter_backwards(): > print seqn[i] > > for elem in seqn.iter_backwards(): > print elem > > The new protocol would be applied to lists, strings, xranges objects, > and possibly other sequence objects as well (depending on use cases > and implementation issues). It would not apply to unordered collections > like dicts and sets. I presume that the result of iter_backwards() is an iterator object with the desired behavior. In other words, it's not the original object that has methods to handle the iteration protocol. > > No language syntax changes are needed. > > > Open Issues > =========== > > * Should tuples be included? In the past they have been denied some list > like behaviors such as count() and index(). I'd say yes, but I don't know the reason why tuples are missing methods. > > * Should file objects be included? Implementing reverse iteration may not > be easy though it would be useful on occasion. Are we talking text files or binary files here? Offhand, I'm not even sure there is a binary file iterator, although if there is reverse iteration shouldn't be difficult. Reverse iteration for text files simply means implementing the reverse scan in C, since the standard library doesn't support it. For small enough files, it may be easier to simply internally use getlines() and then use iter_reverse() on the list. > > * Should enumerate() be included? It would only provide reverse iteration > whenever the underlying sequence supported it. I don't see why not. In general, I support the notion that a concept should be implemented pervasively, unless there's a clear reason not to do it in a special case. Special cases are just that - if they really are special, you trip over them once and then remember them. What gets messy is something that's partially implemented, where there is no clear rule to determine when it is and when it isn't. John Roth > > > Copyright > ========= > > This document has been placed in the public domain. > > > From ssthapa at classes.cs.uchicago.edu Thu Sep 4 15:46:16 2003 From: ssthapa at classes.cs.uchicago.edu (Suchandra Thapa) Date: Thu, 04 Sep 2003 19:46:16 GMT Subject: Python prog needs root -how to do this securely References: Message-ID: John D. wrote: > I have a Python program which runs as user 'www' (it's a CGI). > It needs root privilege to write a particular file. > What's the best way of doing this while remaining secure? > > Right now I do os.system("sudo myutil parms") and pass the parms to it. > I remove : < > & | from the parm string before passing it. > Is there a way to do this without making a system call? With your approach you have to be aware that users on the system will probably be able to view the parameters your are passing to myutil. Whether this is a problem depends on your particular setup. One alternative would be to make nobody, apache, etc. (which ever your apache server runs under) the group owners of the file and give the apache group write permissions to the file. This may not be feasible for your setup. -- ---------------------------------------------------------------------------- Suchandra Thapa s-thapa-11 at NOSPAMalumni.uchicago.edu ---------------------------------------------------------------------------- From jjl at pobox.com Mon Sep 8 07:53:56 2003 From: jjl at pobox.com (John J. Lee) Date: 08 Sep 2003 12:53:56 +0100 Subject: exec code with timeout? References: Message-ID: <87n0dfcx7v.fsf@pobox.com> Alex Martelli writes: > Graham Fawcett wrote: [...] > > Hmm... well, again I'd suggest the PyThreadState_SetAsyncExc function. It > > shouldn't be that hard to wrap... I'd try it myself, but haven't made it > > to 2.3 yet. :( > > Nope -- the attacking script can easily use try/except to defeat attempts > to kill it via PyThreadState_SetAsyncExc . The latter isn't meant for any > "adversarial" situation, but just for potentially _buggy_ threads. [...] Which is what the OP asked for, actually -- the users are trusted. Agreed that a separate process still seems better, though. John From paul at boddie.net Fri Sep 26 07:38:55 2003 From: paul at boddie.net (Paul Boddie) Date: 26 Sep 2003 04:38:55 -0700 Subject: 64-bit EPIC and some modules References: <7h3smmm2m0w.fsf@pc150.maths.bris.ac.uk> <0ck3nvoicm45kb0oon2etsucttatc3aob7@4ax.com> <7h3ad8t2k6q.fsf@pc150.maths.bris.ac.uk> <89d6nv85qdrvegiehk25rpkpirogvqspgi@4ax.com> <7dWcnajRG6oi4-6iXTWJkA@comcast.com> Message-ID: <23891c90.0309260338.139e34ba@posting.google.com> "Terry Reedy" wrote in message news:<7dWcnajRG6oi4-6iXTWJkA at comcast.com>... > "Christos TZOTZIOY Georgiou" wrote in message > news:89d6nv85qdrvegiehk25rpkpirogvqspgi at 4ax.com... > > On Thu, 25 Sep 2003 11:20:27 GMT, rumours say that Michael Hudson > > might have written: > > > > >PS: hp-ux/itanium appears to be utterly horked... > > > > PS: What is horked??? > > In Diablo II, it means that a Barbarian has stood over the corpse and > yelled a particular magical warcry to draw out any remaining potions > or possessions. > > MH might have meant something else ;-) Yes, MH presumably meant "Tux the Penguin" instead of "a Barbarian", "long-term viability" instead of "potions", and "market share" instead of "possessions". ;-) Paul From nospamius at lundhansen.dk Tue Sep 2 10:34:37 2003 From: nospamius at lundhansen.dk (Bertel Lund Hansen) Date: Tue, 02 Sep 2003 16:34:37 +0200 Subject: Polymorphism the Python way References: Message-ID: Daniel Klein skrev: >It's not a problem really. I just thought there would be a better, >more elegant way to achieve polymorphism without using getters. A note on words: If a class operates with for instance a bullet, then derived classes thereof may operate with a metal bullet, a rubber bullet, a grenade or a missile. They all operate as bullets, and the fact that the same object can be instantiated as many different things, is called polymorphism. "Poly morph" = "many shaped". "Encapsulation" is the word that describes the effort(s) to make it impossible for the user of a module to access the attributes (and hidden methods) directly and only allow him to do it through public methods with build-in check so that no disasters occur. -- Bertel, Denmark From sholden at holdenweb.com Tue Sep 16 12:49:39 2003 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 16 Sep 2003 16:49:39 GMT Subject: Duck Typing References: <221d8dbe.0309160101.4a09f2ad@posting.google.com> <3gG9b.12137$3Y2.2543@news2.central.cox.net> <3F6732DB.F31A954E@engcorp.com> Message-ID: "Peter Hansen" wrote in message news:3F6732DB.F31A954E at engcorp.com... > Steve Holden wrote: > > > > exquacktly [ducks and runs] > ^^^^^ > > Steve, did you even _know_ you did this? You're sick! > > -Peter :-) Aah, I see, you think I'm stupid. Of course I knew - without the bracketed afterthought it would hardly have been worth posting. I'll send you a bill ;-) regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From patrick at fraley.de Wed Sep 3 05:57:19 2003 From: patrick at fraley.de (Patrick W. Fraley) Date: Wed, 03 Sep 2003 11:57:19 +0200 Subject: gadfly and SQL-LIKE Message-ID: Hi Everybuddy, I am having a little problem I can not find a solution for. I am trying to use the SQL-LIKE statement in gadfly. After googling around I found out that it is not supported, and that on is supposed to use a regular expression. All great, but there is nowhere a reference to be found on how to do this. No examples, no nothing, just the comment to use regular expressions. Could someone here point me into the right direction? TIA Patrick W. Fraley From donn at u.washington.edu Wed Sep 17 12:19:03 2003 From: donn at u.washington.edu (Donn Cave) Date: Wed, 17 Sep 2003 09:19:03 -0700 Subject: tuples vs lists References: <9egemvkhp2s55horjr9dfveml22158d62g@4ax.com> <3F67606B.C9A89EF3@engcorp.com> <3F676AAB.92479235@engcorp.com> <3F68625F.984871CE@engcorp.com> Message-ID: In article <3F68625F.984871CE at engcorp.com>, Peter Hansen wrote: > Ivan Voras wrote: > > > > Peter Hansen wrote: > > > Ivan Voras wrote: > > > > >> I know that. I was just wandering if they also behave faster. Lists > > >> are only interesting to me in case I need mutability. > > > > > > I'd suggest you have that backwards. Lists should _always_ be > > > interesting > > > to you. Tuples should be interesting only in the case where you need > > > *immutability*. > > > > I disagree. :) I would always use tuples except when I explicitely need > > mutability. That doesn't meen that I would intentionaly (badly) restructure > > code just to use tuples, only that in many cases my structures don't need > > to > > be modified. > > That's your personal choice, I suppose, and I won't try any more to dissuade > you any more except to point out that most Python programmers, I believe, do > not see tuples as their first choice, but use them only in certain special > cases. These two positions may be more similar than different. The notion of a sequence that never needs to be modified is certainly a special case, and if we were looking at the actual applications for these sequences we might all agree that they're more or less appropriately cast as tuples. One argues about principles like this at some risk of silliness. The thing that eventually pushed me towards lists and away from tuples, for sequences of like items, is the notation. It may seem like a awfully prosaic consideration, but lists are usually easier to mentally parse out of an expression, because the tuple's parentheses are shared by other syntactical groupings. And then there's the awkward notation for a single-element tuple. Lists are easier to write and easier to read. Donn Cave, donn at u.washington.edu From sross at connectmail.carleton.ca Tue Sep 2 11:41:32 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Tue, 2 Sep 2003 11:41:32 -0400 Subject: **kwds behavior? References: <924a9f9c.0309020652.212c54eb@posting.google.com> Message-ID: <2S25b.841$I_2.211334@news20.bellglobal.com> "Paradox" wrote in message news:924a9f9c.0309020652.212c54eb at posting.google.com... > Why does the following attempts to pass in keywords arguments not > work. Passing in the keyword arguments to the functions testKeywords1, 2 ,3 does work, but you need to access 'x' using kwds['x']. Passing kwds to locals().update doesn't work because locals is not writable. It might be better if attempting to write to an non-writable dict raised an exception, but that is not the current behaviour. So, your call to update has no effect on the local namespace and, thus, 'x' is not yet defined locally. > Does anyone know how to accomplish something like this. [snip] Well, you can't modify locals directly, but you can do this - class record: "a simple class to use like a c struct or pascal record" def __init__(self, **kwds): self.__dict__.update(kwds) def testKeywords1 (**kwds): my = record(**kwds) print my.x def testNested(): print my.x testNested() # works testKeywords1(x=5) # output 5 5 HTH Sean From dave at 3dex.com Thu Sep 11 15:02:32 2003 From: dave at 3dex.com (Dave Benjamin) Date: Thu, 11 Sep 2003 19:02:32 GMT Subject: Problems with setting up mod_python and Apache References: <3f5f6b41$0$239$fa0fcedb@lovejoy.zen.co.uk> <4zK7b.11532$NW3.6643@news1.central.cox.net> <3f605bee$0$199$fa0fcedb@lovejoy.zen.co.uk> Message-ID: "John Dean" wrote in message news:3f605bee$0$199$fa0fcedb at lovejoy.zen.co.uk... > I have fixed my problem with mod_python. I have one small problem left to > sort out. If I enter the URL http://localhost Apache just displays the > contents of the htdocs directory, but if I enter the URL > http://localhost/test.py everything works as it should. I guess this is > somewhat off topic since it appears to be an Apache configuration problem so > I hope you don't mind me asking you for your opinion on c.l.p. Well, I get around this problem by adding "index.py" to the DirectoryIndex directive. I use a modified version of the publisher module that comes with mod_python that handles this and related special cases. Here's the change that I make, if you're interested: < if not _req.subprocess_env.has_key("PATH_INFO"): < raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND < < func_path = _req.subprocess_env["PATH_INFO"][1:] # skip fist / < func_path = string.replace(func_path, "/", ".") --- > if _req.subprocess_env.has_key("PATH_INFO"): > func_path = _req.subprocess_env["PATH_INFO"][1:] # skip first / > func_path = string.replace(func_path, "/", ".") > > # If no function is specified, assume "default". > if not len(func_path): func_path = "default" > else: > # If no module is specified either, assume "index". > func_path = "default" > module_name = "index" This has the result that "index" is always the default module, and "default" is the function within that module that gets called if no function is explicitly specified on the URL. This works like a charm. > BTW What I am trying to do is to move away from PHP. Since I use Python as > my primary scripting language for just about everything where you would use > a scripting language, it seems to me to be a reasonable idea to use Python > to provide dyanamic content for the web sites I look after. I did the same thing myself last year, after writing PHP for a couple of years. mod_python definitely makes Python a worthy substitute for writing Apache modules. The main drawbacks from my experience are the lack of built-in session handling and more sophisticated parameter passing (ie. PHP's ability to serialize hashes from a form submission). But I'm a little dated now, I'm still using mod_python 2 / apache 1.3 ... Have fun, Dave From roy at panix.com Sun Sep 28 17:06:11 2003 From: roy at panix.com (Roy Smith) Date: Sun, 28 Sep 2003 17:06:11 -0400 Subject: Checking for invalid keyword arguments? Message-ID: I've got a function that takes a couple of optional keyword arguments. I want to check to make sure I didn't get passed an argument I didn't expect. Right now I'm doing: conversion = None drop = False for key, value in kwArgs.items(): if key == 'conversion': conversion = value elif key == 'drop': drop = value else: raise TypeError ('Unexpected keyword argument %s' % key) which seems kind of verbose. Is there a neater way to do this check? From sjoshi at ingr.com Thu Sep 4 12:35:18 2003 From: sjoshi at ingr.com (Sunit Joshi) Date: 4 Sep 2003 09:35:18 -0700 Subject: How do I match this with re Message-ID: <8f8ffe67.0309040835.368f9565@posting.google.com> Hello All I have a problem here where I need to find the drive letters in a text file and replace them with another letter. Now the lines can be as long as this 6 'C:\pds\bddin64\report\mto\' 'SJOSHI' 'D:\pds\bddin64\report\format\' 'SJOSHI' with multiple entries for path; i.e. there may be 2, as above or 1 or more then 2. If I use the expression .*'([A-Z]:).*?', it only matches the 2nd D: How do I get all the path groups ..?? thanks Sunit From peter at engcorp.com Mon Sep 15 14:02:30 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Sep 2003 14:02:30 -0400 Subject: Advice from Jeff (Was Re: Is there "let binding" in Python?) References: <20030914214340.13608.qmail@web40904.mail.yahoo.com> Message-ID: <3F65FEB6.967C2116@engcorp.com> Don Bruder wrote: > > In article , > Jeff Epler wrote: > > > > > Not an answer, but advice: when writing programs in Python, write Python > > programs. > > Gawd, but that's profound! And on several levels... No... I'm serious. > But I'm also smiling. Only about as profound as the pithy sayings of "the Sphinx" in the droll movie "Mystery Men"... -Peter From martin at v.loewis.de Sat Sep 27 07:49:45 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 27 Sep 2003 13:49:45 +0200 Subject: unicode 3 digit decimal conversion References: Message-ID: Peter Otten <__peter__ at web.de> writes: > I see your problem is already solved I'm quite uncertain as to what the solution is, though - or perhaps what the problem is. The OP said that the telnet server expects backslash characters in the data stream (atleast I interpreted his message that way), but then he was happy with an approach that did not send backslash characters. Perhaps the telnet server really expects latin-1, in which case encoding the Unicode string in that encoding, or in iso-8859-15, would work fine most of the time. Regards, Martin From brent.turner at clarisay.com Mon Sep 29 16:35:51 2003 From: brent.turner at clarisay.com (Brent Turner) Date: 29 Sep 2003 13:35:51 -0700 Subject: COM Servers in python 2.3 [win32all build 157]? Message-ID: <2f6cf792.0309291235.27f15233@posting.google.com> Under python 2.2 [win32all build 156] I was able to create a COM object in an exe much of the same way that I could from py source... meaning that I was able to register the com server and create an instance using the current process (exe/source) as the com server. Now, in python 2.3 [win32all build 157] when I try to create the COM instance from the exe, it starts up a new process and fails (b/c my exe does not support the command line parameters) The Source below is what is run from inside the exe. This may not be the way I was supposed to do it, but at the time I found that this worked. Does anybody know what I am doing wrong?? or why it worked in the first place (if it is wrong). Source: ###################################################################### # place all com classes here to be registered at import comservers = [ PythonCollection ] import win32com.server.register import pythoncom import sys if hasattr(sys, 'importers'): # we are running as py2exe-packed executable sys.frozen = 1 pythoncom.frozen = 1 # Register all the comservers for com in comservers: print 'Registering COM Server %s ...' % com win32com.server.register.UseCommandLine(com) ###################################################################### Thanks, Brent From mwilson at the-wire.com Fri Sep 5 15:56:26 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 05 Sep 2003 15:56:26 -0400 Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> Message-ID: In article , "John Roth" wrote: >"Grant Edwards" wrote in message >news:3f58b1f6$0$155$a1866201 at newsreader.visi.com... >> In article , John Roth wrote: >> > >> > "Grant Edwards" wrote in message >> > news:3f58a2bd$0$156$a1866201 at newsreader.visi.com... >> 2) It would mean that there's some sort of difference between >> a function and a method. > >I don't understand your point. There is currently a difference >between a function and a method that could be eliminated by >making self a reserved word and removing it from the method >header. Or have you never tried to invoke a method from the >wrong context and gotten the "unbound method" error? There's no difference in the sense that a method is simply a function whose first parameter refers to the class instance to be worked on. No magic words, no "undeclared" parameters. It means that in my demo code in limitcases.py (somewhere in the newsgroup lately) I can say limitcases.Lowest.__str__ = lambda x: "-Infinity" to give the Lowest class a new method sans ennuis. Regards. Mel. From python at sarcastic-horse.com Tue Sep 16 16:02:53 2003 From: python at sarcastic-horse.com (python at sarcastic-horse.com) Date: Tue, 16 Sep 2003 16:02:53 -0400 (EDT) Subject: how to build a list of mx.DateTime objects from a start and end date? Message-ID: <59268.199.169.240.132.1063742573.squirrel@svr1.turboweb.net> Hi- I want to make a list of mx.DateTime objects that cover all the monthly intervals between two points. For example: >>> import mx.DateTime >>> nov1999 = mx.DateTime.Date(1999, 11) >>> mar2003 = mx.DateTime.Date(2003, 3) >>> alldates = mk_list(startdate=nov1999, enddate=mar2003) >>> alldates [ ... a bunch of mx.DateTime objects including and between the startdate and enddate ...] How would I do something like this? Thanks for the help. From mack at incise.org Tue Sep 9 16:48:11 2003 From: mack at incise.org (Nick Welch) Date: Tue, 9 Sep 2003 15:48:11 -0500 Subject: How to instatiate a class of which the name is only known at runtime? In-Reply-To: <1063139737.1862.5.camel@adsl-209.204.179.133.sonic.net> References: <20030909193530.GA2218@darkstar.localdomain.fake> <20030909194508.GV16821@incise.org> <1063139737.1862.5.camel@adsl-209.204.179.133.sonic.net> Message-ID: <20030909204811.GW16821@incise.org> On Tue, Sep 09, 2003 at 01:35:37PM -0700, Chad Netzer wrote: > "class" is a keyword, and so the above won't work, but the idea is > sound. (Just use a different identifier than 'class') Doh, totally slipped my mind. > The first form, using getattr, is perfectly idiomatic, and that is what > I use. Agreed, getattr isn't bad, but using vars()[foo] or globals()[foo] always feels gross to me. > Also, regarding the earlier import question, there is the builtin > __import__ function: > > help(__import__) Cool. I've seen it before but never gave any thought to it. -- Nick Welch aka mackstann | mack @ incise.org | http://incise.org Every man has his price. Mine is $3.95. From newsgroups at jhrothjr.com Fri Sep 5 16:32:34 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 16:32:34 -0400 Subject: Python port to Swiss Ephemeris work with 2.3? References: <734b753f.0309041612.2066021@posting.google.com> <734b753f.0309042237.5ded1230@posting.google.com> <734b753f.0309051002.4e625e8e@posting.google.com> Message-ID: "Dave" wrote in message news:734b753f.0309051002.4e625e8e at posting.google.com... > > I found it on the Vaults under the Misc heading. Looks good. > > Looks a lot better than my interface. > > You need to recompile using the same compiler that Python > > was compiled with (I believe that's VC 6 for the Windows version.) > > Extension modules ***always*** need to be recompiled for major > > Python releases. John Roth > > Thanks John, I wouldn't know how to do that since I haven't worked > with C much. -Dave Sigh. I don't either. My copy of VC6 is the cheap one that only includes the C++ compiler. Unfortunately, the C module was generated by SWIG, which makes converting it to C++ so I can compile it right out of the question. John Roth From timr at probo.com Fri Sep 26 00:21:08 2003 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Sep 2003 21:21:08 -0700 Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: Grant Edwards wrote: > >Ben Finney wrote: > >>> But now, among a small group of cognoscenti, it is a truism that this is a >>> myth, and that Windows will allow you to use either the forward or the >>> backward slash as a pathname separator. >> >> I highly doubt it, since the forward slash (or just "slash") is the >> conventional Windows command-line option indicator, > >That was configurable back in the DOS days. There was a "well-known" byte in >system RAM that contained the "switch" character. IIRC, DOS even shipped >with a utility to change that value. Yes, indeed. There was a SWITCHAR option in config.sys, and a corresponding DOS service, until DOS 3.0, when it was removed because they couldn't make it work with network software. So, the situation can be summed up rather simply: * All DOS services since DOS 2.0 and all Windows APIs accept either forward slash or backslash. Always have. * None of the standard command shells (CMD or COMMAND) will accept forward slashes. Even the "cd ./tmp" example given in a previous post fails. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jakle1 at hotmail.com Sun Sep 28 23:28:27 2003 From: jakle1 at hotmail.com (Jakle) Date: Mon, 29 Sep 2003 03:28:27 GMT Subject: Recursion References: Message-ID: That's great. You guys have no idea how much that helped. And I love that debugging tip. For some reason I thought that the 2 statements after the recursion call, "result = n * recurse" and "return result" weren't executed till n == 0. If you can't tell, I'm new to this. But I'm dedicated. I want to thank you guys soooo much for taking the time to help out. I'm sitting here jumping for joy because it's alittle more clear :-) I can't wait till it's me helping out in the future. I'm still alittle confused about why the flow of execution goes down then up again, but I now have the tools to look at it in a better light. Time to get my nose in the book again, then write another function using the same logic in order to make sure I understand. Thanks again :-) From link0937 at hotmail.com Tue Sep 16 23:11:42 2003 From: link0937 at hotmail.com (Link) Date: Wed, 17 Sep 2003 11:11:42 +0800 Subject: How can I rewrite the JPython to Python? Message-ID: Hello!I am new to Python and I would like to rewrite the following code to python use to call by C program:// JPython code ======================================= import org.python.util.PythonInterpreter; import org.python.core.*; public class SimpleEmbedded { public static void main(String []args) throws PyException { PythonInterpreter interp = new PythonInterpreter(); System.out.println("Hello, brave new world"); interp.exec("import sys"); interp.exec("print sys"); interp.set("a", new PyInteger(42)); interp.exec("print a"); interp.exec("x = 2+2"); PyObject x = interp.get("x"); System.out.println("x: "+x); System.out.println("Goodbye, cruel world"); } } // C Language code ============================== void main() { Py_Initialize(); printf("Hello, brave new world"); PyRun_SimpleString("import sys"); PyRun_SimpleString("print sys"); // interp.set("a", new PyInteger(42)); // I can't rewrite,Please Help! PyRun_SimpleString("print a"); PyRun_SimpleString("x = 2+2"); // PyObject x = interp.get("x"); // I can't rewrite,Please Help! // System.out.println("x: "+x); // I can't rewrite,Please Help! Py_Finalize(); printf("Goodbye, cruel world"); } From antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru Fri Sep 26 10:11:38 2003 From: antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru (anton muhin) Date: Fri, 26 Sep 2003 18:11:38 +0400 Subject: Equivalent of std::set In-Reply-To: References: Message-ID: Nicolas Fleury wrote: > Hi, > > I haven't work so much in python and I was wondering what python > programmers use for string collections, like an equivalent of C++ > std::set. Do you use a dictionary with dummy values? Tuple/list? Is > there any other structure in some module with uniqueness ensured and > lookup optimised? I'm only interested in storing strings in that > structure. > > Thx for help > > Nicolas > Python 2.3 introduced Set type, in the former versions common idiom was to use dictionaries with dummies IMHO. anton. From fawcett at teksavvy.com Tue Sep 16 19:43:47 2003 From: fawcett at teksavvy.com (Graham Fawcett) Date: Tue, 16 Sep 2003 19:43:47 -0400 Subject: OT: Re: from clipper move to python In-Reply-To: References: Message-ID: <3F67A033.6090306@teksavvy.com> Ken Roberts wrote: >ads wrote in message news:... > > >>Hi Everyone, >> >>I'm starting learning python about 2 weeks, and still have >>difficulties to create GUI based application because I never learn >>about classes and other OOP things. Does anyone knows how to >>create text console application like clipper using python. >> >>Thanks, >> >> > >For those who ask - clipper is a programming language that is a >compiled version of dBase relational database scripting language. > > I'm not old enough to have stories about how I hacked on a shiny new PDP-10 or any such thing. But seeing Clipper on c.l.py brings back memories; my first real programming job was writing a database app in Clipper. How blazingly fast it was, compared with the earlier dBase III version of the app! Clipper was the One True Way to write data-driven apps. Or so I thought: I was a green kid back then, and hadn't even heard of SQL... Those console-based data-entry applications were infinitely more efficient for a good typist than anything that involves (or even allows) a mouse. rhapsodically yours, -- Graham From dave at 3dex.com Wed Sep 10 20:01:19 2003 From: dave at 3dex.com (Dave Benjamin) Date: Thu, 11 Sep 2003 00:01:19 GMT Subject: Problems with setting up mod_python and Apache References: <3f5f6b41$0$239$fa0fcedb@lovejoy.zen.co.uk> <4zK7b.11532$NW3.6643@news1.central.cox.net> Message-ID: Quoting John Dean: > > Here are the lines in my httpd.conf > LoadModule python_module /usr/lib/apache/mod_python.so > > AddModule mod_python.c > > > ..... > ..... > > Addhandler python-program .py > PythonHandler test Looks right to me. Have you verified that: a) you are editing the right httpd.conf (hey, it happens...) b) you are affecting the directory you think you are (do other apache directives work properly?) Once things are working, you may also want to read up on and consider adding this: PythonInterpPerDirectory on (hint: otherwise, if you have a test.py in another directory, you will get bizarre results) Good luck, Dave PS - Please keep replies to the list for the benefit of others. =) From dave at boost-consulting.com Sat Sep 27 12:14:29 2003 From: dave at boost-consulting.com (David Abrahams) Date: Sat, 27 Sep 2003 12:14:29 -0400 Subject: Comment on PEP-0322: Reverse Iteration Methods References: <95rcb.2002$yU5.1775@nwrdny01.gnilink.net> <7da8d8f8.0309242347.48c2f31e@posting.google.com> <8RScb.169633$R32.5449258@news2.tin.it> <7v49nvc9rlj0mi0iojmp3gu359mpgiuk98@4ax.com> <0acdb.128801$hE5.4391247@news1.tin.it> <1Xhdb.130593$hE5.4445587@news1.tin.it> Message-ID: Alex Martelli writes: > David Abrahams wrote: > ... >> Well, (understanding that you don't nececessarily agree with the >> above) you can in fact iterate on std::pair with the usual C++ >> iterator protocol, > > You mean there's an std::pair::begin etc?! No, that's an entirely different question. I can build an iterator which iterates over pair. > OK, I guess I'm even rustier on standard C++ than I thought I was -- > I could have SWORN there wasn't. (Std chapter & verse pls? I plan > to win bets based on this tidbit...!-). So I guess the lack of > those in gcc is a breach of the Standard on gcc's part...? No, nothing like that. >> and with a new mixed compile-time/runtime tuple iterator protocol >> developed by Doug Gregor, iteration over heterogeneous tuples is >> possible too. It certainly is desirable to be able to do that; >> it's a real need that has come up in practice. > > So, given an arbitrary struct, with fields (generally) of different > types, you can iterate field by field? Ah, no. A tuple in C++ is a different thing, and much more like a Python tuple: http://www.boost.org/libs/tuple > That's basically what the "heterogeneous tuple" is supposed to be > equivalent to, in the "party line" I was relating Well, that's just nutty. We can make a much better analogy to a struct in Python with the usual class hacks. But even then, we can arrange to iterate the attributes. > (although the names to go with the fields are only present in a FEW > such tuples, such as those returned by modules time and stat, Whaa?? Are they subclassing tuple? Nope, time.struct_time is not even a tuple. It's just the struct hack with a tuple-like repr() >>> time.localtime() (2003, 9, 27, 12, 10, 43, 5, 270, 1) >>> type(time.localtime()) >>> time.struct_time.__bases__ (,) > as of now; more general tuples still haven't grown the ability to > access fields by name, in Python). > > My partial dissent comes from feeling the need for "frozen/immutable > lists" and the fact that tuples are often used as such (including goofy > immutable representations of dicts, e.g. via tuple(thedict.iteritems()), > and the like). If tuples cannot be thought of as immutable lists, then > (I think) we need "immutable/hashable/frozen" lists by other means. I agree completely. > (I need to say "I think" because, as I quoted, Ruby experts claim that > the "anyobject.freeze" feature they do have isn't actually as useful > as it SEEMS it should be -- though I'm not sure I understand why, yet). Immutability is extremely useful whenever you have inplace operations like +=, because it guarantees value stability for other references to the same object. -- Dave Abrahams Boost Consulting www.boost-consulting.com From tonym1972/at/club-internet/in/fr Fri Sep 26 11:19:24 2003 From: tonym1972/at/club-internet/in/fr (Anthony McDonald) Date: Fri, 26 Sep 2003 17:19:24 +0200 Subject: server side socket program hangs References: <57efaf35.0309260215.5ddd5734@posting.google.com> Message-ID: <3f74571f$0$20952$7a628cd7@news.club-internet.fr> wrote in message news:57efaf35.0309260215.5ddd5734 at posting.google.com... > hi, > i am writing a socket program in python,both client side and server > side.I've written the client side which is working perfectly > fine(checked it against server program written in C).but as for my > server program written in python it simply hangs.it does not show any > error also.I've tried sample programs available .I don understand what > the reason is as i am quite new to it. > here is teh server side program: > > /////////////////////// > from socket import * > import socket > import sys > > HOST = '' #any address > PORT = htons(9999) #same port address as client > > > can someone tell me what the problem is? Your applying a function designed to simplyfy transfering IP addresses to a literal value you want to use for your port. The following should show the effect thats now happening. PythonWin 2.3.1 (#47, Sep 23 2003, 23:47:32) [MSC v.1200 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import socket >>> socket.htons(9999) 3879 >>> -- Anthony McDonald This email address is protected by SpamBayes www.spambayes.org From hildegarde_roth at yahoo.de Wed Sep 17 09:44:49 2003 From: hildegarde_roth at yahoo.de (Hilde Roth) Date: 17 Sep 2003 06:44:49 -0700 Subject: Indexing list of lists References: <95b4b9ac.0309161015.6a0567a7@posting.google.com> Message-ID: <95b4b9ac.0309170544.77e0d12a@posting.google.com> Thanks for the suggestion but zip is not nice for large lists and as for array/numpy, although I chose a numeric example in the posting, I don't see why only numeric arrays should enjoy the benefit of such a notation. l[;0] is illegal right now but does anyone of any other bit of syntax it might conflict with if proposed as an extension? Hilde From tonym1972/at/club-internet/in/fr Thu Sep 11 17:24:13 2003 From: tonym1972/at/club-internet/in/fr (Anthony McDonald) Date: Thu, 11 Sep 2003 23:24:13 +0200 Subject: ftplib question: how to upload files? References: Message-ID: <3f60e646$0$20947$7a628cd7@news.club-internet.fr> wrote in message news:mailman.1063305377.21943.python-list at python.org... > Hi: > > I want to write a procedure to automatically upload some files for me, but > I'm getting stuck. Before I write my own gruesome put() function, I > wanted to check if there is an easier way. > > Here's what I can do so far: > >>>import ftplib > >>>conn = ftplib.FTP('ftp.example.com') > >>>conn.login(user='userid', passwd='passwd') > >>>conn.cwd('/var/www/html/incoming') > > What do I do to send files? > > I have three files I want to upload, but I'm not sure what to do. I hoped > to find a ftplib.put() method, but it looks like ftplib is a low-level > interface. > > All help is welcome. > > The methods your searching for are storlines (for ascii) or storbinary (for non ascii). You can simplyfy the process slightly with your own wrapper to those 2 methods to guess the file mode and call the correct method with the STOR command created for you. An example is below. def upload(conn, fname): (head, tail) = os.path.split(fname) command = "STOR " + tail fd = open(fname, 'rb') temp = fd.read(2048) fd.seek(0, 0) if temp.find('\0') != -1: conn.storbinary(command, fd) else: conn.storlines(command, fd) fd.close() Anthony McDonald From NO-MAIL at hotmail.com Mon Sep 22 17:15:55 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Mon, 22 Sep 2003 21:15:55 GMT Subject: Factorials References: <3ee1e6f1@shknews01> <3ee1fa98$0$45181$65c69314@mercury.nildram.net> Message-ID: No difference on my computer (see my note at the end): times: recursion 6.66 reduction 3.50 iteration 3.16 (for i in range(2,n+1)) xteration 3.16 (for i in xrange(2,n+1)) But when I added another function (it'e a bit slower its range/xrange partners) def factorial_niter(n): s = 1 i = 2 while i<=n: s *= i i += 1 return s ALL the times increased, probably because the grown dictionary. bast times: recursion 6.77 reduction 3.51 iteration 3.20 xteration 3.17 nteration 3.36 M-a-S "Julian Tibble" wrote in message news:slrnbmrgau.438.chasm at galileo.rift... > <...> > (code I used:) > def recursion(n): > s = 1 > for i in range(2, n+1): > s *= i > return s > > def xrecursion(n): > s = 1 > for i in xrange(2, n+1): > s *= 1 > return s s *= 1 <--------------------------------- maybe this is your difference! From max at alcyone.com Fri Sep 19 15:44:19 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 19 Sep 2003 12:44:19 -0700 Subject: How do I learn operator overriding? References: <53332.199.169.240.132.1063995923.squirrel@svr1.turboweb.net> Message-ID: <3F6B5C93.15E9C99B@alcyone.com> python at sarcastic-horse.com wrote: > But if I subtract an integer from my qDate object, I want to get a new > qDate object returned, like this: > > >>> 2001q4 - 2 > (new qDate object with year=2001 and quarter=2) > > Any ideas how to make this possible? In that case an extra class might be appropriate (untested): class SubordinateDate(Date): def __init__(self, date, quarter): self.year = date.year self.quarter = quarter and change the original Date.__sub__ method to: ... def __sub__(self, other): if type(other) is types.IntType: other = SubordinateDate(date, other) return self.quarters() - other.quarters() ... -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ You and I / We've seen it all / Chasing our hearts' desire \__/ The Russian and Florence, _Chess_ From grante at visi.com Sat Sep 6 14:07:28 2003 From: grante at visi.com (Grant Edwards) Date: 06 Sep 2003 18:07:28 GMT Subject: Why the 'self' argument? References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> Message-ID: <3f5a2260$0$166$a1866201@newsreader.visi.com> In article , Harri Pesonen wrote: > I agree, it's not logical. I'm learning Python at the moment, and like > it very much. This "self" thing seems to be the only odd feature, It seemed quite natural to me, but perhaps that's because I'd used other languages that worked the same way. Coming from Modula-3 and Smalltalk, the way classes worked in Python seemed quite intuitive. OTOH, C++ seems like a real non-intuitive mess to me. > it feels like the whole class feature was added later. Why? > The Quick Python book says that Python was designed to be > object oriented from the ground up. Is it true? -- Grant Edwards grante Yow! ... I think I'm at having an overnight visi.com sensation right now!! From aleax at aleax.it Mon Sep 22 11:45:57 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 22 Sep 2003 15:45:57 GMT Subject: DSU pattern (was Re: Trouble sorting lists (unicode/locale related?)) References: Message-ID: Duncan Booth wrote: ... > FWIW, I think something like this belongs in the standard library rather > than as a method on lists or a new builtin. Definitely not a method on lists, we agree on that. Problem is, there is no module in the standard library to collect "functions that are often useful but not QUITE often enough to warrant being built-ins" (and if there was, there are quite a few current built-ins I'd like to relegate into such an auxiliary/utilities module), so that finding a good place, other than built-ins, for such utility functions, is often a bother. Alex From bellman at lysator.liu.se Sat Sep 20 16:07:17 2003 From: bellman at lysator.liu.se (Thomas Bellman) Date: Sat, 20 Sep 2003 20:07:17 +0000 (UTC) Subject: os.environ and os.path.chdir References: Message-ID: Geoff Gerrietts wrote: > Quoting Yun Mao (maoy at cis.upenn.edu): >> Hi, >> How to make changes to os.environ and os.path.chdir still effective after >> I run the script? Currently, the changes are only good within my script. I >> would like the shell who called python myprog.py also gets the change.. >> Thank you! > To the best of my knowledge, this can't be done. [...] >As far as I know, though, there's no way to actually hijack the user's >shell process. The user needs to explicitly give you that control. Actually, there are a couple of ways to do it, at least under Unix. However, they have their problems... One way is to stuff characters into the terminals input buffer using the TIOCSTI ioctl. Like this: import fcntl, termios for c in "cd /usr/lib\n": fcntl.ioctl(1, termios.TIOCSTI, c) It only works if it is being run interctively, under a tty, though. If you have a shell script running the above program, the shell script won't see the command, and thus won't change directory. It will be the original shell that gets the command. And if you're not on a tty, it doesn't work at all. Also, the command you stuff into the terminal can get mixed up with normal type-ahead typed by the user, leaving some garbled command for the shell to read. So, it's not very reliable. Another way is to attach a debugger to the parent process, and force it to do the chdir() system call, or poke around in its memory to change the environment variables. Like this: import os gdb = os.popen('gdb $SHELL %d' % (os.getppid(),), 'w') gdb.write('call chdir("/usr/lib")\n') gdb.write('detach\n') gdb.write('quit\n') gdb.close() Untested code, but you probably get the idea. Changing the environment variables of the parent is a bit trickier. You need to know the memory layout of the parent, so you can poke the correct bytes. You might be able to locate the variable 'environ' and follow it, but there is no guarantee it is still pointing to anything useful. However, I would recommend *against* both of these methods. Don't try any of this stuff youselves, kids; always get a parent to supervise this kind of experiments! :-) -- 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 drlinux at columbus.rr.com Tue Sep 16 21:06:37 2003 From: drlinux at columbus.rr.com (Dave Reed) Date: Tue, 16 Sep 2003 21:06:37 -0400 Subject: App development for Sharp Zaurus PDA using QTopia? In-Reply-To: <3f6751fc$0$162$a1866201@newsreader.visi.com> References: <3f6751fc$0$162$a1866201@newsreader.visi.com> Message-ID: <200309162106.37385.drlinux@columbus.rr.com> On Tuesday 16 September 2003 14:10, Grant Edwards wrote: > I see there's a Python binary package available for the Sharp > Zaurus PDA. Has anybody deleloped an app for that platform? > I'm wondering if the resource requirement of Python are a > problem on that platform. It works ok. I wouldn't try to do heavy number crunching with it or process lots of data, but for basic PDA type apps it's fine. I wrote a program for keeping attendance in my classes using the Qt interface. That's my only Qt experience - I've used Gtk for 6 years so I'm more used to it. Dave From aleax at aleax.it Thu Sep 25 09:58:26 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Sep 2003 13:58:26 GMT Subject: Packages and PyKyra References: <1dCcb.11020$Of2.520042@twister.tampabay.rr.com> Message-ID: <6wCcb.164799$R32.5291608@news2.tin.it> Robert Clayton wrote: > In the PyKyra example programs what does the statement: > > "from PyKyra import *" > > I now assume that this represents a Package hierarchy and not the file > "PyKyra.py" as there is none but for Windows 2000 I am unable to determine > whereor how the path is represented (registry, environment, etc.). Any > suggestions? I have no idea about what PyKyra is, but: [a] You can find out what the path is, at any time, by the two statements: import sys print sys.path [b] If you're right in stating there is no PyKyra.py file, then the import may be coming from: [b1] a PyKyra.pyc or .pyo bytecode file [b2] a PyKyra.pyd or .dll C-coded extension module [b3] the __init__.py file in a PyKyra directory on the path The only case involving "packages" is [b3] -- that's what a package _IS_... a directory with an __init__.py file. In any case, the "from PyKyra import *" statement gets the contents listed in the __all__ entry in module PyKyra, or, if no such entry, then all entries in module PyKyra whose names do not start with a single underscore character _ . The usage of "from whatever import *" is generally unadvisable except perhaps in those rare cases in which module 'whatever' has been carefully designed to support this. Personally, I've lost the habit of "import *" just about entirely -- even for carefully designed modules such as Tkinter and Numeric, I do "import Tkinter as Tk" or "import Numeric as N" and then access their entries explicitly as Tk.Tk, N.array, etc, etc. I find, personally, that this makes my programs more maintainable. Alex From slhath at charter.net Tue Sep 30 17:04:19 2003 From: slhath at charter.net (Scott Hathaway) Date: Tue, 30 Sep 2003 16:04:19 -0500 Subject: intercepting smtp email References: <5Uieb.49566$Lw6.2263065@phobos.telenet-ops.be> <7tkeb.49855$CW5.2223199@phobos.telenet-ops.be> Message-ID: Thanks for the suggestions. My second alternative is to simply use the api in outlook and be bound to that client. Worse things have happened. :) Scott "Rudy Schockaert" wrote in message news:7tkeb.49855$CW5.2223199 at phobos.telenet-ops.be... > It seems you've looking where I've earlier this week ;-) I'm affraid > there's nothing for Python on Windows yet. > > .r!kard wrote: > > > Google rules: > > http://home.student.utwente.nl/g.v.berg/btk/ > > This one is for unices only, no Windows. > > > http://pycap.sourceforge.net > > From the Todo.txt file: > > * Make this work on Windows. I briefly struggled with compiling using > VC7 under Win XP > using winpcap_ and LibnetNT_. No luck, and was getting some rather > interesting errors > about missing header files which appeared to be where they should be :-/. > > > http://www.ghaering.de/python/unsupported/pylibpcap/ > > This could be a candidate if it were available for Python 2.3.x . It's > for Python 2.2 only now. > > > http://aspn.activestate.com/ASPN/Mail/Message/python-list/1578279 > Further down the thread: > http://aspn.activestate.com/ASPN/Mail/Message/python-list/1578500 > Gerhard H?ring wrote: > > http://www.ghaering.de/python/unsupported/pylibpcap/ > > I'll check if the sniff.py example will work, too. > > It doesn't look like it does. I may have introduced a subtle bug or some > more changes are needed to make it useful under win32. > > If anybody wants to continue the win32 port, it's open source and you > can continue where I stopped. > > -- Gerhard > > Out of luck again :-( > > > > > *pheew* that was some real hardcore Googeling I can tell you... > > > > .r!kard > > >> > >> > >>>>>>>I want to write an NT service that will intercept any outgoing smtp > >>>>>>>traffic, like Norton Antivirus does. Can anyone tell me how I can > >>> > >>>do > >>> > >>>>>>>something like this in Python? I do not know how to intercept the > >>>>>>>outgoing traffic, specifically. > >> > > > > > From ryan at ryanswift.com Wed Sep 3 15:00:34 2003 From: ryan at ryanswift.com (Ryan Swift) Date: 3 Sep 2003 12:00:34 -0700 Subject: Extracting TIFF from emails References: <87y8x654qk.fsf@pobox.com> Message-ID: I have found the email module, I am using 2.2.2. This is my code: if __name__ == "__main__": server = connect(mailserver, mailuser, mailpasswd) try: (msgCount, msgBytes) = server.stat() print '\nThere are', msgCount, 'mail messages, total', msgBytes, 'bytes' print 'Retrieving message', msgCount, '\n' (hdr, message, octets) = server.retr(msgCount) print 'Header:', hdr print 'Octets:', octets print 'Message:', message email_file = open('email.txt', 'w') email_file.writelines(message) email_file.close() for part in message.walk(): if part.get_content_maintype() == 'multipart': continue filename = part.get_filename() fp = open(os.path.join(dir, filename), 'wb') fp.write(part.get_payload(decode=1)) fp.close() finally: server.quit() print 'Closed connection I can print message and see it with no problems. It also gets written to 'email.txt' with no problems. It is a simple multi-part MIME email with TIF attachment. However, I get this error when I try to walk through it: Traceback (most recent call last): File "C:\Python22\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 305, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=1) File "C:\Python22\lib\site-packages\Pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python22\lib\site-packages\Pythonwin\pywin\debugger\debugger.py", line 591, in run exec cmd in globals, locals File "C:\Python22\mailtest.py", line 29, in ? for part in message.walk(): AttributeError: 'list' object has no attribute 'walk' Am I not properly using walk? Thanks again. From lvraab at earthlink.net Tue Sep 30 17:13:48 2003 From: lvraab at earthlink.net (Lucas Raab) Date: Tue, 30 Sep 2003 21:13:48 GMT Subject: Visual Basic integration Message-ID: Can I use Python as an extension language to Visual Basic sort of like in C or C++? From eppstein at ics.uci.edu Wed Sep 24 20:11:01 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 24 Sep 2003 17:11:01 -0700 Subject: Pre-PEP: reverse iteration methods References: Message-ID: > > # let inifinite iterators identify themselves > > assert not hasattr(obj, 'infinite') > > > >As infinite iterators are rare, it would not be too cumbersome to let them > >identify themselves as such. It would be quite cumbersome to have to identify simple generators as infinite or finite manually, and impossible (halting problem) to do so reliably automatically. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From mark at hahnca.com Tue Sep 30 18:32:58 2003 From: mark at hahnca.com (Mark Hahn) Date: Tue, 30 Sep 2003 15:32:58 -0700 Subject: append special chars with "\" References: <3f793544$0$64721@hades.is.co.za> Message-ID: Isn't this what re.escape(string) is for? "tertius" wrote in message news:3f793544$0$64721 at hades.is.co.za... > Is there a better way to append certain chars in a string with a > backslash that the example below? > > chr = "#$%^&_{}" # special chars to look out for > str = "123 45^ & 00 0_" # string to convert > n = "" # init new string > for i in str: > if i in chr: # if special character in str > n+='\\' # append it with a backslash > n+=i > print "old:",str > print "new:",n > > > Thanks > Tertius > From pheniks at softhome.net Wed Sep 10 00:01:19 2003 From: pheniks at softhome.net (Page) Date: Wed, 10 Sep 2003 06:01:19 +0200 Subject: advice choosing IDE In-Reply-To: References: Message-ID: Y2KYZFR1 wrote: > Lupe wrote in message news:... > >>I'm convinced to try Python! >> >>I've read many posts, and although I recently bought a book on C to start >>learning it, I'd like to give Python a good chance. >> >>What IDE would you recommend for someone who needs easiness of use with a >>background of Pascal and VB for MS Office? I've definitely changed to >>Linux now and I would like a free IDE either for procedural or object >>oriented programming. >> >>I'd need an easy help on syntax, if possible with examples and a front end >>debugger with easy trace, breakpoints and watches. >> >>Programming is not my profession, just a hobby! >> >>With all this in mind what would be your recommendation? I've read so many >>posts on the subject that I'm confused. For a beginner, I just need one >>solution... >> >>Lupe > > > > your best bet is Komodo from ActiveState . . . not free but definately > worth the money. The other bet is Visual Python from guess who, > ActiveState it add great support for Python to Visual Studio 6 / .Met > > Last choice would be Visual SlickEdit . . . > > other than that, Python IDE choices are all just glorified color coded > crappy text editors. I find Wing IDE to work wonders. Has all the essentials you'll need. And works on linux & win32 ;) http://archaeopteryx.com/wingide HTH Page From robin at jessikat.fsnet.co.uk Mon Sep 29 14:36:44 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 29 Sep 2003 19:36:44 +0100 Subject: extension call backs and the GIL References: Message-ID: <8z8ebLA8uHe$EwB+@jessikat.fsnet.co.uk> In article , Aahz writes ...... >Looks like Bernhard has put you on the right track, but just for the >record: calling an extension does not automatically release the GIL; you >need to explicitly call the Py_BEGIN_ALLOW_THREADS macro. I was just >assuming that because you said "accelerator" you were already releasing >the GIL. The code is intended to run single thread so we never have done anything about threading. It's a real pain. In a zope world we ought really to give every request a fresh context ie each thread would see an entirely 'clean' python and then be forced to load its own fonts/resources. It just sucks from the overall system viewpoint. How does one ensure that each thread sees its own version of sys.modules etc etc or is that considered a dumb question? -- Robin Becker From tzot at sil-tec.gr Thu Sep 4 13:07:58 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Thu, 04 Sep 2003 20:07:58 +0300 Subject: Extracting TIFF from emails References: <87y8x654qk.fsf@pobox.com> <87llt5fpcc.fsf@pobox.com> Message-ID: On 4 Sep 2003 08:15:28 -0700, rumours say that ryan at ryanswift.com (Ryan Swift) might have written: >Apparently I am getting the email as a list, but I don't know of a way >to do it otherwise. I assume you didn't see my reply since yesterday? I don't know the mailconfig module; does it return a list of strings that end with '\n'? If yes, use message = email.message_from_string(''.join(your_list_of_strings)) If not, substitute '\n' for '' in the line above. -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From tzot at sil-tec.gr Tue Sep 30 12:34:54 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 30 Sep 2003 19:34:54 +0300 Subject: append special chars with "\" References: <3f793544$0$64721@hades.is.co.za> <8e4jnvgmkcs0v1p8vneln8d12r99s2t49f@4ax.com> Message-ID: On Tue, 30 Sep 2003 14:50:19 GMT, rumours say that Alex Martelli might have written: >Christos TZOTZIOY Georgiou wrote: > >> On Tue, 30 Sep 2003 07:58:27 GMT, rumours say that Alex Martelli >> might have written: >> >>>charmap = {} >>>for c in chr: charmap[c] = c+'\\' >> >> I believe you meant charmap[c] = '\\' + c ... > >Sure, if the original poster wants the backslash BEFORE the character >(the "append" in the subject suggested to me he wanted it AFTER). You are correct about the subject (append instead of 'pre-pend' -sp?), but the OP's code was not appending, in spite of the comments: for i in str: if i in chr: # if special character in str n+='\\' # append it with a backslash n+=i I just assumed the OP was a better coder than English speaker :) -- TZOTZIOY, I speak England very best, Ils sont fous ces Redmontains! --Harddix From rowen at cesmail.net Wed Sep 10 14:37:46 2003 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 10 Sep 2003 11:37:46 -0700 Subject: Running user scripts in a Tkinter app? Message-ID: I have a Python/Tkinter remote control application and want to add support for running user scripts. I would like the scripts to be written in python, would like them to be able to update Tkinter widgets and (the hard part) would also like them to be capable of pausing until some condition is met (e.g. a remote control command finishes) without hanging the event loop. I plan to add a library of routines to send commands and wait for specific replies. For example: - call(cmd) sends a command string to the remote host and returns a "command object" that keeps track of the state of the command - waitcmd(cmd_obj) pauses the script (but not the overall application) until cmd_obj finishes or fails I'm confused as to the best way to write the "waitcmd" function. It seems like a good place to use threads, but my understanding is that Tkinter is not thread safe. The only solution I've thought of is to try to recreate the Tkinter main loop within the wait function. Very crudely: tkobj = Tkinter.Frame() def waitcmd(cmd_obj): while not cmd_obj.isdone(): tkobj.update() I think this will work, but am worried it will be much slower than the usual Tkinter main event loop. If there was some way to start a new Tkinter event loop (while the main loop is paused) and terminate this new loop when the wait was finished, that'd be perfect. Any suggestions? Would this be easier in some other GUI library? -- Russell From ialbert at mailblocks.com Mon Sep 8 18:51:04 2003 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 08 Sep 2003 18:51:04 -0400 Subject: gadfly gfplus error Message-ID: Hello, I've been playing around with gadfly, and it is a great piece but I am having problems with gfplus the interactive shell to gadfly. Namely I get the following error when running the file: --- Traceback (most recent call last): File "/usr/local/bin/gfplus", line 3, in ? main() File "/usr/local/lib/python2.3/site-packages/gadfly/scripts/gfplus.py", line 269, in main shell.cmdloop() File "/usr/local/lib/python2.3/cmd.py", line 109, in cmdloop self.preloop() File "/usr/local/lib/python2.3/cmd.py", line 150, in preloop if self.completekey: AttributeError: GadflyShell instance has no attribute 'completekey' --- It looks as if the GadflyShell does not provide some attributes that are needed later on. Inserting the cmd.Cmd.__init__(self) as the first line of the GadflyShell constructor solves this problem. Is that the right solution? Istvan. From alanmk at hotmail.com Thu Sep 25 05:40:41 2003 From: alanmk at hotmail.com (Alan Kennedy) Date: Thu, 25 Sep 2003 10:40:41 +0100 Subject: CGI Redirect to another page References: <09a3d6364c.tim@worthy.demon.co.uk> <2c60a528.0309240338.1e4dd261@posting.google.com> Message-ID: <3F72B819.F76F0821@hotmail.com> [Andrew Chalk wrote] > What is wrong with meta-refresh? It is claimed that search engines treat meta-refresh with suspicion. I don't know if this is true or not. The following article (as an example, this is just the first link I found when googling for "abuse meta refresh"), claims that Altavista bans sites that use a meta refresh period below 30 seconds. META Refresh And Search Engines http://www.netmechanic.com/news/vol4/promo_no15.htm regards, -- alan kennedy ----------------------------------------------------- check http headers here: http://xhaus.com/headers email alan: http://xhaus.com/mailto/alan From FBatista at uniFON.com.ar Thu Sep 11 18:17:59 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 11 Sep 2003 19:17:59 -0300 Subject: list to string Message-ID: #- main (args): #- fhand=open(args[1:],"r+") This is because args[1:] returns a list, and you need a string. See: >>> mylist = ["first", "myfile.txt", "third"] >>> mylist[1:] ['myfile.txt', 'third'] >>> mylist[2] 'third' >>> . Facundo From __peter__ at web.de Thu Sep 4 10:31:04 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Sep 2003 16:31:04 +0200 Subject: question: How can I put empty directories into a zip-archive? References: <3F574431.6020902@snafu.de> Message-ID: T. Kaufmann wrote: > Hi there, > > in my directory are some 'normal' files like *.py sources and some empty > directories too. How can I put all togehter into a zip-archive? > > There is no problem to zip the *.py files but if I try to add empty > directories > an exception is trown. > > Thanks. > > o-o > > Thomas Try http://mail.python.org/pipermail/python-list/2003-June/170517.html Peter From fgeiger at datec.at Sun Sep 28 07:50:27 2003 From: fgeiger at datec.at (F. GEIGER) Date: Sun, 28 Sep 2003 13:50:27 +0200 Subject: IDE with a specific feature References: Message-ID: <3f76cabb@news.swissonline.ch> Wing can do that too: Open both the editor and the source browser. In the source browser select a method being in the module shown in the editor and then select "Source". Cheers Franz "Daniel Klein" schrieb im Newsbeitrag news:j7ocnvshp0jar2duskdgpd92qc7blvf8t0 at 4ax.com... > I don't want to get into a 'which IDE is the best' conversation. I'm > looking for an IDE that has the ability to view 2 (or more) > methods/functions within the same module simultaneously. > > I've looked at the screen shots for Komodo, Wing, BlackAdder, etc and > it is not obvious that any of them have this feature. > > This is something I got use to in Smalltalk and have found it quite > useful when working on several methods that work closely together. > > Daniel Klein From gyromagnetic at excite.com Tue Sep 30 08:10:52 2003 From: gyromagnetic at excite.com (gyro) Date: Tue, 30 Sep 2003 06:10:52 -0600 Subject: isNumber? check In-Reply-To: References: Message-ID: <3f7972cc@news.ColoState.EDU> Rob Hunter wrote: > > On Monday, September 29, 2003, at 10:20 AM, Gerrit Holl wrote: > >> Rob Hunter wrote: >> >>> How do I check if a value is a number in Python? >>> >>> One way is (x == type(1)) and (x == type(1.2)) and (x == >>> type(2387482734274)) and ... >>> >>> but this seems kludgy. Any better way? >> >> >> Why do you want to do so? > > > > I am writing an interpreter, and my parser has to decide if an > expression is a number or not. > > > >> Maybe, it is better in your >> case to just run the piece of code using the number, and >> if it fails, it fails. >> However, if you must, you need to >> do type(x) is type(1) and ... etc., or isinstance(x, int) >> and isinstance(x, float), etc. >> >> Gerrit. > > > Below is a function I sometimes use. -g def is_a_number(x): """This function determines if its argument, x, is in the format of a number. It can be number can be in integer, floating point, scientific, or engineering format. The function returns True if the argument is formattted like a number, and False otherwise.""" import re num_re = re.compile(r'^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?$') mo = num_re.match(x) if mo: return True else: return False From jallan at smrtytrek.com Tue Sep 23 12:18:02 2003 From: jallan at smrtytrek.com (jallan) Date: 23 Sep 2003 09:18:02 -0700 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> Message-ID: <299f1138.0309230818.22bc9bf6@posting.google.com> martin at v.loewis.de (Martin v. L?wis) wrote in message news:... > Peter Otten <__peter__ at web.de> writes: > > > # The German es-zed is special--the normal mapping is to SS. > > # Note: the titlecase should never occur in practice. It is equal to > > titlecase(uppercase()) > > > > 00DF; 00DF; 0053 0073; 0053 0053; # LATIN SMALL LETTER SHARP S > > [...] > > > > Thus, to comply with the standard, "?".upper() --> "SS" is required. > > No. It would be required if .upper would claim to implement > SpecialCasing - but it makes no such claim. Of course not. From http://www.python.org/doc/current/lib/string-methods.html#l2h-203: << *upper( )* Return a copy of the string converted to uppercase. >> This makes no claim about how the magic is done. But there is certainly an implied claim that it is done correctly. Unicode specifications are easily available at http://www.unicode.org/versions/Unicode4.0.0/. At 3.13 is indicated: << The full case mappings for Unicode characters are obtained by using the mappings from SpecialCasing.txt _plus_ the mappings from UnicodeData.txt, excluding any latter mappings that would conflict. >> Case mappings for Unicode require use of SpecialCasing otherwise the results are not in accord with the Unicode standard. At 4.2 is found: << Only legacy implementations that cannot handle case mappings that increase string lengths should use UnicodeData case mappings alone. The single-character mappings are insufficient for languages such as German >> I don't see any particular reason why Python "cannot handle case mappings that increase string lengths". Unicode again warns that using UnicodeData.txt alone is not sufficient. The text continues on "SpecialCasting.txt": << Contains additional case mappings that map to more than one character, such as "?" to "SS". >> Section 5.18 Case Mappings goes into further detail about casing issues and specifically mentions: << Case mappings may produce strings of different length than the original. For example the German character U+00DF ? LATIN SMALL LETTER SHAPR S expands when uppercase to the sequence of two characters "SS". This also occurs where there is no prcomposed character corresponding to a case mapping, such as with U+0149 'n LATIN SMALL LETTER N PRECEDED BY APOSTROPHE. >> See also http://www.unicode.org/faq/casemap_charprop-old.html for the Unicode FAQ which contains: << Q: Why is there no upper-case SHARP S (?)? A: There are 139 lower-case letters in Unicode 2.1 that have no direct uppercase equivalent. Should there be introduced new bogus characters for all of them, so that when you see an "fl" ligature you can uppercase it to "FL" without expanding anything? Of course not. Note that case conversion is inherently language-sensitive, notably in the case of IPA, which needs to be left strictly alone even when embedded in another language which is being case converted. The best you can get is an approximate fit. [JC] Q: Is all of the Unicode case mapping information in UnicodeData.txt? A: No. The UnicodeData.txt file includes all of the 1:1 case mappings, but doesn't include 1:many mappings such as the one needed for uppercasing ?. Since many parsers now expect this file to have at most single characters in the case mapping fields, an additional file (SpecialCasing.txt) was added to provide the 1:many mappings. For more information, see UTR #21- Case Mappings [MD] >> Python specifications make an implied claim of full support for Unicode and an implied claim that the function upper() uppercases a string properly. The implied combined claim is that Python supports Unicode and supports proper casing in Unicode. This implied claim is false. Truly accurate documentation for upper() should say that it uppercases a string except for those characters where uppercasing would expand a character to more than one character in which circumstance that character is not uppercased or uppercased with loss of data. Python specifications need not say how casing is done, whether by using Unicode tables directly or by using its own methods that accomplish the same results. Users should not have to know such details. They may wish to know where a particular function does not do what might be expected of it. Jim Allan From martin at v.loewis.de Tue Sep 23 17:41:45 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 23 Sep 2003 23:41:45 +0200 Subject: convert Unicode to lower/uppercase? References: <299f1138.0309210940.32e9acfe@posting.google.com> <299f1138.0309230818.22bc9bf6@posting.google.com> Message-ID: Peter Otten <__peter__ at web.de> writes: > Looking into stringobject.c (judging from a first impression, > unicodeobject.c has essentially the same algorithm, but with a few > indirections): You are mistaken. The implementation in unicodeobject.c is fundamentally different. The byte string implementation uses the C library, the Unicode implementation uses the Unicode character database. So the former cannot be changed, whereas the latter could, in theory, be extended to use additional data. Regards, Martin From anton at vredegoor.doge.nl Thu Sep 25 06:24:03 2003 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Thu, 25 Sep 2003 12:24:03 +0200 Subject: Problems with string and lists (searching and replaceing) References: Message-ID: jblazi wrote: >I shall have a computer science class this year and I decided to use >Python. It is my favourite language and I have used it for many years. Now >I thought, one of our first "real" programs, in our pre-graphical and >pre-class state, would be to write simple program that works like this: > >One of the pupils enters a word. It should be a valid German word >consisting of five letters, for example 'abcde' (which is not a German >word by the way). That may come as a surprise to non-German speakers ;-) >The the other player may enter a guess which must be a five letter word as >well, for example 'xbxxx'. Then the system answers with the string '-*---' >as the 'b' in 'xbxxx' was correct and at the right place as well. > >Had the second player entered 'xxxbx', the system had responded with >'---.-', as the 'b' is correct but not correctly positioned. > >The second player must find out the original word. > >Now I did not see how to do it as simply as posible, that was the problem. Part of the confusion arose because it was thought to be a simple problem, but instead it proved to be harder than it seemed. I have experienced this while playing with it and loosing track of what was going on inside my code. Thanks for posting your algorithm, without that as a reference I probably would have had wrong code, thinking the problem was easily solved. (I'm not completely sure I got it right *this time* even) Another matter is whether Python makes programming simpler for newbies or if it only complicates things for them by introducing a lot of high level language constructs. This is reminiscent of discussions about whether computer processors with reduced instruction set (RISC) are better than processors with more -and more complex- instructions. The argument of the RISC philosophers is that higher functions could be build using the few basic instructions and since higher functions are subject to market fluctuations (sometimes they are used a lot and sometimes not) it is preferable to only keep the basic set and to build from that. This way of thinking is not limited to processor developers but can also be observed in higher languages that pride themselves in being flexible and fast (e.g. Lisp). Of course the complex instruction set advocates remind us that we need to cater to the needs of the programmers and that it is better to provide batteries in order to prevent people making their own sublanguage each time a commonly needed procedure has to be coded. This way we get a coherent community and readable sourcecode. The problem gets to the rockbottom of decision making if one is presented with the need to teach newbies how to program. Of course newbies are better off learning only a few basic functions and to develop their own solutions as they go. It is even not uncommon for teachers to have to face the raw uninterestedness that newbies tend to express for complex instructions that they do not see the advantages of. Sometimes later it is seen that it was good to learn all that stuff, but more often than not it proves to be useless since history has proven that higher functions are subject to popular demand anyway. Now being a member of a community of programmers that all via one way or another have come to understand different coding requirements and seeing that all in all Python delivers a lot of the things one will reach anyway after hard years of reinventing the wheel each time, the question can be asked whether this knowledge can be found only by having done it the hard way, and -only after that- recognizing the elegance of the solutions offered, or if it is also possible to transfer these insights directly to untrained programmers. One problem that arises is that for newbies things make no difference that for experienced Pythoneers are considered different. For example are zip and enumerate really more difficult than using range and len for iterating ? A newbie couldn't care less since they're both new. The same goes for using dict.get versus dict[i]. So it could well be that *experienced* Pythoneers are the real newbies here. At the eve of introducing new language features like the ternary operator, iterator tools, metaclasses, backward iterators, generators etcetera, this discussion becomes a bit heated sometimes, because every new function that is accepted adds to the constant threat of total redesign of all Python functions using only a few basic instructions. Projects like Pypy that try to rebuild Python using the higher level constructs only are like someone having found a last crate of beer at a very late hour of a garden party. It's good for some fun but everybody knows that the end is near. There is just no way around rebuilding the basic structure from the ground up sometimes and IMO it would be advisable to rebuild Pythons functionality not using Pypy -although it's a nice project- but by making very small basic building blocks -like bitfields- and instead of having all functions inside one mega-dll (pythonxx.dll) it would be better to have each function inside its own dll and to access these dlls using Ctypes or something like it. This way it would be possible to construct a Python from the ground up, and instead of having a new release each time it would be possible to just update a single dll. For an analogy of what I mean see the way Cygwin distributes updates. It would create huge compatibility problems for sure, but the gains would be even greater because new higher order functions could be created on the fly, and newbies and Pythoneers would be working side by side, with the newbies having the advantage. Ok, back to reality, here's some code I produced about your specific problem, you can decide for yourself whether newbies would like it more than the script you provided (I changed your script minimally in order to be able to run it from my interpreter). It depends a lot on dict.get returning "None" when an item is not found and on having the value "0" in a dictionary being evaluated as "False" just as well as "None" and on being able to specify a default value for dict.get that it can return if there is no corresponding key in the dictionary. It can handle strings of different size. Anton def vergleiche_woerter(wort,eingabe): eing = list(eingabe) wo = list(wort) ergebnis=list('_'*len(wort)) # Suche zuerst nach Bullen for i in range(len(eing)): if eing[i] == wo[i]: ergebnis[i] = '*' eing[i]=wo[i] = None for i in range(len(eing)): if eing[i] == None: continue if eing[i] in wo: j = wo.index(eing[i]) ergebnis[i] = '.' wo[j] = None return "".join(ergebnis) def hint(word,guess): res,cnt = [],{} for w,g in zip(word,guess): if w == g: res.append('*') else: res.append('_') cnt[w] = cnt.get(w,0)+1 for i,g in enumerate(guess): if cnt.get(g): res[i] = '.' cnt[g] -= 1 return "".join(res) def test(): a,b = 'aabbab','aaaaaa' print a,b print vergleiche_woerter(a,b) print hint(a,b) if __name__=='__main__': test() From __peter__ at web.de Wed Sep 10 18:50:29 2003 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Sep 2003 00:50:29 +0200 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> Message-ID: Stephen Horne wrote: > However, it would probably catch a very substantial portion of real > accidental side-effect errors. It may be a matter of taste, but I think it will cause a *very* substantial portion of side effect errors. A simple example: def nested(ref o): o = ReadOnly(o) def fun(o): nested(ref o) # so glad we can do no harm to o...riginal x = C() fun(x) x.attr = newValue # oops Note that even in today's Python you can do weird stuff: >>> class C: pass ... >>> class D: ... def __setattr__(self, n, v): raise Exception, "read-only" ... >>> c = C() >>> c.x = 1 >>> c.__class__ = D >>> c.y = 2 Traceback (most recent call last): File "", line 1, in ? File "", line 2, in __setattr__ Exception: read-only >>> c.x 1 This would at least propagate over the entire calling hierarchy. To go back to your container example, if copying is costly and only sometimes necessary, wrap the item into a copy-on-write proxy for every logically distinct but physically identical instance. That decision should be explicit rather than hidden as a side effect of a container class. Peter From bignose-hates-spam at and-benfinney-does-too.id.au Tue Sep 23 21:06:21 2003 From: bignose-hates-spam at and-benfinney-does-too.id.au (Ben Finney) Date: 24 Sep 2003 10:56:21 +0950 Subject: why the inconsistency? References: Message-ID: On 23 Sep 2003 18:04:33 -0700, mensanator wrote: >>>> print `2**64` > 18446744073709551616L > > Why is the "L" there? I thought "L" isn't used anymore? To answer this directly: because you've asked for the result of repr( 2**64 ) which, as demonstrated, is showing you that the number is stored as a long integer (since the point of repr() is to show you information about the type of the object as well as its value). I believe the `foo` syntax is deprecated in favour of repr( foo ), no? If you'd used repr(), perhaps the assumption would have become apparent. -- \ "Outside of a dog, a book is man's best friend. Inside of a | `\ dog, it's too dark to read." -- Groucho Marx | _o__) | Ben Finney From joshway_without_spam at myway.com Thu Sep 18 18:12:22 2003 From: joshway_without_spam at myway.com (JCM) Date: Thu, 18 Sep 2003 22:12:22 +0000 (UTC) Subject: Binding frustration References: Message-ID: Rob Hunter wrote: ... > def getGenres(title): #it takes a movie title and returns a list of > genres that the movie falls into > result = [] # my accumulator > def inGenre(g): # g is a genre > if dictionary I have collected from a mini web crawl)>: > result = result + [g] # if title is of genre g, then add Here you're attempting to rebind a variable which lives in an enclosing scope. This isn't possible in Python (except for globals). Use result.append(g) instead and it should work. From mark at diversiform.com Thu Sep 18 11:22:39 2003 From: mark at diversiform.com (mark) Date: Thu, 18 Sep 2003 08:22:39 -0700 Subject: Setting environment variables In-Reply-To: Message-ID: <001301c37df8$b3a6f290$5501a8c0@markxp> I tend to establish environment variables using an install program like Inno Setup, then access them from within my Python script. This worked for me under Win2000, but I haven't tried it with XP. HTH, Mark -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Sami Viitanen Sent: Wednesday, September 17, 2003 11:41 PM To: python-list at python.org Subject: Setting environment variables Hello, Is there any other way to set variables than os.putenv(). Putenv doesn't actually put any values to actual system variables.. I'm trying to set CVSEDITOR variable automatically from script so that user wouldn't have to set that him/herself. CVS can't use variable set with putenv(). Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list From member37767 at dbforums.com Tue Sep 2 11:21:44 2003 From: member37767 at dbforums.com (alantangcs) Date: Tue, 02 Sep 2003 11:21:44 -0400 Subject: Embedding and Importing Problems Message-ID: <3317430.1062516104@dbforums.com> Hi All, Currently, I am embedding Python in a C++ program. This is what it does: 1) Initializes the interpreter (Py_Initialize) 2) Run some simple code in a string which adds the directory "Script" to "sys.path" 3) Import the module contained in "init.py" Now I place a file called "test1.py" in the "Script" directory. In "init.py" (which is in the same directory as the C++ program), I place the line "import test1". When I run the program, all seems fine until I reach Py_Finalize. The program just pops up an "Unhandled exception in ..... (python23.dll) .... Access Violation". Amazingly, if I replace the import line with "from test1 import *", everything works perfectly as well, and I don't get the unhandled exception problem. Does anyone have any ideas why "import" doesn't work? Thanks! Alan -- Posted via http://dbforums.com From tzot at sil-tec.gr Tue Sep 16 18:27:35 2003 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 17 Sep 2003 01:27:35 +0300 Subject: When passing functions as args, how to pass extra args for passed function? References: Message-ID: On Tue, 16 Sep 2003 17:08:53 -0400 (EDT), rumours say that python at sarcastic-horse.com might have written: >When I pass a function as an arg, like for map(...), how do I pass args to >use for that function? > >If I have a function like this: > >def pretty_format(f, fmt='%0.3f'): > return fmt % f > >I want to use it with map() like this: > >formatted = map(pretty_format, unformatted_list) >#exept I want fmt='%4.5f' !!! > >I need to figure out how to pass a non-default value for fmt. How do I do >that? I believe this is what you want: formatted = map(pretty_format, unformatted_list, ['%4.5f'] * len(unformatted_list)) -- TZOTZIOY, I speak England very best, Microsoft Security Alert: the Matrix began as open source. From hawkfish at trustedmedianetworks.com Thu Sep 11 11:44:24 2003 From: hawkfish at trustedmedianetworks.com (Richard Wesley) Date: 11 Sep 2003 15:44:24 GMT Subject: Massive unit test vs MySQL References: Message-ID: In article , Richard Wesley wrote: > In article , > Neil Padgen wrote: > > > On Monday 08 September 2003 22:28, Richard Wesley wrote: > > > > > In article , > > > Neil Padgen wrote: > > > > > > > > I doubt it - it is generated by mysqldump. And there is no problem > > > from the command line. > > > > > > > I use exactly the same approach to set up my unit tests, but I have a > > different way to get the mysqldump data into the database: > > > > os.system('mysql database_name < dumpfile') > > Sadly, this did not work, nor did garbage collection (gc.collect()). > > For some reason, mysql is holding onto a whole lot of connections from > my script until the script terminates. OK, I'm an idiot. It had nothing to do with the reload script. The connections were from the TestCase subclass I have that instantiates a connection management object. It appears that the unittest module does not dispose of the objects it instantiates until the end of the run, so you need to REALLY clean up in the tearDown method. I discovered this by making a persistent connection for the reload operation and noticing that the number of connections still increased. Thanks to all who responded. -- Best regards, Richard Wesley Co-President, Electric Fish, Inc. (v) +1-206-493-1690x210 (f) +1-206-493-1697 (h) +1-206-632-4536 (m) +1-206-409-4536 From frank at pc-nett.no Thu Sep 18 10:32:29 2003 From: frank at pc-nett.no (frank) Date: Thu, 18 Sep 2003 16:32:29 +0200 Subject: ANN: Soprano 0.04 released Message-ID: Soprano is a GUI app that scans a selected range of ip addresses and try to get info about the hosts such as users, localgroups, shares, operating system. This program only runs under windows. changes 0.002 > 0.003:. added settings window setting are saved in xml and are stored under data\setting.xml setting include: "logon as" with username and password or use null request resolv hostname shares users groups info portscanner improved right click menu\submenu. new functions: add user add group add share send msg (NetMessageBufferSend) changes 0.003 > 0.04:. Looks a lot better!!!! Added splitterWindow treectrl and textctrl are now "children" of splitterwindow (makes the whole thing look a lot better and more dynamic) All the information gathered is now saved the xml file data\soprano.xml. The soprano.xml is used to display info about the selected host after the initial scan. The pinger is now a separate file (pinger.py). Source code and windows binary at http://sourceforge.net/projects/soprano/ From prochak at netzero.net Thu Sep 25 23:09:22 2003 From: prochak at netzero.net (Erik Lechak) Date: 25 Sep 2003 20:09:22 -0700 Subject: Where to publish my code References: <1f0bdf30.0309212039.16c9bef0@posting.google.com> Message-ID: <1f0bdf30.0309251909.6745ed9@posting.google.com> Hello, > Not that I'm trying to discourage you in any way from working on your own, but > are you familiar with viper? I can't believe that I have never heard of this before. It looks neat, but it is implemented using tk (I prefer wxPython). I need some wxOGL-like functionality for other projects so I am writing a wxOGL-like library in python. A visual programming tool is just the best demo/testing app I can think of to shake all the bugs loose. Thanks for the link, Erik Lechak From harry.g.george at boeing.com Mon Sep 15 06:52:12 2003 From: harry.g.george at boeing.com (Harry George) Date: Mon, 15 Sep 2003 10:52:12 GMT Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <17d520f6.0309130704.7944c876@posting.google.com> <87znh89ufv.fsf@pobox.com> <878yoqoudj.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: > Steve Lamb writes: > > > On 2003-09-13, John J. Lee wrote: > > > I've never seen anybody give a convincing reason why GTk is a good > > > choice for *anything* except writing GNOME apps. > > > > I run several GTK apps that don't touch Gnome: > > Sylpheed-Claws > > Pan > > XChat > > > > GTK != GNOME. > [...] > > Yep: that's exactly what I don't understand! *Why* did you do that? > > > John Don't know about others, but I do it (run gtk-not-gnome apps) because GTK... a) Is easy to install on a variety of commercial *NIX systems, and getting better on MS Win** (contrast to gnome). b) Is fast loading (contrast to wx). c) Is GPL on all platforms (contrast to QT/KDE). d) Is rich enough/attractive enough (contrast to tcl). e) Is less painful to bring up than a gnome or kde app if you happen to be starting from somewhere else (e.g., fvwm2). So while I run pretty much everything on my trusty Linux boxes, I tend to focus on gtk for multi-platform. -- harry.g.george at boeing.com 6-6M31 Knowledge Management Phone: (425) 342-5601 From rob at cs.brown.edu Thu Sep 18 17:39:37 2003 From: rob at cs.brown.edu (Rob Hunter) Date: Thu, 18 Sep 2003 17:39:37 -0400 Subject: Binding frustration In-Reply-To: <701E2432-EA1F-11D7-967C-003065F081D2@cs.brown.edu> Message-ID: <9A18BC06-EA20-11D7-967C-003065F081D2@cs.brown.edu> So it just occurred to me that probably, in this case, the Python way is the Scheme way: def getGenres(title): def inGenre(g): return return filter(inGenre, ['Comedy','Suspense', ...]) :) But still, wrt my original complaint, doesn't it seem wrong that I couldn't write that program? Rob On Thursday, September 18, 2003, at 05:31 PM, Rob Hunter wrote: > So I thought I had come to peace with binding in Python, but then this > happened to me: > > I was trying to do things the Python way (as opposed to the Scheme > way) as was suggested to me, and so here's a shortened version of my > program: > > def getGenres(title): #it takes a movie title and returns a list of > genres that the movie falls into > > result = [] # my accumulator > > def inGenre(g): # g is a genre > if Python dictionary I have collected from a mini web crawl)>: > result = result + [g] # if title is of genre g, then add > it to the accumulator > > # and then I do a number of inGenre tests: > inGenre('Comedy') > inGenre('Sci-fi') > inGenre('Suspense') > ... > return result > > So what's wrong with this program? Well, Python tells me: > > UnboundLocalError: local variable 'result' referenced before assignment > > It seems my only choice is to move result to the global environment, > but if that's not a kludge, I don't know what is. So why doesn't this > work? Python lambdas are able to use "free" variables in this way. > Why not a def? And more importantly, how should I get around this? > > Thanks all, > > Rob > > > -- > http://mail.python.org/mailman/listinfo/python-list > From nick.keighley at marconi.com Wed Sep 24 10:28:25 2003 From: nick.keighley at marconi.com (Nick Keighley) Date: 24 Sep 2003 07:28:25 -0700 Subject: Python <-> C via sockets References: <8ad2cfb3.0309240113.19d9198a@posting.google.com> Message-ID: <8ad2cfb3.0309240628.dbbca33@posting.google.com> Eric Brunel wrote in message news:... > Nick Keighley wrote: > > I'm probably missing something rather obvious, but is there a known > > problem with getting a Python based socket program to communicate with > > a C based socket program? A simple echo server written in Python > > (the example from Python in a Nutshell actually) will happily talk > > to a Python based client. If a C based client is substitued the connection > > is refused (or so the C client reports). The C client will talk to > > a C server. > > Communications between C and Python via sockets definetly work: we do that > every day (no kidding ;-) > > Can you post an example of your code? by the time you read this the posted code may have appeared. A call to htons() (convert unsigned short to network byte order) was ommitted on the C side. this line:- sin.sin_port = PORT; should read:- sin.sin_port = htons(PORT); thanks! -- Nick Keighley From andrew-pythonlist at puzzling.org Mon Sep 15 05:57:20 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Mon, 15 Sep 2003 19:57:20 +1000 Subject: Could somebody please explain what is happening .... In-Reply-To: <3f657f95$0$10968$fa0fcedb@lovejoy.zen.co.uk> References: <3f657f95$0$10968$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <20030915095720.GB2226@frobozz> On Mon, Sep 15, 2003 at 08:59:42AM +0000, John Dean wrote: > Hi > > I have been reading quite a lot of Python source code recently and I have > come across a particular construct which I don't understand. I would be > grateful if somebody could explain the reason for including the following > lines of code. I have seen it only at the beginning of a module:- > > global sys > import sys > > global os > import os > > .... > .... > > I know what global means and I know what import means but what is the reason > for making an imported module global? The 'global' statement is useless in the global scope (it only does something useful inside functions), so I'm guessing that whoever wrote that code didn't understand Python's 'global' statements. -Andrew. From cliechti at gmx.net Wed Sep 24 16:41:47 2003 From: cliechti at gmx.net (Chris Liechti) Date: 24 Sep 2003 22:41:47 +0200 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: <3F71B857.2D1E3268@engcorp.com> Message-ID: Peter Hansen wrote in news:3F71B857.2D1E3268 at engcorp.com: > Anthony Baxter wrote: >> >> On behalf of the Python development team and the Python community, >> I'm happy to announce the release of Python 2.3.1 (final). > > The highlights mention the existence of a new API > PyThreadState_SetAsyncEnc, which is "deliberately accessible only from > C", that can interrupt a thread by sending it an exception. > > I can't find an online discussion of this, so I'm asking here. Why > was this made accessible only from C? Is it dangerous? Experimental? > Someone feels it will be used inappropriately if too readily > available at the Python level? martellibot has something about it: http://www.strakt.com/docs/os03_threads_interrupt.pdf > Presumably somebody will come up with a little extension module or > other technique for calling this which will let anyone use it at will, > so I'm unclear on why it should be made inaccessible from Python. why bother with c, just use ctypes to call the function ;-) chris -- Chris From danbmil99 at yahoo.com Mon Sep 8 13:11:26 2003 From: danbmil99 at yahoo.com (dan) Date: 8 Sep 2003 10:11:26 -0700 Subject: negative indices for sequence types References: Message-ID: As is often the case, I think this comes down to documentation. While the behavior is mentioned early in the tutorial, I found it difficult to find it in the reference -- but whatever, we can chalk this up to RTFM on my part. My explanation of the behavior is correct however. list[a] always equals list[a % len(list)]. A negative number mod N = its absolute value subtracted from N: a % n == n - abs(a) # where -n <= a <= 0 However if I want to count from the end of the list, I would of course write list[len(list)-a]. I wasn't really considering that the purpose of this feature was to count from the end of a list, which I admit could come in handy. Thanks for the responses. Fernando Perez wrote in message news:... > dan wrote: > > > I was recently surprised, and quite shocked in fact, to find that > > Python treats negative indices into sequence types as if they were > > mod(length-of-sequence), at least up to -len(seq). > > > > This fact is *deeply* buried in the docs, and is not at all intuitive. > > Very deeply indeed: section 3.1.4 of the beginner's tutorial: > > http://www.python.org/doc/current/tut/node5.html#SECTION005140000000000000000 > > Of all places, this is the section on lists: > > >>> a = ['spam', 'eggs', 100, 1234] > > [... snip ...] > > >>> a[-2] > 100 > >>> a[1:-1] > ['eggs', 100] > > > Can anyone explain why this anomaly exists, and why it should continue > > to exist? > > Because this 'anomaly' is incredibly useful in many contexts, as many others > have already pointed out. Rest assured that it will continue to exist, > probably for as long as the language is around. Better get to like it :) > > Cheers, > > f. From eniac at sdf-eu.org Sat Sep 27 21:17:53 2003 From: eniac at sdf-eu.org (Geiregat Jonas) Date: Sun, 28 Sep 2003 01:17:53 +0000 Subject: Tutor In-Reply-To: <6kqdb.146$Vb3.97520@news1.news.adelphia.net> References: <6kqdb.146$Vb3.97520@news1.news.adelphia.net> Message-ID: <3f763600$0$24183$ba620e4c@reader0.news.skynet.be> After reading How to Think Like a Computer Scientist: Learning with Python, I suggest you start reading www.diveintopython.org or buy Python 2nd edition from O'reilly's, the books VERY good. It teaches you almost everything from handeling strings to network connectivety. It even handels python's standard GUI toolkit TK. From peter at engcorp.com Tue Sep 2 14:07:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 02 Sep 2003 14:07:25 -0400 Subject: win32com problems with Visible property References: Message-ID: <3F54DC5D.62B1C7C0@engcorp.com> Rebecca Taylor wrote: > > I have been working with win32com on python for 2 years now. I > recently tried to modify an older script I had made which creates and > excel workbook, fills it with data and then graphs the data. > > Nothing is working! > When I try to run it I get this error: > > "Property '%s.%s' can not be set." % (self._username_, attr) > AttributeError: Property 'Excel.Application.visible' can not be set." > > Does anyone know why this is happening? I can't figure out if windows > has changed or if win32all or the new python distribution is the > problem. Worse yet, I reinstalled my old versions of python and > win32all and that isn't working either! I'm not sure what the problem is, but cutting and pasting the *actual* traceback instead of retyping might help us find it, or at least would help us trust everything you're saying. Not having 100% confidence in a problem report (as in this case) tends to make one investigate less intensely, I've found... -Peter From FBatista at uniFON.com.ar Mon Sep 8 10:50:39 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 8 Sep 2003 11:50:39 -0300 Subject: FAQs in spanish Message-ID: Hi! I searched for FAQs in spanish, and I didn?t found them. Can you please tell me if there is anyone? Because I can translate them but don?t wan?t to duplicate efforts... Thanks. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at wanadoo.fr Sat Sep 27 16:39:04 2003 From: nobody at wanadoo.fr (Phil) Date: Sat, 27 Sep 2003 22:39:04 +0200 Subject: Module using Numeric array: strange behaviour Message-ID: Hi, I don't understand this strange behaviour: I compile this code : #include #include"Numeric/arrayobject.h" static PyObject * return_vector(PyObject *self, PyObject *args) { PyObject *input1; PyArrayObject *vector; if (!PyArg_ParseTuple(args, "O", &input1)) return NULL; vector = (PyArrayObject *)PyArray_ContiguousFromObject(input1, PyArray_DOUBLE, 1, 1); if (vector == NULL) return NULL; return PyArray_Return(vector); } /* registration table */ static struct PyMethodDef testMethods[] = { {"return_vector", return_vector, 1}, /* method name, C func ptr, always-tuple */ {NULL, NULL} /* end of table marker */ }; /* module initializer */ void inittest() /* called on first import */ { /* name matters if loaded dynamically */ (void) Py_InitModule("test",testMethods); /* mod name, table ptr */ import_array(); /* indispensable pour utiliser les arrays */ } Very simple: this module takes a Numeric array (vector) as argument and send this array back to python... If I compile it under macOSX, the result in python is: >>> import test >>> from Numeric import * >>> v=array([1.0,2.0,3.0,4.0],Float) >>> v array([ 1., 2., 3., 4.]) >>> test.return_vector(v) array([ 1., 2., 3., 4.]) but in linux the result is: >>> import test >>> from Numeric import * >>> v=array([1.0,2.0,3.0,4.0],Float) >>> v array([ 1., 2., 3., 4.]) >>> test.return_vector(v) array([ 1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j]) Strange !!! the result is a complex array. The C vector is really complex because if I try to use it in the C module, the result is...incomplete. For example, if I try to multiply each item of the vector array by a scalar ( pi for example) in a loop, I get this result in python: >>> import test >>> from Numeric import * >>> v=array([1.0,2.0,3.0,4.0],Float) >>> v array([ 1., 2., 3., 4.]) >>> test.return_vector(v) array([ 3.14159265+0.j, 0.+0.j, 6.28318531+0.j, 0.+0.j]) It's the result of pi* 1.0, 0.0, 2.0, 0.0 ( the four first elements of the internal representation of the complex array ([ 1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j]). Anyone any idea where I'm going wrong? Thank you for any help. Philippe From richie at entrian.com Thu Sep 18 11:56:48 2003 From: richie at entrian.com (Richie Hindle) Date: Thu, 18 Sep 2003 16:56:48 +0100 Subject: How to inheritance overwrite non virtual? In-Reply-To: References: Message-ID: [Axel] > The mother-class is calling the method of the child-class, not > it own method. I want the mother-method to be called like "the > chield never was existing", but I find no way. class A: def bwahHaHa(self): """When called by callMe(), derived classes don't get a look in.""" print "Bwah-Ha-Ha!" def callMe(self): """Calls non-overridable method bwahHaHa().""" A.bwahHaHa(self) ########## This is the interesting bit ########## class B(A): def bwahHaHa(self): """Vain attempt to override what callMe() does.""" print "Squeak" b = B() b.callMe() # Prints "Bwah-Ha-Ha!" b.bwahHaHa() # Prints "Squeak" -- Richie Hindle richie at entrian.com From mark.wondratschek at sap.com Mon Sep 1 07:28:25 2003 From: mark.wondratschek at sap.com (Mark Wondratschek) Date: Mon, 1 Sep 2003 13:28:25 +0200 Subject: Python zipfile: Zip empty directories. References: Message-ID: ThanX a lot Peter! "Peter Otten" <__peter__ at web.de> wrote in message news:biqg9h$9g8$01$1 at news.t-online.com... > Mark Wondratschek wrote: > > > but this must be supported by the zip format > > ('cause winzip etc. does it this way). The empty-file idea was one of my > > reflections, too. But I'm sure there must be better ways... > > See what I've found (did not test it myself) googling for > zip empty directory: > > http://mail.python.org/pipermail/python-list/2003-June/170517.html > > Peter From user at invalid.domain Mon Sep 15 05:58:48 2003 From: user at invalid.domain (Invalid User) Date: Mon, 15 Sep 2003 11:58:48 +0200 Subject: configuration files and 'distutils' Message-ID: How can I specify where the configuration files specfied in the 'data_files' section should go? For example, if I have: data_files=[('config', ['connection.cfg'])] How can I have a configuration file placed anywhere else beside the default '/usr/config' directory? From aleax at aleax.it Tue Sep 30 04:36:08 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 30 Sep 2003 08:36:08 GMT Subject: overriding built-ins References: Message-ID: dan wrote: > Thanks for the responses, and my apologies for getting the terminology > confused. What I really should have asked is this: > > * Is there any way to create your own statements? > and, > * if so, can they override the names of built-in statements such as > 'print'? > > To which the answers seem to be, no, and definitely not (with a strong Right. > hint of "why would you ever want to do that"?) Actually, I suspect it's pretty obvious to most respondents why one might want to create their own language, embedded inside Python but enriched and modified. Guido himself is on record as having the far _dream_ of one day managing to let people define "application-specific languages" inside Python -- IF he can come up with a smart way to do it, one that won't destroy Python's simplicity and utter straightforwardness. I suspect that "strong hint" reflects a deep distrust that any such silver bullet exists, and a deep fear that in the pursuit of such elusive goals Python's simplicity and philosophy of "there should be only one way to do it" might be destroyed. There exist languages which have very powerful macro systems. Common Lisp is the canonical example, but if you prefer syntax that is rather more Python-like you might look into Dylan instead. Lisp and Dylan also share the powerful concept of "multiple dispatch", a way to do OO that is as superior to C++'s or Python's as the latter is superior to that of _purely_ single-inheritance languages [ones without even such helpers as Java interfaces or Ruby mixins]. Some languages do not really have such power, but can still come close -- e.g., in Smalltalk, "IF" is not a _statement_, just a method to which you pass code blocks, so there is little impediment to piling up "more of the same" to make your own application-specific language inside it; to a lesser extent, you can do somewhat similar things in Ruby -- and Perl has its own inimitable way (google for "Lingua Latina Perligata" if you're REALLY TRULY into such... ahem... divertissements:-). A widespread feeling around the Python community is that Python's own uniqueness is SIMPLICITY. Python is straightforward and thereby most productive because it DOESN'T EVEN TRY to let you bend its syntax in strange ways (in that, it's closest to Java -- i.e., it even lacks the puny "preprocessor" that C and C++ come with). If you want an application-specific language, you design and implement it in the good old time-trusted way -- lexx and yacc, or their Python equivalents (of which there are quite a few) -- Python stays Python, your language is your own, and everybody (hopefully) is happy...;-). Alex From rebel at removethis.rebel.com.au Tue Sep 9 23:40:42 2003 From: rebel at removethis.rebel.com.au (Chris) Date: Wed, 10 Sep 2003 03:40:42 GMT Subject: Embedded Perl or Python (XPost) References: Message-ID: Chris wrote in news:c907a3eba2b531449c8dc7a212285911 at news.teranews.com: > Hi > > I am posting this on both the perl and python groups SNIP > > QUESTION > > Given the above which interpreter is most likely to fit my bill with > the smallest footprint ? > > Thanks in advance > Chris Ok Guys thanks for the input I have decided to try and take the best of both worlds (why not) Size restrictions permitting I will include both a PERL interpreter and a Python Interpreter at least as a users choice That way I get all you wonderful developers creating fab scripts to extend my software :-) Chris From ajsiegel at optonline.net Thu Sep 11 09:47:56 2003 From: ajsiegel at optonline.net (Arthur) Date: Thu, 11 Sep 2003 09:47:56 -0400 Subject: OT: Americans love their guns Message-ID: <000501c3786b$4e861630$0c02a8c0@Arts> >I think it's a mistake to cite Lott here. As an >extreme libertarian he >has shown his own bias a couple of times. His >famous "More guns, less >crime" findings has been challenged recently >>(see e.g. >http://www.jointogether.org/gv/news/alerts/reader/0,2061,562387,00.html), >and he could not produce any evidence whatsoever that his telephone >survey on the crime-repelling effects of gun carrying has been actually >conducted. I have never owned a gun, nor can off-hand think of anyone I know well who does own a gun. So am not excitable on the issue. But I do find that the repeated use of statistics in this thread is quite the problem, not quite the solution. Those claiming a right to gun ownership are specifically claiming the irrelevancy of such analysis. That is exactly, in many ways, the point - it seems to me. Statistically, they have exactly one family. And statistically have the right - in their to view - to do exactly what they statistically decide is necessary to protect that statistic. To in fact specifically not be a statistic. Yes, there is something quite American about that viewpoint. God bless. Art From lp at your-pants-coder.dk Mon Sep 1 05:35:54 2003 From: lp at your-pants-coder.dk (Larz) Date: 01 Sep 2003 09:35:54 GMT Subject: Python Documentation? References: <3f530ea6$0$32489$edfadb0f@dread16.news.tele.dk> Message-ID: > The documentation takes contributions on example snippets, > description, etc. so when the site is completely done and a base of > documentation have been posted, im gonna post link in here, then maybe > the community will help us to create a great documentation source :) Hi all, I'm the friend that Dan is talking about ;) Just wanted to clarify our project a little bit. Dan and I are long time php programmers. One thing that is superb about php, is it's online documentation that everyone in the community can contribute to (not the actual documentation, just comments with examples). Every since I first started using python, I've truly missed a documentation source similar to that of PHP's. So Dan and I have started our little project to make a documentation site in the spirit of that documentation. So far it looks great, and you can see some python documentation by using URLs like http://example.com/doc/string.split and there will of course be a search function. Also, it will not only be the "standard" modules of Python, by suggestion (and perhaps permission), we will include third party modules, such as MySQLdb and the like. As Dan writes, it will be ready very soon, within a few weeks. It will of course be devoid of user comments in the beginning, but we're hoping that users will contribute with some of their invaluable experience! Best regards, Lars Petersen -- larz to mail me, remove your pants! From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Thu Sep 11 07:15:09 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Thu, 11 Sep 2003 12:15:09 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <3F5F83B1.48763F85@alcyone.com> <3F5FD6D7.119F04A1@alcyone.com> Message-ID: <4ql0mv0965j34bv92ug1fviajfir4lg2qe@4ax.com> On Wed, 10 Sep 2003 18:58:47 -0700, Erik Max Francis wrote: >Stephen Horne wrote: > >> I don't agree with this. >> >> If the caller has to specify the behaviour in the syntax they use for >> the call AS WELL AS the definition (in both cases using the 'ref' >> modifiers) then the call mechanism is 100% explicit and predictable. >> If, given Pythons dynamism, you have an function object of the wrong >> type (and therefore one which does not support the call mechanism you >> are trying to use) then it will fail - just as attempting to do a >> conventional function call on a non-function will fail. > >That isn't what I meant. Look at the following code: > > someFunction(thisArgument, thatArgument) > >With Python as it stands right now, I know that this call can never >rebind the names thisArgument and thatArgument. It doesn't matter what >someFunction is, it doesn't matter what thisArgument or thatArgument >are. I know it can never happen. > >With your proposed change, now whenever I see a function call in code I >don't know whether it's going to rebind names from the caller's side. >It might, it might not. Furthermore, with Python's dynamicism, it might >be hard to tell without running the code (since functions are first >class objects, inspecting the function name may not help). Wrong. That statement will behave exactly as it always did, and CANNOT rebind thisArgument or thatArgument even if my suggestion were implemented. The CALLER has to EXPLICITLY allow the rebinding by using the ref flags IN ADDITION TO specifying it in the function definition, as is done in C# - that was the whole point. With this call, the first argument may be rebound but not the second (assuming the function was written to accept the arguments specified that way). someFunction(ref thisArgument, thatArgument) ^ | Note this explicit modifier in the call However, I am still retracting the suggestion for reasons I have already covered. From anthony at interlink.com.au Tue Sep 2 00:51:42 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Tue, 02 Sep 2003 14:51:42 +1000 Subject: homebrew 2.3 install on RedHat9 not playing nice with Tkinter In-Reply-To: <200309010953.32852.mfranklin1@gatwick.westerngeco.slb.com> Message-ID: <200309020451.h824pgv9031012@localhost.localdomain> >>> Martin Franklin wrote > Red Hat Linux: Red Hat 9 built Python2.2 in UCS-4 mode and hacked > Tcl to support it. To compile Python2.3 with Tkinter, you will > need to pass --enable-unicode=ucs4 flag to ./configure. > > Which I did and now _tkinter.so is building of the box > so in answer to OP read the README;-) Note that this will "work", but the resulting tk applications will leak memory like a sieve. -- Anthony Baxter It's never too late to have a happy childhood. From buzzard at urubu.freeserve.co.uk Mon Sep 1 10:06:32 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 1 Sep 2003 15:06:32 +0100 Subject: artificial intelligence References: Message-ID: "Arthur" wrote in message news:mailman.1062394443.2068.python-list at python.org... > >Maybe there was some notice about using Python in > >geophysic and the symposium book in one journal, so there was a sudden > >spat of, say, three people who bought both. > > You would think the parameter for a statistically significant sample size > would be a fundamental concept in this kind of thing. And no action taken > before one was determined to exist. > Statistical tests take sample sizes into account (so e.g. a larger effect will tend to be statistically significant for a smaller sample size). Sample size calcs. are more useful when you're in a position to determine how large the sample will be. > OTOH, the concept of "coincidence" must necessarily be ruled out in AI, I > would think. > Coincidence can't generally be ruled out, but you can look for relationships in the (sample) data that would be unlikely to be present if the same relationships weren't also present in the population. > *Our* intelligence seems to give us a read as to where on the bell curve a > particular event may lie, or a least some sense of when we are at an extreme > on the curve. Which we call coincidence. AI would probably have a > particularly difficult time with this concept - it seems to me. > Some people have a difficult time with (or are unaware of) "statistical thinking". Maybe some of them are involved in AI? (Well, of course some of them are. :-)) > Spam filtering software must need to tackle these kinds of issues. > It can do, and I've no doubt some of it does. Spam filtering is a classification problem and can be handled in a variety of ways. It's generally easy to come up with an overly complex set of rules / model that will correctly classify sample data. But (as you know) the idea's to come up with a set of rules / model that will correctly (as far as possible) classify future data. As many spam filters use Bayesian methods, I would guess that they might be fitted using Bayesian methods; in which case overly complex models can be (at least partially) avoided through the choice of prior, rather than significance testing. What do Amazon use? My guess (unless it's something really naive) would be association rules. Duncan > Art > > From godoy at metalab.unc.edu Mon Sep 29 22:31:50 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Mon, 29 Sep 2003 23:31:50 -0300 Subject: Threading and Windows. References: Message-ID: Dennis Lee Bieber writes: > Forgive me if this has some obvious facet that I'm missing -- I'm not > experienced in os.spawnv* family. Neither am I. In fact, this program was my first use of it. > However, the documentation I have for os.spawnv() suggests > that this call alone will create a separate/new process. And you are > calling it with a no-wait argument... So why do you even need the > threading overhead? This isn't the behaviour I found here on a Linux box. The caller process got 'stuck' and only worked again when the called proccess ended. With threads I got it working all the time. > Hmmm, if "another.py" is the target, you may be encountering the > possibility that Windows doesn't know how to start a .py file from the > command line. Windows (especially the W9x line) doesn't, to my > knowledge, honor #! lines in script files. Using the thread module I could get it to work on Windows and then, yes. I got this problem. :-) Sorry for my lameness on Windows but this isn't my platform of choice. I'll add some conditional and check the platform... On the other hand, isn't there a way to associate programs with extensions on Windows? Wouldn't this solve the problem with the call I made? Or it only works in certain circunstances and (by Murphy's law) this is not one of those circunstances? Thanks for your help, -- Godoy. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 05:09:53 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 10:09:53 +0100 Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: On Fri, 26 Sep 2003 02:03:10 GMT, "Andrew Dalke" wrote: >Stephen Ferg: >> At one time, it was accepted as a truism that Windows (like MS-DOS) >> was different from Unix because Windows used the backslash as the path >> separator character, whereas Unix used the forward slash. > >It was? My copy of Norton's Guide to the IBM PC makes >the explicit statement that directories were directly influenced by >unix. I actually regard this as a point of similarity. The character >used is a minor issue. Directly influenced, yes - but as DOS 1 didn't have subdirectories but did have options marked with '/', the unix subdirectories couldn't be duplicated exactly in DOS 2. The character used *is* a minor issue, but it is still a difference - what Stephen Ferg wrote is, I believe, valid. Even if DOS was internally happy to accept '/' as a path separator, still the 'accepted as a truism' bit rings true to me - what is accepted as an obvious truth is not always actually true, and to most people users DOS was the command line and Windows was just a shell on top of DOS - the 'truism' was what people could see, not what was hidden away in the INT 21h calls that only programmers cared about. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From bgailer at alum.rpi.edu Wed Sep 3 10:33:59 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 03 Sep 2003 08:33:59 -0600 Subject: win32com problems with Visible property In-Reply-To: References: Message-ID: <5.2.1.1.0.20030903082835.01d6b178@66.28.54.253> At 04:07 PM 9/2/2003 -0400, David Rushby wrote: >"Rebecca Taylor" wrote in message >news:f431a335.0309020839.486b6f92 at posting.google.com... > > I have been working with win32com on python for 2 years now. I > > recently tried to modify an older script I had made which creates and > > excel workbook, fills it with data and then graphs the data. > > > > Nothing is working! > > When I try to run it I get this error: > > > > "Property '%s.%s' can not be set." % (self._username_, attr) > > AttributeError: Property 'Excel.Application.visible' can not be set." > > > > Does anyone know why this is happening? I can't figure out if windows > > has changed or if win32all or the new python distribution is the > > problem. Worse yet, I reinstalled my old versions of python and > > win32all and that isn't working either! > >The property is named 'Visible', not 'visible'. > >When makepy is run, COM identifiers become case-sensitive. Perhaps your old >installation of win32com hadn't been makepy-ified, but the new one has? I don't think this is the problem. If it were the OP would get an attribute error. "...object has no attribute 'visible'" Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From aaron at brokensociety.com Mon Sep 1 03:05:00 2003 From: aaron at brokensociety.com (Aaron Kunkle) Date: Mon, 01 Sep 2003 00:05:00 -0700 Subject: os.popen to pyqt widget Message-ID: <1062399899.4475.29.camel@aaron> I'm trying to pipe the output of a shell command (with os.popen) to a QTextEdit to show the output in real time. Can some one help me with this? I'm guessing I need some kind of buffer to check on the output every so often but I'm new to python so I don't know a good way of doing that. I can send or post my source code so far if anyone would like to see it. Thanks, Aaron -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike at DeleteThis.Geary.com Mon Sep 15 21:03:58 2003 From: Mike at DeleteThis.Geary.com (Michael Geary) Date: Mon, 15 Sep 2003 18:03:58 -0700 Subject: object.attribute vs. object.getAttribute() References: Message-ID: I've always disliked accessor methods in C++ and Java. I can understand the reason for using them, but they are just so ugly. Danger: Advice from a Python newbie follows... :-) My suggestion would be to use Python properties, as defined with the property() function that was added in 2.2. Best of both worlds: You get the clean syntax of directly reading and writing properties just as if they were attributes, but behind the scenes you've defined get/set/del functions for each property. Personally, I wouldn't define properties for everything--I would use ordinary attributes wherever they do the job. The beauty is that you can always replace an attribute with a property without having to change the calling code--which eliminates most of the reason for using accessor methods as you would in C++. -Mike Roy Smith wrote: > For the past 6-8 months, I've spent most of my time writing C++ and a > little bit of Java. Both of these languages support and encourage the > use of private data and explicit accessor functions, i.e. instead of > writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to > writing Python, I find myself in a quandry. > > Historically, I've always avoided accessor functions and just reached > directly into objects to get the value of their attributes. Since > Python doesn't have private data, there really isn't much advantage to > writing accessors, but somehow I'm now finding that it just feels wrong > not to. I'm not sure if this feeling is just a C++/Java-ism that will > cure itself with time, or if perhaps it really does make sense and I > should change the way I code. > > On the plus side, accessors/mutators give me: > > 1) Implicit documentation of which attributes I intended to be part of > an object's externally visible state (accessors). > 2) Hooks to do data checking or invarient assertions (mutators). > 3) Decoupling classes by hiding the details of data structures. > 4) Vague feeling that I'm doing a good thing by being more in line with > mainstream OO practices :-) > > On the minus side: > > 1) More typing (which implies more reading, which I think reduces the > readability of the finished product). > 2) Need to write (and test) all those silly little functions. > 3) Performance hit due to function call overhead. > 4) Only the appearance of private data (modulo some slots hackery). > 5) Code is harder to change (adding functionality means going back and > adding more slots). > 6) Vague feeling that I'm dirtying myself by letting C++ and Java change > my Python coding habits :-) > > Comments? From mwh at python.net Mon Sep 22 10:46:58 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 22 Sep 2003 14:46:58 GMT Subject: was: Re: looking for MOP documentation References: <3F66F516.3D06D946@engcorp.com> <3F69AD0F.53D51719@engcorp.com> <3F69D215.5649AF66@hotmail.com> <3F69DFEB.5B05CED8@engcorp.com> <7h37k45j895.fsf@pc150.maths.bris.ac.uk> <3F6B2AB1.2D839EF5@engcorp.com> <7h3d6dt9e8i.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h3smmo996u.fsf@pc150.maths.bris.ac.uk> Holger Krekel writes: > Michael Hudson wrote: > > Holger Krekel writes: > > > > > Although probably 2/3 of the implementation of Python deal with the > > > type/object implementations, from a using-the-language point of view > > > the syntax probably contributes more obviously to the observed > > > "simplicity" of Python. > > > > OK, I disagree with you, too :-) > > Nah, that's almost impossible because I have carefully interspersed > the above sentence with "probably" and "more obviously" :-) OK, you're right in what you say -- the syntax probably does make more of an obvious impact. I'll carry on believing that the powerful data structures are more important, but that hardly contradicts your paragraph. > > > But the term "meta object protocol" seems to point much more into > > > the direction of types/objects as Michael suggests and here Python > > > has a lot to offer. Is there some free material on MOP somewhere? > > > > http://www.elwoodcorp.com/alu/mop/contents.html > > Uuh, it's all LISP based, i see. Well, CLOS (== Common Lisp Object System). Difficulties in understanding are likely to come as much from not grokking CLOS as not grokking Lisp. > Maybe i still give it a try. Anyone willing to give a pythonic > crash-course in LISP in - say - 10 x 5-line paragraphs? :-) Not right now, sorry... > > looks like being a version of AMOP online, you know that book I > > brought with me to one of the pypy sprints :-) (actually, it may have > > been the Gothenbourg sprint). I can bring it to the next sprint I > > come to, if you like. > > sounds good and like more fun than funding papers. Actually, the URL isn't the text of the book, but is similar material... Cheers, mwh -- This system uses a highly redundant optical communication technique to achieve ultra-low, ultra-robust transmission. The basic unit is the M1A1 tank. -- RFC 1217, Memo from the Consortium for Slow Commotion Research From mjackson at alumni.caltech.edu Thu Sep 25 09:52:04 2003 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 25 Sep 2003 13:52:04 GMT Subject: "for" with "else"? References: Message-ID: Invalid User writes: > Is this to be expected? > (python 2.2.2) > > ++++++++++++++++++++++++++++++= > >>> for x in range(5): > .... print x*x > .... else: > .... print "done" > .... > 0 > 1 > 4 > 9 > 16 > done > ++++++++++++++++++++++++++++++= Yes. The else clause is invoked iff the for loop terminates normally. Contrast with: ++++++++++++++++++++++++++++++ >>> for x in range(5): ... print x*x ... if x==4: ... break ... else: ... print "did all" ... 0 1 4 9 16 >>> ++++++++++++++++++++++++++++++ (This happens to be the *reverse* of what my intuition expects - it would seem more natural if the syntax meant "do this for loop to completion, else do this extra stuff," but this is the way it is and one must simply remember it.) -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson There are no foolish questions and no man becomes a fool until he has stopped asking questions. - Charles P. Steinmetz From rhunter007 at yahoo.com Sun Sep 14 17:43:40 2003 From: rhunter007 at yahoo.com (Rob Hunter) Date: Sun, 14 Sep 2003 14:43:40 -0700 (PDT) Subject: Is there "let binding" in Python? Message-ID: <20030914214340.13608.qmail@web40904.mail.yahoo.com> Is there an equivalent to Scheme's LET in Python? LET creates a new binding in the current environment. For example, here's some Scheme code: (let ((x 3)) (let ((f (lambda (arg) (* arg x)))) (let ((x 4)) (f 5)))) So, this program, which also tests that Scheme has correct scoping, returns 15. And in Python, I can write an equivalent program that does correctly return 15, but I have to use what, in Scheme, we call "left-left lambda"--a way of simulating LET. Or rather, LET is syntactic sugar for left-left lambda. As a simpler example, if I want to write: (let ((x 3)) (+ x 4)) I can write ((lambda (x) (+ x 4)) 3) in Scheme or, (lambda x: x+4)(3) in Python. I want to know if there's a less syntactically cumbersome way of getting LET in python. Thanks! PS: I'm a newbie, so the answer in fact might be super-easy. __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From posman at eval.ca Mon Sep 15 10:16:17 2003 From: posman at eval.ca (Paul Osman) Date: Mon, 15 Sep 2003 10:16:17 -0400 (EDT) Subject: list of lists In-Reply-To: References: Message-ID: On Mon, 15 Sep 2003, Tom wrote: > Hi, > > I have a list that consists of lists. > E.g. T=[[1, 2, 3], [4, 5], [6]] > Is there a way to address the a specific component in the "inner" list > directly? > E.g. right now I want to get the second value of the first list. > Unfortunately I have to save it to a variable first and then read it. > a = T[0] > print a[1] > > That kind of sucks, becaus I have to read a lot of values from a lot of > lists! :-( > Is there a faster way than my saving it to a "help variable" first? > > Thanks folks!! > > Regards, Tom > > Hi Tom, Do you mean this? >>> T=[[1, 2, 3], [4, 5], [6]] >>> T[0][1] 2 >>> print T[0][1] 2 >>> print T[1][1] 5 HTH, -- Paul Osman paul at eval.ca http://perl.eval.ca "Idealists...foolish enough to throw caution to the winds...have advanced mankind and have enriched the world." - Emma Goldman From jepler at unpythonic.net Tue Sep 2 11:04:25 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 2 Sep 2003 10:04:25 -0500 Subject: **kwds behavior? In-Reply-To: <924a9f9c.0309020652.212c54eb@posting.google.com> References: <924a9f9c.0309020652.212c54eb@posting.google.com> Message-ID: <20030902150424.GB17554@unpythonic.net> Changes to locals() do not necessarily affect anything. locals() Update and return a dictionary representing the current local symbol table. *Warning*: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. -- http://python.org/doc/current/lib/built-in-funcs.html#l2h-47 You should probably try a different approach to whatever the underlying task is. Jeff From tjreedy at udel.edu Tue Sep 23 22:01:40 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2003 22:01:40 -0400 Subject: Pre-PEP: reverse iteration methods References: Message-ID: "Raymond Hettinger" wrote in message news:HA5cb.185$kD3.168 at nwrdny03.gnilink.net... > for i in xrange(n).iter_backwards(): > print seqn[i] > > for elem in seqn.iter_backwards(): > print elem I would prefer a much shorter name, such as riter for reverse/right iter. This goes along with current nomenclature such as rfind, etc. Terry J. Reedy From aaron at reportlab.com Wed Sep 3 12:13:33 2003 From: aaron at reportlab.com (Aaron Watters) Date: 3 Sep 2003 09:13:33 -0700 Subject: gadfly and SQL-LIKE References: Message-ID: <9a6d7d9d.0309030813.6f6d2363@posting.google.com> "Patrick W. Fraley" wrote in message news:... > Hi Everybuddy, > > I am having a little problem I can not find a solution for. > > I am trying to use the SQL-LIKE statement in gadfly. After googling > around I found out that it is not supported, and that on is supposed to > use a regular expression. All great, but there is nowhere a reference > to be found on how to do this. No examples, no nothing, just the > comment to use regular expressions. > As it currently stands what you need to do is evaluate the query using gadfly, pull the query out into "normal" python, and then use a python loop and string operations (such as regular expressions) to choose the results you want (and throw out the others). This will work for analogues of simple positive queries such as select a,b from t where c like '%this%' but may not for fancy queries involving "not in" and so forth -- which would require a proper implementation of "like" in gadfly. Sorry. Probably the "right" way to fix this is to allow the importation of an arbitrary function into gadfly from python, which wouldn't be too hard but isn't trivial. -- Aaron Watters ps: my copy of MSAccess doesn't support "like" properly either, fwiw... === to do is to be -- Sartre to be is to do -- Marx do be do be do -- Sinatra From phil at riverbankcomputing.co.uk Tue Sep 16 18:09:24 2003 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Tue, 16 Sep 2003 23:09:24 +0100 Subject: App development for Sharp Zaurus PDA using QTopia? In-Reply-To: <3f6751fc$0$162$a1866201@newsreader.visi.com> References: <3f6751fc$0$162$a1866201@newsreader.visi.com> Message-ID: <200309162309.24010.phil@riverbankcomputing.co.uk> On Tuesday 16 September 2003 7:10 pm, Grant Edwards wrote: > I see there's a Python binary package available for the Sharp > Zaurus PDA. Has anybody deleloped an app for that platform? > I'm wondering if the resource requirement of Python are a > problem on that platform. http://www.riverbankcomputing.co.uk/zaurus/download.php Phil From tim at remove_if_not_spam.digitig.co.uk Mon Sep 29 06:00:56 2003 From: tim at remove_if_not_spam.digitig.co.uk (Tim Rowe) Date: Mon, 29 Sep 2003 11:00:56 +0100 Subject: Recursion References: Message-ID: On Mon, 29 Sep 2003 06:06:37 GMT, Dennis Lee Bieber wrote: > Each time Factorial makes a recursive call to itself (I know, that is >redundant phrasing) it creates a new "block" of local variables, the >variables in the previous block can not be seen. When a return >statement is encountered, the block of locals is deleted, leaving the >return value visible to the calling block. I can't remember if the tutorial points it out, but for jakle's sake I should mention that this means that the recursive implementation of factorial uses a lot more memory than a simple loop implementation (and is probably a lot slower too). Factorials are useful for teaching recursion, but it's not usually the best way to implement a factorial function [1]. There are some applications that are not so easy to implement as a loop, though (traversing a tree structure is usually one of the first that nascent programmers encounter) and then recursion starts being actually useful. [1] Some languages depend on recursion much more than Python does, but they will typically spot cases that can be converted to simple loops and do that behind the scenes for efficiency. From richie at entrian.com Fri Sep 19 12:35:15 2003 From: richie at entrian.com (Richie Hindle) Date: Fri, 19 Sep 2003 17:35:15 +0100 Subject: file position *tell()* works different In-Reply-To: References: <13a533e8.0309190137.2df0cc60@posting.google.com> Message-ID: [Peter] > I wonder if the function *tell()* is not correctly implemented under win32. [Tim, quoting the standard] > For a text stream, its file position indicator contains > unspecified information, usable by the fseek function for returning > the file position indicator for the stream to its position at the > time of the ftell call It still doesn't seem to work as specified: ------------------------------ peter.py ------------------------------ # Open the file in text mode, read a line, and store the position. fp = file('test_data.txt', 'rt') line = fp.readline() storedPosition = fp.tell() print 'Line: %r, file pointer after read: %d' % (line, storedPosition) # Read some more and print it. print 'Read another line from this position: %r' % fp.readline() # Now seek back and read the same line again. fp.seek(storedPosition) print 'Another read from the same position: %r' % fp.readline() ---------------------------------------------------------------------- This prints: Line: '0123456789\n', file pointer after read: 8 Read another line from this position: '0123456789\n' Another read from the same position: '89\n' I'd expect doing readline/tell/readline/seek/readline to read the same line the second two times. And however you implement tell and seek, a tell value of 8 after reading 11 bytes looks pretty weird. I'd write the same code in C if I had the time, so at least we could be *sure* we can blame Microsoft. 8-) -- Richie Hindle richie at entrian.com> From colarte at telesat.com.co Fri Sep 26 05:14:34 2003 From: colarte at telesat.com.co (Camilo Olarte) Date: Fri, 26 Sep 2003 04:14:34 -0500 Subject: Q: How to Change Pmw.ComboBox width ?? Message-ID: <20030926041434.4943182a.colarte@telesat.com.co> Hello list, I was trying to make a Pmw.ComboBox and while using it i needed to change its width. I tried to configure it's inner components directly like _listbox.config but nothing changes.. By default in my computer this combobox width is of 12 (characters) and since I am showing number of the month i need only 3 characters. i could use a Pmw.Counter but my boss don't likes it's arrows :( ... Here is some sample code of what i'm doing. import Tkinter, Pmw class DemoCombo: def __init__(self, parent): parent.configure(background = 'white') arrmes = [1,2,3,4,5,6,7,8,9,10,11,12] # Create and pack the dropdown ComboBox. self.dropdown = Pmw.ComboBox(parent,label_text = 'Month:', labelpos = 'n',scrolledlist_items = arrmes, scrolledlist_usehullsize = 1,) # How do I change pmw combobox width ... # self.dropdown.configure(width =2) ...Na didn't change widht # self.dropdown._list.configure(width =2) ...Na didn't change widht # self.dropdown._list._listbox.configure(width =2) ...Na didn't cha nge widht self.dropdown.pack(side = 'top') self.dropdown.selectitem(0) # Display the first element def fnShow(self): print self.dropdown.get() ################################### # Create demo in root window for testing. if __name__ == '__main__': root = Tkinter.Tk() Pmw.initialise(root, fontScheme = 'pmw1') widget = DemoCombo(root) Frm = Tkinter.Frame(root) testBtn = Tkinter.Button(Frm, text = 'Print Month', testBtn.pack(side = 'left') exitBtn = Tkinter.Button(Frm, text = 'Exit', command = root.destroy) exitBtn.pack(side = 'right') Frm.pack() root.mainloop() Camilo Olarte From hildegarde_roth at yahoo.de Tue Sep 16 14:15:28 2003 From: hildegarde_roth at yahoo.de (Hilde Roth) Date: 16 Sep 2003 11:15:28 -0700 Subject: Indexing list of lists Message-ID: <95b4b9ac.0309161015.6a0567a7@posting.google.com> This may have been asked before but I can't find it. If I have a rectangular list of lists, say, l = [[1,10],[2,20],[3,30]], is there a handy syntax for retrieving the ith item of every sublist? I know about [i[0] for i in l] but I was hoping for something more like l[;0]. Hilde From gh at ghaering.de Mon Sep 8 05:54:35 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 08 Sep 2003 11:54:35 +0200 Subject: More Comments on Python Redesign In-Reply-To: <005401c375eb$1ea0b9c0$0a00a8c0@JASPER> References: <005401c375eb$1ea0b9c0$0a00a8c0@JASPER> Message-ID: <3F5C51DB.6070700@ghaering.de> Tim Parkin wrote: > [...] I was merely reacting to some unfounded criticisms of the > design I'd put forward. If I seem to have been a little over the top > then I apologise profusely but as you can imagine the reaction to 8 > weeks of hard work that had been put in by quite a few people. > Comments like the one you have made just make me realise how much > time we've all wasted. If you are this influential then I shall stop > working on the redesign and let someone you like carry on. Thanks for your work on this. I for one *do* like your design prototype. And I'm unpleasantly surprised by the tone of the criticism as well. -- Gerhard From aleax at aleax.it Sun Sep 28 16:44:13 2003 From: aleax at aleax.it (Alex Martelli) Date: Sun, 28 Sep 2003 20:44:13 GMT Subject: overriding built-ins References: Message-ID: dan wrote: > I really have two related questions. > > 1) Is it possible (without recompiling and changing the core Python > behavior) to write functions that utilize the same syntax as built-in > functions? Yes, but don't confuse functions with statements. It seems you are systematically doing just that. > IE, can I create a function that does this: > >>>>printCaps "hello" #note no parentheses > HELLO No. You are thinking of "imitating" print, which is a STATEMENT, *NOT* a built-in function. Examples of built-in functions are input, hex, max. What they have in common, which sharply distinguishes them from statements: they use perfectly normal function syntax, and their names are not in any way reserved. > 2) Is it possible to do this with the built-in keywords themselves, ie > override functions such as print? print is a statement, not a function. No, there is no way to use any Python keyword except as Python uses it. Alex From nskhcarlso at bellsouth.net Mon Sep 1 22:15:51 2003 From: nskhcarlso at bellsouth.net (KC) Date: Mon, 01 Sep 2003 22:15:51 -0400 Subject: htmllib.py and parsing malformed HTML Message-ID: I have written a parser using htmllib.HTMLParser and it functions fine unless the HTML is malformed. For example, is some instances, the provider of the HTML leaves out the tags but includes the tags. Apparently, htmllib and more likely sgmllib do not parse an end tag if a corresponding start tag was not found. Does anyone know a way to "fool" the parser into handling the end tag is a start tag was not found? Thanks, Kevin From max at alcyone.com Tue Sep 23 04:33:07 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 23 Sep 2003 01:33:07 -0700 Subject: compiling python program References: Message-ID: <3F700543.350E2074@alcyone.com> Al wrote: > I'd like to "hide" my code from being viewed (linux). Is there anyway > for me > to compile my program into .pyc and only have the .pyc files > available, or > do I always have to have the .py file? You can just provide the .pyc file to clients. But it will only be runnable by the same version of Python you used to compile it. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ Moral indignation is jealousy with a halo. \__/ H.G. Wells From jjl at pobox.com Fri Sep 12 10:10:52 2003 From: jjl at pobox.com (John J. Lee) Date: 12 Sep 2003 15:10:52 +0100 Subject: why is this failing? References: <9x58b.139$u07.2@newsread1.news.atl.earthlink.net> <3F60E645.2501B9EE@engcorp.com> <3f60ea13$0$42053$a1866201@newsreader.visi.com> <87llsu6hij.fsf@pobox.com> <3F611490.23E27E1B@alcyone.com> Message-ID: <87ad9am70z.fsf@pobox.com> Erik Max Francis writes: > "John J. Lee" wrote: > > > You wouldn't happen to know how to do this for python-mode? > > The latest versions will do it automatically. Just to check (I'm using a patched version, so it's a bit of a pain to switch): the latest versions from the python-mode SF project highlight builtins like "len" and "list", not just keywords like "print"? John From raims at dot.com Sun Sep 7 11:26:23 2003 From: raims at dot.com (Lawrence Oluyede) Date: Sun, 07 Sep 2003 17:26:23 +0200 Subject: Comments on Python Redesign References: Message-ID: <87vfs4mxgg.fsf@voodoo.fake> "James P. Rutledge" writes: > That validator does checks on webpages and reports on the pages > "conformance to W3C Recommendations and other standards." Right, I also suggest you all to use the new version of the validator which is more "human friendly": http://validator.w3.org:8001/ Zeldman's post about the new version: http://zeldman.com/daily/0803a.shtml#validator -- Lawrence "Rhymes" Oluyede http://loluyede.blogspot.com rhymes at NOSPAMmyself.com From newsgroups at jhrothjr.com Tue Sep 9 18:40:11 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 9 Sep 2003 18:40:11 -0400 Subject: How to instatiate a class of which the name is only known at runtime? References: <3F5E3E3E.9C31763F@alcyone.com> Message-ID: "Erik Max Francis" wrote in message news:3F5E3E3E.9C31763F at alcyone.com... > John Roth wrote: > > > As Nick said, you can use the exec statement. You can > > also use the _import() function. > > >>> _import > Traceback (most recent call last): > File "", line 1, in ? > NameError: name '_import' is not defined > > Do you mean __import__? Yes. John Roth > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE > / \ But when I reached the finished line / Young black male > \__/ Ice Cube From tim.one at comcast.net Thu Sep 4 22:58:53 2003 From: tim.one at comcast.net (Tim Peters) Date: Thu, 4 Sep 2003 22:58:53 -0400 Subject: Quickie mail.python.org status In-Reply-To: <16215.13839.220121.550541@montanaro.dyndns.org> Message-ID: [Francois Pinard] > I do not understand why the bad guys would have programmed > such a deadline within their code, but I still wish this > deadline story is true! [Skip] > The speculation I've read is that the author was paid (or is going to > be paid) by spammers. The virus will propagate (and relay spam?) > until the agreed upon deadline. The best stuff I've read suggests Sobig.F was a victim of its success: it contained a list of IP addresses for 20 compromised machines around the world (infected by previous Sobig variants). Infected machines got programmed to download new software from a random one of those boxes a while ago, the speculation being that the new software would establish proxy servers (presumably for use by spammers) on a veritable army of compromised machines. OTOH, maybe it's just some sociopathic teen having fun. Whatever, this final stage was apparently hard to reverse-engineer, but because the worm caused so much damage so fast, a lot of effort got poured into it. As a result, all the machines it was going to contact got pulled off the net before the mystery downloads triggered. Note that Sobig.F is already the sixth in a series. It's usually been the case that the next in the series got released right after the "expiration date" of its predecessor. This planned obsolescence may be its most intriguing feature -- it certainly fuels some strained speculations! The worst news for c.l.py readers is that python.org email addresses are sitting in millions of browser caches, and when the worm spreads itself it forges a sender email address pulled off the infected machine sending the worm copy. That means mail.python.org is on the receiving end of gazillions of complaints, most machine-generated by idiot email servers that think they're complaining back to the entity who sent the email. So as much as by the worm itself, mail.python.org gets hammered by brain-dead responses from servers that recognize and block the worm. From jwsacksteder at ramprecision.com Fri Sep 26 11:36:03 2003 From: jwsacksteder at ramprecision.com (jwsacksteder at ramprecision.com) Date: Fri, 26 Sep 2003 11:36:03 -0400 Subject: COM: A bold new adventure in pain Message-ID: <71650A6F73F1D411BE8000805F65E3CB3B3630@SRV-03> I am attempting to do something that has apparently never yet been done before- implement a Crystal Reports User Function Library in Python. I suppose I should preface this by saying "I just barely understand what I am doing". CR has a standard for creating plug-ins that implement functions too complicated to be done in CR's own internal grammar. When CR starts up, it looks for COM automation servers starting with CRUFL and makes their methods available as additional formulas inside CR. I have implemented a COM automation object that is registered and can be called with Dispatch. It does, in fact, accept an input string and return properly-formatted output. HOWEVER- My object does not appear the the 'COM Browser' of Activestate's Pythonwin, and fails to be included in CR. This leads me to believe my little endeavour has gone off the rails somehow. My class definition(sans methods) looks something like this: class code128tools: _public_methods_ = [ 'code128B' ] _reg_progid_ = "CRUFLfoo.code128" _reg_desc_ = "Crystal Reports UFL Code128 toolkit" _reg_clsid_ = "{733D454C-43C1-436F-A0E2-E12AE05E4F07}" I think I have failed to define the 'type library'. I welcome any assistance gratefully. From lk at digicart.hu Thu Sep 18 06:14:04 2003 From: lk at digicart.hu (Ladvánszky Károly) Date: Thu, 18 Sep 2003 10:14:04 GMT Subject: Closures in python References: <9caba98e.0309180208.692e9b68@posting.google.com> Message-ID: <43d0f38b7160ca20a68b667f9029df82@news.meganetnews.com> Try this. def f(n): return n*2 def t(fnc_prm, n): return fnc_prm(n) t(f, 2) I hope it helps. K?roly "Kasper B. Graversen" az al?bbiakat ?rta a k?vetkezo h?r?zenetben: 9caba98e.0309180208.692e9b68 at posting.google.com... > Having played with Smalltalk for the past month, I'm getting used to > passing code as arguments to methods... how easy is it to do this in > python? I haven't seen any recent postings on this subject here... > > \kasper From tebeka at cs.bgu.ac.il Wed Sep 17 09:57:11 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 17 Sep 2003 06:57:11 -0700 Subject: Graphic python debugger References: <20030917120146.3c5202e2.max@fr.fm> Message-ID: <33803989.0309170557.32e9f6d4@posting.google.com> Hello Maxime, > I'm looking for a graphic debugger for python on linux like DDD or GVD. > I tried pdb and pdb-mode for emacs, but I would use a more gvd-like > debugger. IDLE (which comes with Python) has a debugger. HTH. Miki From hjwidmaier at web.de Thu Sep 25 16:10:53 2003 From: hjwidmaier at web.de (Hans-Joachim Widmaier) Date: Thu, 25 Sep 2003 22:10:53 +0200 Subject: Mutable strings References: <2ZBbb.100213$hE5.3539928@news1.tin.it> <20030922125024.GE32482@unpythonic.net> Message-ID: Am Mon, 22 Sep 2003 15:26:56 +0200 schrieb Alex Martelli: > On Monday 22 September 2003 02:50 pm, Jeff Epler wrote: >> On Mon, Sep 22, 2003 at 12:31:58PM +0000, Alex Martelli wrote: >> > But, there IS one! So, hat's wrong with it...?! >> >> People seem to love to have literals for things. Otherwise, they feel >> that a type is second-class. > > Sure. I have no problem deeming "mutable strings" (array of bytes) > to be "second-class" in some vague sense, since their use is so rare > and the need for literals of that type even rarer; lacking literals for, > e.g., sets.Set "troubles" me far more;-). > > I do keep daydreaming of some "user-defined semiliteral syntax" > such as, e.g. {} to > result in a call to (e.g.) .__literal__ with a list (or other > sequence) of tokens as the argument, returning whatever that > call returns. But perhaps it isn't that good an idea after all (it > does imply the __literal__ classmethod or staticmethod doing > some sort of runtime compilation and execution of those tokens, > and opens the doors to the risk of some seriously nonPythonic > syntax for such "literals-initializers"). [Sorry for replying so late] After writing what I did, I kept thinking about the issue. I finally realized the same thing - it wasn't so much the missing datatype, as you can use array but the missing literals. Having to construct constant values at runtime doesn't strike me as nice. I'm coming from the embedded world (hmm, that's not entirely true, as I'm not leaving it), and doing something efficiently is a big concern there, so doing something at runtime what you could do upfront is considered a bad thing. Python doesn't have and cannot be the perfect language for just everything. But even without "mutable strings", why does it have to be so handy even for manipulating binaries then? I'll get over it and give array a try. Thanks to Jeff for finding the gist of it and Alex for his analysis. It helps. Hans-J. From uj797 at victoria.tc.ca Fri Sep 5 12:19:40 2003 From: uj797 at victoria.tc.ca (Arthur T. Murray) Date: 5 Sep 2003 08:19:40 -0800 Subject: Basic Aspects of AI References: <88222545.0309050507.16e720a4@posting.google.com> Message-ID: <3f58a98c@news.victoria.tc.ca> > [...] We are preparing a subject for university... > we'd like to teach an introductory course on AI and > we are doing the previous research before deciding the > contents that give a better view of this exciting topic. http://www.amazon.com/exec/obidos/ASIN/0595654371/ -- "AI For You" (AI4U) is an AI textbook that you might consider using as an AI Lab supplement to pre-Singularity textbooks of artificial intelligence. > It would be really helpful and a lot more interesting if you could > give me your opinion on which are the basic areas to cover... or, > in other words, what would you consider essential for the best > understanding of the subject. http://mentifex.virtualentity.com/acm.html shows DIY AI steps. http://mentifex.virtualentity.com/python.html is a Python AI Blog. > I have posted this message in different groups. > Basically because I think not everyone may know about everything, > but maybe about some aspects of AI yes. Really interested also!! http://www.kurzweilai.net/mindx/profile.php?id=26 - Mind-eXchange is where readers share ideas and support for Open Source AI projects. > So, this is my query. Giving a good understanding of AI and > spreading its contents is basic for getting more minds > involved in it. Thank you very much in advance. From djc at object-craft.com.au Sun Sep 7 21:13:26 2003 From: djc at object-craft.com.au (Dave Cole) Date: 08 Sep 2003 11:13:26 +1000 Subject: CSV Module questions. References: Message-ID: > I'm trying to understand how to use the "csv" module. I assume this > means "comma seperated values" in files. I quote from the docs... > > > http://python.org/doc/current/lib/csv-fmt-params.html "When creating > reader or writer objects, the programmer can specify a string or a > subclass of the Dialect class as the dialect parameter" > > Ok, that's fine and dandy, but how do I specify it when I want to > create a "writer" to write a simple dictionary to a file, and > specify how it's to be written? > > Example (from the docs): > > # Just some stupid dictionary with key same as value. > someiterable = {'john d': 'john d', 'fred': 'fred'} > > # make the writer. > writer = csv.writer(file("some.csv", "w")) > for row in someiterable: > writer.writerow(row) > > Ok, so this made the file, but the file contents are thus... > > $ less some.csv > j,o,h,n, ,d > f,r,e,d > > which is NOT what I want. Obviously I have to probably make a > "Dialect" or something like that. But how do I do that? Obviously, > since Python severely lacks acceptable example code.... why didn't > they just put in a few examples of how to do this? I certainly > cannot figure this out. > > Here is what I want... > > "john d", "john d" > "fred", "fred" > > How to I write to a file in this way? Is is possible? When you write a "row" the writer expects the "row" to be a sequence. Passing a string as the "row" the writer causes the string to be handled as a row sequence thereby producing a row of single characters. Try this: >>> import sys, csv >>> w = csv.writer(sys.stdout) >>> someiterable = {'john d': 'john d', 'fred': 'fred'} >>> w.writerows(someiterable.iteritems()) john d,john d fred,fred - Dave -- http://www.object-craft.com.au From aleax at aleax.it Thu Sep 25 08:12:44 2003 From: aleax at aleax.it (Alex Martelli) Date: Thu, 25 Sep 2003 12:12:44 GMT Subject: adodbapi / string encoding problem References: Message-ID: <0ZAcb.118994$hE5.4097227@news1.tin.it> Achim Domma wrote: > Hi, > > I read a webpage via urllib2. The result of the 'read' call is of type > 'str'. This string can be written to disc via > file('out.html','w').write(html). Then I write the string into a Memofield > in an Access database, using adodbapi. If I read the text back I get a > unicode string, which can not written to disc via file(...) due to > encoding problems. How do I have to decode the unicode string to get my > original data back? You have to *EN*-code Unicode into string, with the same way the string had been *DE*-coded to Unicode originally, in order to be sure to get the same string back; specifically, you have to use the same *codec* (which stands for COder-DECoder). I don't know what codec adodbapi is using (Python's normal default codec is ASCII, which is the "minimum common denominator" of just about every encoding around -- if adodbapi hadn't surreptitiously inserted a different codec, it's impossible that anything would be decoded that might cause problems in encoding it back;-). Alex From anthony at interlink.com.au Fri Sep 12 11:44:15 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Sat, 13 Sep 2003 01:44:15 +1000 Subject: looking for MOP documentation In-Reply-To: References: Message-ID: <200309121544.h8CFiFF7024643@localhost.localdomain> >>> kasper graversen wrote > hello there. > > I've been searching the web (including the www.python.org :) but in vain of > finding recent documentation for the python MOP. I see some information on > python 1.5---is this the best and still valid information today? Erm, what's "MOP" mean? The current python is 2.3, and should probably be used everywhere possible (1.5 is seriously seriously old) Anthony -- Anthony Baxter It's never too late to have a happy childhood. From sross at connectmail.carleton.ca Sat Sep 6 18:34:27 2003 From: sross at connectmail.carleton.ca (Sean Ross) Date: Sat, 6 Sep 2003 18:34:27 -0400 Subject: Newbiequestion about lists and arrays.... References: <9193c0d1.0309061320.a0f430f@posting.google.com> Message-ID: "Michael" wrote in message news:9193c0d1.0309061320.a0f430f at posting.google.com... [snip] > c=[1]*3 > for y in range(3): > for x in range(3): > > c[x]=[1,2,3] > p[y]=c > > p[1][1][1]=888 > print p[1][1][1] > print p [snip] > Why does: > > p[0][1][1]=888 > > and > > p[1][1][1]=888 > > print out the same result? Hi. The problem is with "p[y] = c". This line binds p[y] to whatever c is bound to. c \ [[1,2,3], [1,2,3], [1,2,3]] / p[y] But, then, you've done this for all p[y], 0<=y<3, so c \ [[1,2,3], [1,2,3], [1,2,3]] / | | p[0] p[1] p[2] Now you modify p[1][1][1]: p[1][1][1] = 888 with this result: c \ [[1,2,3], [1,888,3], [1,2,3]] / | | p[0] p[1] p[2] Thus, p, which is [p[0], p[1], p[2]], looks like [[[1, 2, 3], [1, 888, 3], [1, 2, 3]], [[1, 2, 3], [1, 888, 3], [1, 2, 3]], [[1, 2, 3], [1, 888, 3], [1, 2, 3]]] Which is not what you wanted. To avoid this, you need only change p[y] = c to p[y] = c[:] c[:] creates a copy of whatever c was bound to. p[y] is then bound to that copy. c \ [[1,2,3], [1,2,3], [1,2,3]] # original [[1,2,3], [1,2,3], [1,2,3]] # copy (c[:]) / p[y] This happens for each y, 0<=y<3, so c \ [[1,2,3], [1,2,3], [1,2,3]] # original [[1,2,3], [1,2,3], [1,2,3]] # copy (c[:]) / p[0] [[1,2,3], [1,2,3], [1,2,3]] # copy (c[:]) / p[1] [[1,2,3], [1,2,3], [1,2,3]] # copy (c[:]) / p[2] Now, when you do p[1][1][1] = 888 The result is c \ [[1,2,3], [1,2,3], [1,2,3]] [[1,2,3], [1,2,3], [1,2,3]] / p[0] [[1,2,3], [1,888,3], [1,2,3]] / p[1] [[1,2,3], [1,2,3], [1,2,3]] / p[2] And, thus, p, which is [p[0], p[1], p[2]], looks like: [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 888, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]] Which is what you were looking for. Or, you could just build 'p' using a list comprehension: >>> from pprint import pprint as puts >>> p = [[[1,2,3] for y in range(3)] for x in range(3)] >>> p[1][1][1] = 888 >>> puts(p) [[[1, 2, 3], [1, 2, 3], [1, 2, 3]], [[1, 2, 3], [1, 888, 3], [1, 2, 3]], [[1, 2, 3], [1, 2, 3], [1, 2, 3]]] Which is also what you were looking for. HTH Sean From rickard-karlsson at bostream.nu Wed Sep 24 10:53:20 2003 From: rickard-karlsson at bostream.nu (Rickard Karlsson) Date: 24 Sep 2003 07:53:20 -0700 Subject: Newbie question, problem with functions References: <31bd93f0.0309231304.329c9589@posting.google.com> Message-ID: <31bd93f0.0309240653.6203330f@posting.google.com> > You are in fact passing the result of self.execute(...), i. e. None, instead > of the method. Do > > b3 = Button(frame, text="pwd", command=lambda: self.execute('pwd')) Thank you so much, it works fine now. From newsgroups at jhrothjr.com Tue Sep 16 06:53:51 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 16 Sep 2003 06:53:51 -0400 Subject: Duck Typing References: <221d8dbe.0309160101.4a09f2ad@posting.google.com> Message-ID: wrote in message news:221d8dbe.0309160101.4a09f2ad at posting.google.com... > Hello All, > I have been seeing this term "duck typing" for quite sometime now. It > will be nice if one of us can give an example in Python demonstrating > duck typing and/or link to some Python references. Why in the world would anyone want to do such a thing? I hadn't heard the term until you just brought it up, so a quick Google defined it. AFAICT, it's simply a cute name that's applied to a very common technique in languages that don't use static typing. In other words, if you need a file-like object, and someone passes you an object, your options are either to just use it (and handle the exceptions if it doesn't really support the proper interface) or use reflection to see if it has methods with the proper name and number of parameters, and then be prepared to handle the exceptions when they don't do what you expect. Six of one, half a dozen of the other. John Roth > > Regards, > Srijit From peterm at resmed.com.au Sun Sep 28 19:45:54 2003 From: peterm at resmed.com.au (Peter Milliken) Date: Mon, 29 Sep 2003 09:45:54 +1000 Subject: [ANN] pylint-0.2 References: Message-ID: I get the same error. I tried to find documentation to see whether I was using Pylint correctly or not but there isn't any. There seems to have been an attempt at providing the possible command line options (python pylint.py --help) but I don't find them particularly self-explanatory - so without documentation and the apparent ability to "run out of the box", I guess I'll just have to give this one a miss. One nice thing that has happened is it has led me to the Optik package (Option parsing). There is some nice documentation for this package - the author(s) of Pylint could take some direction from this package if they really want people to use Pylint (I have a personal hangup with people who write good, useful packages and then don't bother documenting them - life is just too short to read somebody else'e code to get around this deficiency :-) I get frustrated however when I think there is something that I could be taking advantage of but something as simple as the lack of 0.5hr of documentation stops me :-( ). In the meantime, I'll just have to watch this space :-) Peter "Mark Hahn" wrote in message news:EBkdb.3354$hp5.1305 at fed1read04... > > > Pylint is a lint-like tool for Python code > > Does pylint only work for modules? When I tried to run it on my code file > (ezpicmailer.py) , it raised an exception: > > No config file found, using default configuration > > Exception: Unable to find module for C:\photoedit\ezpicmailer in > > > and then it gave a long list of modules in my sys.path. It seems to insist > that the argument I give it be a module in sys.path, not just an arbitrary > python code file. > > ------------------------------------------ > > "Alexandre Fayolle" wrote in message > news:mailman.1064594507.31702.python-list at python.org... > Logilab has released pylint-0.2 > > What's new? > ----------- > > In addition to a large number of bug fixes, this release adds two new > checkers, for missing encoding declaration, and for FIXME comments. Zope > support was improved. > > About Pylint > ------------ > > Pylint is a lint-like tool for Python code. It performs almost all the > verifications that pychecker does, and additionally can perform some > stylistic verification and coding standard enforcements. The checked > code is assigned a mark based on the number and the severity of the > encountered problems. The previous mark of a given piece of code is > cached so that you can see if the code quality has improved since the > last check. > > URLs > ---- > > Homepage: http://www.logilab.org/projects/pylint > Download: ftp://ftp.logilab.org/pub/pylint/pylint-0.2.tar.gz > > > -- > Alexandre Fayolle > LOGILAB, Paris (France). > http://www.logilab.com http://www.logilab.fr http://www.logilab.org > D?veloppement logiciel avanc? - Intelligence Artificielle - Formations > > From max at ucmg.com.ua.remove.it Thu Sep 4 03:41:41 2003 From: max at ucmg.com.ua.remove.it (Max Ischenko) Date: Thu, 04 Sep 2003 10:41:41 +0300 Subject: Using Python under ASP In-Reply-To: References: Message-ID: > Another thing I've done, rather than just port all the code in a given > piece, is to find things I can modularize and then move only the > pieces to Python that I think make sense. For example, I've got a page > set up that you can dynamically add content to, kind of like a wiki, > but much more structured. The only part that is in Python is the > script that edits the HTML file, as file access and manipulation is so > much easier in Python than in an VBScript. All of the user elements > are either in straight html pages or in asp with vbscript. I post my > results to the Python page, update the file, then Response.Redirect to > the page I'm interested in viewing after the file is updated. I got a question on this issue. When modularizing Python code, how does one handle data exchange between Python snippets? I mean, you can't store anything complicated in a Session (for instance). Yeah, I can pickle/unpickle any Python object but that feels like a kludge. Should I setup some global hash, keyed by SessionID to store data there? -- Regards, Max. From martin at v.loewis.de Mon Sep 1 01:56:31 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 01 Sep 2003 07:56:31 +0200 Subject: Update to Python 2.3 on Red Hat Linux 9 References: <8242f4a7.0308282240.4c87f997@posting.google.com> Message-ID: bokr at oz.net (Bengt Richter) writes: > >Can you elaborate? What is this "this" you are referring to? > >And what do you mean by "highly automated"? > > > s/this/finding out all the libraries ... and compiling these for 2.3/ > > s/highly automated/make -someopts someargs/ > > or some setup.py stuff? distutils? Ah... You should perhaps try to build Python yourself some time and see how it works. Obtaining all the prerequisites is a gross PITA, as you have to determine what header files and libraries are needed, and then determine how your Linux distributor chose to package them - or, if you are using a trademark Unix (Solaris, HP-UX), you even might have to install (build, configure) the prerequisites. Once the prerequisites are present, this is highly automated, and distutils figures it all out. > E.g., for 2.2 I recompiled PIL and zlib from sources on windows, and > if there was a precanned deal, I missed it & re-invented just enough > to get by ;-/ Windows is a different story entirely. You read and follow the instructions in PCBuild/README, that's it. Regards, Martin From mwilson at sarcastic-horse.com Tue Sep 23 17:50:52 2003 From: mwilson at sarcastic-horse.com (Matthew Wilson) Date: Tue, 23 Sep 2003 17:50:52 -0400 (EDT) Subject: string.rstrip In-Reply-To: References: <731fc603.0309221414.78a92789@posting.google.com> Message-ID: <40885.199.169.240.132.1064353852.squirrel@svr1.turboweb.net> What would be the best way to strip off the last "_asdf" from "asdf_asdf_asdf"? >>>>>> "Hank" == Hank writes: > > Hank> The last 't' was stripped. Is this fixed or documented > Hank> anywhere? it works for other cases, but this one seems to > Hank> give me a weird result. > > That's because rstrip removes any characters up until the first one > one that doesn't match. Since the 't' before the '.' is in the strip > string '.txt' it is stripped too. Does this example clarify: > > > >>> 'John D. Hunter'.rstrip('retD') > 'John D. Hun' > > If you want to remove the extension, the best way is to use splitext > > >>> import os > >>> base, ext = os.path.splitext('test.txt') > >>> base > 'test' > > Hope this helps, > John Hunter > > -- > http://mail.python.org/mailman/listinfo/python-list > From mcfletch at rogers.com Sat Sep 6 16:54:44 2003 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 06 Sep 2003 16:54:44 -0400 Subject: [Jargon] Python glossary - contribute your definitions In-Reply-To: <16218.13681.159432.907101@montanaro.dyndns.org> References: <16218.13681.159432.907101@montanaro.dyndns.org> Message-ID: <3F5A4994.5@rogers.com> Skip Montanaro wrote: ... >I'm still interested in getting this off the ground, though. To make it >more likely that something significant gets done, I created a Wiki to which >people can add definitions: > > http://manatee.mojam.com/python-glossary > > ... Seems like something that could be hashed out faster and more reasonably as a thread on comp.lang.python where people propose, then vote on words (and/or definitions) suitable for a glossary. For example: * bot -- mythical or near-mythical creatures which appear as people on the comp.lang.python newsgroup, yet seem to operate at an impossible level of knowledge, accuracy and verbosity, often in regard to obscure and fascinatingly off-topic ideas. Common examples, Tim-bot, Martelli-bot, F-bot. Note that, for instance, Guido is seldom (if ever) described as a bot, whether because his posts tend to remain relatively short and on-topic, or because of his relatively succlusion within python-dev. * PSU -- Python Secret Underground, apparently mythical covert group ultimately responsible for the destiny of Python. According to the myths, tends to cut of posters mid-post (making them disappear via a band of thugs travelling around in white vans IIRC). Tends to be the target of most "conspiracy theory" posts, as it tends to allow for distancing criticism with humour. * superclass -- (1) the ancestor of a class within the inheritance hierarchy, a class which is one of the base-classes of a given class. (2) In a more limited sense, the class directly above the given class in the inheritence hierarchy, this definition comes into play more with Python 2.2's method-resolution-order. As distinct from a meta-class (implementation of the class). * dictionary, dict -- (1) a key to value mapping (2) a built-in type, currently implemented using a highly optimised hash-table implementation * generator -- a function or method which produces an interable stream of values by temporarily suspending operations when an item is discovered and resuming them only when the next value is returned. Requires that the method not "return" a value, instead the method should "yield" values as they are available. Generators allow for calculating results on an as-needed basis. * list comprehension -- declarative syntax for initialising new list objects, based on functional-language constructs. Each list comprehension can be expanded into an equivalent (series of) for-loops and if statements. * mro -- method resolution order, the ordering of classes in which Python (2.2 and beyond) attempt to resolve instance-attribute lookup in a class hierarchy. * python-dev -- (1) the mailing list on which the core Python development team discusses and organises Python's future development (2) the core Python development team itself. * standard library -- collection of code distributed with the core Python interpreter and generally assumed to be available in most environments o "blessed into the standard library" is occasionally used to describe Guido's acceptence of a module for inclusion in the standard library * Python-Labs -- * PBF -- * PSF -- * distutils -- (arguably this is just a module, but it's a critical module that people hear about w/out context quite often) * namespace -- (focus on Python semantics) Some of those are obviously too spartan to really help a new user, some are possibly not appropriate, some may be considered too basic to be included, some may be dead wrong. Having the general populous review and suggest improvements interactively would seem to be as useful an editing mechanism as any IMO, and would also allow new users to follow along in "word a day" style :) . Setting out a few ground-rules: * Cover humour, don't make it (i.e. the PSU mythos has had dozens of posts along the years, creating entirely new myths doesn't help, people want to know what's being talked about, not "how clever we can be") * Use neutral terminology as much as possible, imagine you were writing for the Jargon file, not a usenet post * Provide enough information that a google search will lead the interested to the information they need, exhaustive (encyclopeadic) entries aren't the goal of a glossary. * Skip has final say in resolving any Jargon issues, as the python-dev person in charge of the glossary check-in, we're all just suggesting things to him, in the end. * Focus on terms which are used (commonly) within the Python community, but are not generally used by tech folks. Some duplication of Jargon-file elements may be required to cover Python-specific sub-specialisations, or to cover very common Python idioms, but the Jargon file already covers a lot of tech jargon. * New users in particular, feel free to pipe up with a word you'd like defined. * Prefix all subject-lines with [Jargon] might make the process go a little more smoothly too. Just my 2c, Mike _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From buzzard at urubu.freeserve.co.uk Sat Sep 27 11:58:43 2003 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 27 Sep 2003 16:58:43 +0100 Subject: Saving Numeric arrays to file? References: Message-ID: "Alex Martelli" wrote in message news:GLhdb.178998$R32.5726980 at news2.tin.it... > Duncan Smith wrote: > ... > > What I > > *would* like is a reasonably generic (and not terribly inefficient) > > solution for > > storing strings that contain escape characters in text files. Cheers. > > I'm not quite sure what you mean by "contain escape characters" in this > context. But maybe the quoted-printable coding is what you're looking > for? See module quopri in the standard Python library. > > > Alex > Thanks Alex, I was writing to file strings such as '\n\x00\x00\x00\x00\x00\x00\x00' and then trying to retrieve them via readline(). It turns out that querying a MySQL table is easily quick enough for my purposes (the bottlenecks are elsewhere). But I'll certainly check out quopri (seeing as I wasn't aware of it). Thanks again. Duncan From glingl at aon.at Wed Sep 17 17:05:55 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed, 17 Sep 2003 23:05:55 +0200 Subject: None, False, True In-Reply-To: <3F68CB67.5000409@aon.at> References: <0KI9b.12967$x21.4828@twister.southeast.rr.com> <3F68CB67.5000409@aon.at> Message-ID: <3F68CCB3.2080609@aon.at> Gregor Lingl schrieb: .... > > Interestingly this doesn't occur in IDLE: > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on > win32 > Type "copyright", "credits" or "license()" for more information. > ... > IDLE 1.0 > >>> None = 3 > SyntaxError: assignment to None (, line 1) > >>> print None > None remark: If you run the script: None = 3 print None within IDLE, it does NOT issue a syntax error, but prints 3 (i. e. it works like the plain python interpreter) Gregor From mertz at gnosis.cx Sun Sep 7 13:50:42 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sun, 07 Sep 2003 13:50:42 -0400 Subject: Comments on Python Redesign References: Message-ID: "Tim Parkin" wrote previously: |text resizing here is a sample of +1 text size. |http://pollenation.net/assets/public/python-main-2larger.html |http://pollenation.net/assets/public/python-interior-2larger.html Yeah... this moves it from truly awful to merely bad. So that's a good step. Even so, the lines of text are squashed together vertically in an awkward way that makes reading difficult. I don't even really know how that effect was achieved (or in what browser)... is there a CSS attribute for "really small vertical spacing"? In my experience, good pages remain good even in the complete absence of their CSS stylesheet. Well, and CERTAINLY good pages do not embed ad-hoc tags all over them, but I don't think the redesign demo did that. While I'm only guessing, this is a page that would fare poorly with the CSS dropped, and with user-specified fonts and colors specfied. The problem is that it is WAY over-designed. It looks like something you'd design for a magazine, not for the web, with many browsers possible. Parkins, or whoever, has a certain browser and screen size, and probably took out a ruler to align everything properly on that unique combination. But on my screen, there is a gaping wasted space on the right edge. Why not put the "news and announcements" over on the right edge, using as much space as is available, instead of squashing things into fixed sized boxes? "Features" could then flexibly fill the middle section, scrolling down as far as is needed for the window size and font of a reader. That said, I -DO- like the look of the left navigation buttons. They could use more contrast still, but the light 3-D effect is good, and the subsections below an "opened" button is visually clear. The roundish, almost OpenLook-like, pane/box frames are fine. I kinda like the fingerprint icon, or whatever that is meant to be (two snakes?). And having a search tool at top seems useful. It's just hard to get past the font disaster (and the goofy, oversized, photos). Yours, Lulu... -- 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 john at rygannon.com Thu Sep 18 18:08:11 2003 From: john at rygannon.com (John Dean) Date: Thu, 18 Sep 2003 22:08:11 GMT Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> <3y7ab.1043$Od.78860@twister.tampabay.rr.com> <3f697584$0$10966$fa0fcedb@lovejoy.zen.co.uk> <87n0d26yv6.fsf@pobox.com> Message-ID: <3f6a2ce0$0$10967$fa0fcedb@lovejoy.zen.co.uk> Thank you John I don't see any point in making lame excuses, since most people are smart enough to see through rubbish. After all, we are only human and we should honest enough to admit to our failings -- Best Regards John From phil_nospam_schmidt at yahoo.com Fri Sep 5 22:16:49 2003 From: phil_nospam_schmidt at yahoo.com (Phil Schmidt) Date: 5 Sep 2003 19:16:49 -0700 Subject: I need a little help with Tkinter Entry widget References: <221e7b06.0309051235.2d5b4868@posting.google.com> Message-ID: <221e7b06.0309051816.4b514614@posting.google.com> Oh! Seems obvious when you say it! I've been using the Fredrik Lundh documentation, and saw nothing about those. Perhaps I should follow the recommendations of other posters and get that book about Tkinter... Thanks, Phil From sdementen at hotmail.com Fri Sep 12 07:19:13 2003 From: sdementen at hotmail.com (Sebastien de Menten) Date: 12 Sep 2003 04:19:13 -0700 Subject: formatting number in the CSV module Message-ID: <8dad5312.0309120319.13bc9062@posting.google.com> Hi, I need to output numbers to a csv file and use the new csv module in python2.3: " import csv data = [[ 0.321524523,0.5243523],[0.54635643,0.62776]] w = csv.writer(file("out.csv","w")) w.writerows(data) " However, I would like to format the number so that only the first 2 decimals are stored in the csv file. Is it possible to specify a formatting command like "%.2f" to the csv writer ? Seb ps: data in the real application is a BIG numeric array... From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 30 21:10:05 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 01 Oct 2003 02:10:05 +0100 Subject: "for" with "else"? References: Message-ID: <2c9knv86m1il4ajng85655dm7u5j5b992i@4ax.com> On Thu, 25 Sep 2003 11:15:51 -0400, "John Roth" wrote: >Frankly, I'd like to see special case syntax for an empty >sequence, but it's not that hard to handle now. That is what the 'else' suggests to me - particularly with 'while' loops. I don't think I've ever needed the existing 'else', but I could have used a loop-body-not-executed-at-all special case on a number of occasions I can see the use an application of 'else', of course - if you use 'break' to end a loop you may need different cleanup and therefore need to skip the standard cleanup. But if this is an issue I'm probably already using raise rather than break because it's most likely an error rather than a normal case. My guess is that it probably made a lot more sense before exceptions were added to Python. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From gerrit at nl.linux.org Tue Sep 30 07:33:31 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 30 Sep 2003 13:33:31 +0200 Subject: append special chars with "\" In-Reply-To: <3f793544$0$64721@hades.is.co.za> References: <3f793544$0$64721@hades.is.co.za> Message-ID: <20030930113331.GA3079@nl.linux.org> tertius wrote: > Is there a better way to append certain chars in a string with a > backslash that the example below? > > chr = "#$%^&_{}" # special chars to look out for > str = "123 45^ & 00 0_" # string to convert > n = "" # init new string > for i in str: > if i in chr: # if special character in str > n+='\\' # append it with a backslash > n+=i > print "old:",str > print "new:",n Another possibility: for c in chr: str = str.replace(c, r"\c") Untested, however, but something like this should work. Gerrit. -- 1. If any one ensnare another, putting a ban upon him, but he can not prove it, then he that ensnared him shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From ubaidullahnubar at hotmail.com Fri Sep 12 09:09:02 2003 From: ubaidullahnubar at hotmail.com (Ubaidullah Nubar) Date: 12 Sep 2003 06:09:02 -0700 Subject: RAD with Python Message-ID: <17d520f6.0309120509.491e4d7c@posting.google.com> Hi, How well is Python suited for developing database based applications? I am new to Python so please bear with me if some of the questions are too simple. I specifically have the following questions: 1. Is there an example of a simple data-entry application written in Python using a GUI interface? Something like a simple address book app with a listbox displaying all addresses with the ability to add/modify/delete. 2. There seem to be a number of GUI frameworks available? Which one is good for use on Windows and Linux? 3. Can Python apps be compiled to an exe? Can the resulting executable be distributed commercially? 4. What types of applications are not suitable to be written in Python? I have good knowledge of many languages including C++, Assembler, Java, etc. My preferred development tool is Clarion currently. If anybody with a Clarion background can share their experience with Python, that will be very helpful. Appreciate your answers... Thanks & Regards, Ubaidullah Nubar. From mpeuser at web.de Fri Sep 5 04:24:41 2003 From: mpeuser at web.de (Michael Peuser) Date: Fri, 5 Sep 2003 10:24:41 +0200 Subject: newbie question about dictionnary ? References: <3f582f90$0$20952$7a628cd7@news.club-internet.fr> Message-ID: "Sophie All?on" schrieb im Newsbeitrag news:3f582f90$0$20952$7a628cd7 at news.club-internet.fr... > for doing this I thought the dictionary was excellent but the key is a > string while I want it > to be the 2 points forming the edge ? How to do it ? > Luckily you are wrong! Keys can be numbers, strings, AND tuples of immutable data!!! Example: a="first" b=2 x={} x[(a,b)]="hi" print x However it will not work when assigning objects or lists to a or b. So you can use it when you store your objects in a list and refer to them by indexes. This is old fashioned stuff but may be really efficient. Kindly Michael P From bgailer at alum.rpi.edu Wed Sep 3 13:25:41 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 03 Sep 2003 11:25:41 -0600 Subject: Invisible function attributes In-Reply-To: References: <51809ae4.0309030715.7706cadb@posting.google.com> Message-ID: <5.2.1.1.0.20030903112137.030177c8@66.28.54.253> Of course the inevitable question is why do you want to do this? Consider creating a class instead (with a __call__ method if you want to call the instance as a function). class Foo: a = 1 # pre-initialized property def __call__(self): print self.a foo = Foo() foo() # prints 1 Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From g2h5dqi002 at sneakemail.com Tue Sep 30 03:01:12 2003 From: g2h5dqi002 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Tue, 30 Sep 2003 19:01:12 +1200 Subject: Slice inconsistency? In-Reply-To: References: <10c662fe.0309261245.1f35f43a@posting.google.com> Message-ID: Stephen Horne wrote: > The idea that single slices *should* behave in a different way to > extended slices seem bizarre to me - the kind of thing that arises out > of historic issues rather than out of principle. And it is indeed a historic issue. If you want the gory details: Once upon a time, there was no such thing as a slice object. Indexing and slicing were treated as completely separate things, and handled by separate methods at the C level: seq[x] --> the C-level equivalent of __getitem__(self, x) seq[x:y] --> the C-level equivalent of __getslice__(self, x, y) (There were no 3-element slices, either.) Moreover, the arguments to the C-level __getslice__ method *had* to be integers, and the interpreter performed the convenience of interpreting negative indices for you before calling it. Then Numeric came along, and people wanted to be able to slice multi-dimensional arrays. So the slice object was invented, and the parser and interpreter taught to create them when encountering slice notation, and feed tuples of them to __getitem__. But, for backwards compatibility, the special case of a single 2-element had to be handled specially. If the object being sliced had (at the C level) a __getslice__ method, it would be used. If it didn't, a slice object would be created and passed to __getitem__. This was fine for C objects, such as Numeric arrays, which can choose to not provide a __getslice__ method. But due to the way old-style classes are implemented, they *always* have a __getslice__ method at the C level, regardless of whether they have one at the Python level. So it's impossible to write an old-style Python class that doesn't get its single two-element slices mangled. Fortunately, new-style classes are much more like C objects, and they don't suffer from this problem. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jepler at unpythonic.net Thu Sep 4 08:51:15 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 4 Sep 2003 07:51:15 -0500 Subject: Arguments of function as out In-Reply-To: References: Message-ID: <20030904125110.GC14960@unpythonic.net> On Thu, Sep 04, 2003 at 08:12:57AM +0200, Birgit Rahm wrote: > > Thank you, > I've already read this, but I hoped, there is a way to get these out > parameters beside this. > Because I cant redesign the function on the server side. So I have only the > possibility to change the client side code, which calls this function. > It seems there is no way in python to use it and get the new out paramter > value after finishing the function. > Birgit I found this result when searching for 'omniorbpy "out parameter"': http://www.omniorb-support.com/pipermail/omniorb-list/2000-April/015244.html I don't know for certain that this is the way omniorbpy behaves today, but it is a very pythonic way to work. | From: Duncan Grisby | Subject: [omniORB] omniORBpy out parameter passing issue | [...] | Out arguments in the Python mapping appear as extra return values in a | tuple. So, if you have IDL | | interface I { | long op(in string a, out short b, inout double c); | }; | | Then to call op, you do | | (result, b, c) = i.op(a, c) | | I recommend that you read the mapping specification, which you can | download from | | http://www.omg.org/cgi-bin/doc?ptc/00-01-12 | | Cheers, | | Duncan. Jeff From jerf at jerf.org Mon Sep 1 20:18:12 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 02 Sep 2003 00:18:12 GMT Subject: Advice to a Junior in High School? References: <3d6c6fc3.0308261246.32db39d5@posting.google.com> Message-ID: On Tue, 26 Aug 2003 13:46:27 -0700, Stan Graves wrote: > "Howard Nease" wrote in message >> I >> love the subject, and I've wanted to be a computer scientist ever since >> I was 12 years old. (Unrelated to my reason for posting: You don't *need* to leave Computer Science, it's not going anywhere. People choose to become professional musicians, too, even though almost nobody can even make a living at it. You can be a Computer Scientist, you just may not make a lot of money. C'est la vie; for me, I still have to be a Computer Scientist, I love it too much to quit.) > Study literature - I have yet to see a single computer scientist who can > manipulate symbols as well as Shakespeare. class Rose: "A Rose is a Rose is a Rose.""" def sweetness(self): return "very" rose = Rose() otherName = rose assert rose.sweetness() == otherName.sweetness() Would you *notice* if a computer scientist matched Shakespeare? How can you compare the two at all? Statements like that sound all profound but are really the exact opposite; meaningless. From martin at v.loewis.de Thu Sep 4 15:56:16 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Sep 2003 21:56:16 +0200 Subject: PYTHONPATH x *.pth??? In-Reply-To: References: Message-ID: Carlos Moreira wrote: > I want to install Python third packages in a > non-default directory. > What?s the better way? > > - PYTHONPATH variable? > - *.pth files in site-packages? It depends on your requirements. For example: - Why is it that you don't want to install the packages in the default directory? Then, considering that reason, why would it be acceptable to install a .pth file there? - Is it acceptable that users of your application set PYTHONPATH? - Do you have to consider multiple installations of Python And so on. You should also consider a third alternative: - Extend sys.path explicitly in the application, before importing the third package. > I know that the two methos above are equivalents. But > what method will be keep in future Python releases > (for example)? Both with be kept indefinitely. Regards, Martin From kbilsted at it-c.dk Thu Sep 18 06:08:52 2003 From: kbilsted at it-c.dk (Kasper B. Graversen) Date: 18 Sep 2003 03:08:52 -0700 Subject: Closures in python Message-ID: <9caba98e.0309180208.692e9b68@posting.google.com> Having played with Smalltalk for the past month, I'm getting used to passing code as arguments to methods... how easy is it to do this in python? I haven't seen any recent postings on this subject here... \kasper From NO-MAIL at hotmail.com Tue Sep 16 18:30:03 2003 From: NO-MAIL at hotmail.com (M-a-S) Date: Tue, 16 Sep 2003 22:30:03 GMT Subject: why pass statement? References: Message-ID: "Hans Nowak" wrote in message news:mailman.1063743501.23038.python-list at python.org... > 'pass' is a no-op statement that, according to the tutorial, is used when a > statement is required syntactically but the program requires no action. I know. I just state that there is NO need for it. Just define in __builtins__ pass = None and that's it. BTW Algol-68 used 'skip' for both purposes (no action and no data). > Your code, using None, has the same effect. However, there's a slight > difference in the bytecode that is generated: > > >>> def f(): pass > ... > >>> def g(): None > ... > >>> import dis > >>> dis.dis(f) > 1 0 LOAD_CONST 0 (None) > 3 RETURN_VALUE > >>> dis.dis(g) > 1 0 LOAD_GLOBAL 0 (None) > 3 POP_TOP > 4 LOAD_CONST 0 (None) > 7 RETURN_VALUE > > This is probably irrelevant, but it wouldn't be correct to say that using pass > is exactly the same as using None. > > HTH, > > -- > Hans (hans at zephyrfalcon.org) > http://zephyrfalcon.org/ That's just a question of optimization. And thank you for showing me how to dig to the code! M-a-S From mpeuser at web.de Sat Sep 6 03:17:51 2003 From: mpeuser at web.de (Michael Peuser) Date: Sat, 6 Sep 2003 09:17:51 +0200 Subject: just curious References: Message-ID: "Elaine Jackson" schrieb im Newsbeitrag news:rnd6b.904924$ro6.18233500 at news2.calgary.shaw.ca... > I'm new to Python, and I've noticed the following: (1) Python has a quite strict "call by value" similar to C. This means - as in C) you can use formal parameters as if they were local variables. (And there are some useful tricks with that..) So A = A + B will have no outside impact. (2) A += B for lists is a shortcut for A.extend(B) which means that it changes something A is bound to (or "points to" as you would say in C). This is somewhat awkward because it sometimes works counter intuitive as in your case. Just keep in mind: A+=B is *not* A=A+B but behaves as if in most cases.... ;-) Kindly Michael P > > >>> def f(a,b): > a+=b > >>> def g(a,b): > a=a+b > >>> p=[1,2,3] > >>> q=[4,5,6] > >>> r=[7,8,9] > >>> s=[10,11,12] > >>> f(p,q) > >>> p > [1, 2, 3, 4, 5, 6] > >>> g(r,s) > >>> r > [7, 8, 9] > > Any deep reason for this, or "just because"? TIA. > > Peace, > EJ > > From rolfedh at hotmail.com Fri Sep 26 16:31:23 2003 From: rolfedh at hotmail.com (Rolfe) Date: 26 Sep 2003 13:31:23 -0700 Subject: Successful installation of mod_python on Apache on Win2k? References: Message-ID: > From: Rolfe Dlugy-Hegwer [mailto:RDlugyHegwer at symmetricom dot com] > Sent: Thursday, September 25, 2003 7:53 PM > To: 'sholden at holdenweb dot com' > Subject: mod_python on Win2k question > > > Hi Steve, > > I saw your thread on comp.lang.python: "I'm interested in installing > mod_python in two environments:1. Wind2000/Apache2" > > Any joy getting mod_python to run on Win2k? > Oh, yes. To quote Stanley Unwin (of whom you've probably never heard) "Deep joy in the fundimole". > I 1)downloaded fresh versions of apache and mod python, 2)made default > installations, 3)followed additional configuration > instructions for mod > python, 4) followed the tests recommended by mod_python > documentation, 5) OK, well I [...] just downloaded the installer. I had Python 2.2 installed, and I decided not to push the envelope by recompiling for 2.3 (which I also had installed). I also chose the somewhat older 3.0 mod_python, and then bolted the session and cookie stuff on from the 3.1 alpha mod_python, which seems to work after a bit of grotesque hacking an d one bug removal. > consulted the mod_python FAQ > and I can't get it to work. My browser displays the .py file > as text instead > of running it as a script. > It's probably the directory characteristics that need to change. If you plan to use the publisher interface (probably about the most general thing to do), you need to bear two things in mind: 1. Mod_python doesn't play well in script-aliased directories, so don't try using your cgi-bin directory for mod_python scripts. 2. You'll need an .htaccess file that reads something like [ferkles in /Inetpub/wwwroot/modpython ...] this: DirectoryIndex index.py AddHandler python-program .py PythonHandler mod_python.publisher PythonDebug On Actually you don't need the DirectoryIndex line, and obviously you can set up equivalent lines in httpd.conf instread if you want. > I'm going find someone who has succeeded and will write up > instructions for > the mod_python FAQ and for comp.lang.python. > I'm sure that would be very useful. Let me know if this has helped! [...] ;-) regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Interview with GvR August 14, 2003 http://www.onlamp.com/python/ From knightsofspamalot-factotum at gvdnet.dk Fri Sep 5 16:20:23 2003 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Fri, 05 Sep 2003 22:20:23 +0200 Subject: Selecting elements from a list References: <87y8x4w6ym.fsf@gvdnet.dk> <87brtzu5ak.fsf@gvdnet.dk> <87znhjw4r1.fsf@gvdnet.dk> Message-ID: <87smnbvvg8.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Duncan" == Duncan Smith writes: Duncan> Yes, messrs. Kjaerulff and Olesen. Then I'm afraid that we were talking about different people, and these people are probably less likely to run about getting wet on random Fridays. :-) They're swell people, though, or at least Kristian is, in my experience (only know Uffe by sight, hardly even voice). Oh well, it was still amusing despite the Fates not playing _that_ much with us. Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAj9Y8AcACgkQYu1fMmOQldWpSACdEn8FUR9Oh3CHya7SaEFpY+y5 CTQAoMd5w0JKmxiT8ULcv+RnD+lBQYSk =+uoP -----END PGP SIGNATURE----- From newsgroups at jhrothjr.com Wed Sep 10 07:38:45 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 10 Sep 2003 07:38:45 -0400 Subject: OT: Mailman misfeature. was: Re: How to instatiate a class of which the name is only known at runtime? References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:bjml1l$fd9$00$1 at news.t-online.com... > Marco Herrn wrote: > > > 1. How to do the import? I didn't find a way to give a string to the > > import statement. > > > > 2. How to write such code to instantiate? > > Off topic: This thread like some others is spread over a few toplevel > entries in my newsreader (KNode 0.7.2). Is this a bug? It's not a bug, it's a misfeature. Articles that are gated from the mailing list to the newsgroup have improperly truncated reference lists, so newsreaders can't put them together properly. If you look at the headers for a message posted via news, you'll find something like: References: <3F5ECDE2.40206 at mxm.dk> <3F5ECEF7.9080409 at mxm.dk> However, if you look at the headers for a message gated from the Python mailing list, you'll find: References: Which happens to be the ID of the first message in the tree, (which was, coincidentally, gated from the mailing list.) regardless of how far down in the tree it happens to be. Then if, for some reason, you don't have the message at the top of the tree, you get this scatter effect. I have no idea whether this is a problem with Mailman, the Mail RFCs, or the mail to news gateway. HTH John Roth From max at alcyone.com Thu Sep 11 20:34:24 2003 From: max at alcyone.com (Erik Max Francis) Date: Thu, 11 Sep 2003 17:34:24 -0700 Subject: why is this failing? References: <9x58b.139$u07.2@newsread1.news.atl.earthlink.net> <3F60E645.2501B9EE@engcorp.com> <3f60ea13$0$42053$a1866201@newsreader.visi.com> <87llsu6hij.fsf@pobox.com> Message-ID: <3F611490.23E27E1B@alcyone.com> "John J. Lee" wrote: > You wouldn't happen to know how to do this for python-mode? The latest versions will do it automatically. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ What a crime to waste [youth] on children. \__/ George Bernard Shaw From gh at ghaering.de Sun Sep 7 13:36:26 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 07 Sep 2003 19:36:26 +0200 Subject: in Ram database? In-Reply-To: References: Message-ID: <3F5B6C9A.1060907@ghaering.de> Tim Roberts wrote: > William Trenker wrote: >>Here is a simple example: >>[example of how NOT to use the DB-API] > This fails for me. No surprise. > There seems to be quite a bit of confusion in sqlite.py > regarding the transaction state. No. > The Connection object maintains a flag > called inTransaction that doesn't get cleared when you call "commit" > through the Cursor, Yeah, because that's not the way the Python DB-API is to be used. You're supposed to use the methods .commit() and .rollback() on the cursor object for transaction management. > so the script fails during termination because the > Connection tries to rollback what IT thinks is an open transaction. > > So, I tried changing it to use conn.commit() instead of > cursor.execute("commit"), but that causes a new problem: the > cursor.execute("begin transaction") fails beause cursor.execute > automatically opens a new transaction before sending the SQL to the engine, > and nested transactions aren't allowed. Yeah, maybe you should consider reading the DB-API spec or the PySQLite docs? See above for *NOT* issuing BEGIN/ROLLBACK/COMMIT yourself through .execute(), unless you know exactly what you're doing, which you are apparently not ;) If you know exactly what you're doing, you can use the parameter autocommit=1 (not =0, like I wrote in my other response) in the .connect() call. > Deleting the call to "begin transaction" solves that problem, because the > first "execute" in the loop causes a transaction to be opened > automatically. PySQLite has 7 tests in its test suite for transaction handling. Now hacking the PySQLite source code seems like a smart idea to make a b0rken example code work :-/ > Hmmm; this may be an opportunity for me to actually contribute to pysqlite, > which is one of the more useful things I've come across in Python. I'd be happy to help you get a better understanding. But I'm currently /a little bit/ ?nerv? because of the same old b. s. "solutions" for some problems being repeatedly posted on c.l.py. So people please remember: 1) the DB-API module handles transactions just fine for you, there is NO need to mess around with this yourself. Use .commit() or .rollback() on the connection object and everybody will be happy. Especially me ;) 2) the DB-API module quotes parameters just fine for you, there is NO need to mess around with this yourself. Just use a tuple of the parameters for the second parameter of the .execute() call. -- Gerhard From martin at v.loewis.de Thu Sep 4 15:47:09 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Sep 2003 21:47:09 +0200 Subject: Comparing objects - is there a maximum object? In-Reply-To: <7bdbb1a6.0309041124.6801b755@posting.google.com> References: <7bdbb1a6.0309041124.6801b755@posting.google.com> Message-ID: Chris Brew wrote: > so (unless this has been superseded) it doesn't seem that there is > such an object. Any suggestions? The easiest way to produce a maximum object is class Max: def __cmp__(self, other): return 1 maximum = Max() HTH, Martin From guy.flowers at Machineworks.com Mon Sep 15 11:15:49 2003 From: guy.flowers at Machineworks.com (Guy) Date: 15 Sep 2003 08:15:49 -0700 Subject: Processes. Message-ID: Hi I've done some projects in python for my work which invole some test scripts etc. All quite basic stuff, I find python a good language to work in but have come up against a brick wall. I'm been searching google for hours about processes pids etc. My problem is as follows the main problem code can be seen below : server = uc_server(HOST_str, PORT_num) while 1: asyncore.poll(SERVER_TIMEOUT) # Only pops queue when the current item is blank. if (server.current_queue_item == [0,"","",["",0],["",""]]): # Pops a queue item if there are any queue items to get. Temp_Current_Item = MainQueue.Pop() if (Temp_Current_Item != N): server.current_queue_item = Temp_Current_Item Execute_Command_str = ServerSupport.CreateCommand(Temp_Current_Item) # Only executes if on a win32 platform. if (sys.platform == "win32")and(Execute_Command_str != N): output, input = popen2("cmd.exe") input.write(Execute_Command_str+"\n") input.write("exit\n") while 1: text = output.readline() if text: print text else: # Sets the current queue item to blank. server.current_queue_item = [0,"","",["",0],["",""]] break What I want to have is a server which is multi platform win32, unix(lots of differnt sorts and may be mac later but forget mac for now.) that people can telnet onto leave a job, and then the server runs the jobs one at a time. What I have is a server that people can telnet on to leave a job, the server will execute it and keep executing it until it is done. I thought that maybe the poll thing would sort this out by switching from the main body of the script to the server part of the script, but it didn't. The way that I use popen2 is my fav. way of executing processes as I can catcher all output. What would be really good if I could execute commands or scripts by using child processes and searching for there pids this way I would know whats running on the box at any one time. There's loads about pids processes on google but it mainly in unix, I mainly want it in win32 which there is hardly anything about. Please Please Help TIA TTFN Guy From alberto.mantovaniNOSPAM at bologna.marelli.it Thu Sep 25 12:03:39 2003 From: alberto.mantovaniNOSPAM at bologna.marelli.it (Alberto Mantovani) Date: Thu, 25 Sep 2003 16:03:39 GMT Subject: pythonwin from dos Message-ID: <3f731176.33482654@powernews.libero.it> hi, how is it possible to run a python script in the pythonwin environment from dos command line? If I use the command "/run scriptname.py" and the pythonwin is already opened I get error, so someone can help me? thanks Alberto From hat at se-126.se.wtb.tue.nl Tue Sep 16 09:20:26 2003 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Tue, 16 Sep 2003 13:20:26 +0000 (UTC) Subject: from clipper move to python References: Message-ID: On Mon, 15 Sep 2003 13:00:57 +0700, ads wrote: > Hi Everyone, > > I'm starting learning python about 2 weeks, and still have > difficulties to create GUI based application because I never learn > about classes and other OOP things. Does anyone knows how to > create text console application like clipper using python. I don't know what clipper looks like, but you may want to have a look at curses, which I believe is also available with a Python interface (no doubt called pycurses or something in that direction). Albert -- Unlike popular belief, the .doc format is not an open publically available format. From ialbert at mailblocks.com Mon Sep 1 20:50:31 2003 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 01 Sep 2003 20:50:31 -0400 Subject: artificial intelligence In-Reply-To: References: Message-ID: Duncan Smith wrote: > What do Amazon use? My guess (unless it's something really naive) would be > association rules. In my previous job I worked for a research group studying recommender systems. We have our own, called MovieLens http://www.movielens.org among others we use a so called item-item recommender. We compute similarities between items then look at a given basket and based on it we choose to recommend the most similar items no yet selected. The good thing about this method is that item similarities are more static they don't need to be recomputed as often. Istvan. From fredrik at pythonware.com Fri Sep 26 16:17:33 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 Sep 2003 22:17:33 +0200 Subject: pilconvert script disappeared ? References: Message-ID: St?phane Ninin wrote: > I have just installed python 2.3 with many other libs, including PIL, > (from http://www.pythonware.com/products/pil/), > version 1.1.4 for Python 2.3b1. > > Am I dreaming or has the script pilconvert.py disappeared from the free PIL > distribution ? > > Can I find it somewhere else ? see: http://mail.python.org/pipermail/image-sig/2003-August/002386.html From pdfernhout at kurtz-fernhout.com Mon Sep 1 16:36:32 2003 From: pdfernhout at kurtz-fernhout.com (Paul D. Fernhout) Date: Mon, 01 Sep 2003 16:36:32 -0400 Subject: Object Database (ODBMS) for Python In-Reply-To: References: Message-ID: <3f53ad7e_5@corp.newsgroups.com> Niki- Thanks for the pointer to e4graph. I found more info about it here: http://www.marshallbrain.com/robotic-freedom.htm There are several similarities -- and conceptually the ideas are very related (to the same extent the ER model is related to graphs). A few comments on part of their blurb on that page: "The e4Graph library allows you to model any kind of relationship between data that can be represented by a directed graph, including circular graphs of connections between data items. e4Graph is unique in that it allows these circular relationships to be represented directly rather than implicitly or through meta-data, as is necessitated by other approaches such as relational databases. A bi-directional link between two data items can be represented by two directed connections between those data items." The Pointrel Data Repository System allows circular relationships. All links in the Pointrel System are bi-directional (well, sort of quad directional in a way). Differences include: * The Pointrel System is in pure Python (e4graph is in C++ and uses a C++ database). * The Pointrel System suports the notion of "spaces" which could be seen as somewhat like "graphs" -- except query operations can span spaces (or even multiple archives for that matter). * The Pointrel System focuses more on complete history (e.g. tracking many versions of a linked node as it were in the e4graph metaphor). These comments are all off the top of my head after persuing the e4graph site for a few minutes; perhaps after looking more at e4graph I may realize some of these comments are incorrect or there may other important differences or similarities. Thanks again for pointing e4graph out. In general, the Pointrel System bears a resemblance to any system that implements something related to Peter Chen's "Entity Relational" (ER) model. http://bit.csc.lsu.edu/~chen/display.html http://www.cs.sfu.ca/CC/354/zaiane/material/notes/Chapter2/node1.html The Pointrel System is not quite the same as pure ER in some implementation details (e.g. it embeds the notion of a space, it focuses on triads not arbitrary relationships, the newer version doesn't have relations as first class objects, it doesn't seperate attributes from relations, etc.), but otherwise has many of the same features. --Paul Fernhout http://www.pointrel.org Niki Spahiev wrote: > 8/29/2003, 19:11:51, Paul D. Fernhout wrote: > > [...] > PDF> Well, to chime in here, in a "friendly" competition / cooperation sort > PDF> of way, the Pointrel Data Repository System, > PDF> http://sourceforge.net/projects/pointrel/ > PDF> while not quite an object database (and admittedly its case being > PDF> easier) has a simple API in the bare minimum use case (it has more > PDF> complex variants). Here is an example of its use (with fragments > PDF> inspired in response to an earlier c.l.p poster's use case a few days ago): > > How it compares with e4graph? > -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- http://www.newsfeeds.com - The #1 Newsgroup Service in the World! -----== Over 100,000 Newsgroups - 19 Different Servers! =----- From messageboardfan1 at yahoo.com Thu Sep 25 11:13:35 2003 From: messageboardfan1 at yahoo.com (ataraxia2500) Date: Thu, 25 Sep 2003 17:13:35 +0200 Subject: newbie script References: <3f71937f$0$28022$79c14f64@nan-newsreader-01.noos.net> <3f719ed5$0$14824$79c14f64@nan-newsreader-03.noos.net> <3f72eb7c$0$29964$79c14f64@nan-newsreader-02.noos.net> Message-ID: <3f730632$0$8285$79c14f64@nan-newsreader-01.noos.net> Peter Otten wrote: > ataraxia2500 wrote: > >> I get that weird error when I tried to run the little loop, this is what >> it says: >> >> sys:1: DeprecationWarning: Non-ASCII character '\xa0' in file myloop.py >> on line 3, but no encoding declared; see http://www.python.org/peps >> pep-0263.html for details >> File "myloop", line 3 >> os.system('/home/joe/src/myprog/myprog') >> ^ >> SyntaxError: invalid syntax >> >> does it mean anything to you? > > > The whitespace before os.system() consists of '\xa0' characters, no idea > why. > > However, I have noticed that when I copy and paste from KNode 7.2 using > Strg+C/Strg+V instead of the middle mouse button, all '\xa0' are magically > converted back to old '\x20' space characters. > > Peter what editor do u use? I'm using kedit and kwrite From mwh at python.net Mon Sep 22 08:57:48 2003 From: mwh at python.net (Michael Hudson) Date: Mon, 22 Sep 2003 12:57:48 GMT Subject: was: Re: looking for MOP documentation References: <3F6319E9.4C7BAA0F@engcorp.com> <3F66F516.3D06D946@engcorp.com> <3F69AD0F.53D51719@engcorp.com> <3F69D215.5649AF66@hotmail.com> <3F69DFEB.5B05CED8@engcorp.com> <7h37k45j895.fsf@pc150.maths.bris.ac.uk> <3F6B2AB1.2D839EF5@engcorp.com> Message-ID: <7h3d6dt9e8i.fsf@pc150.maths.bris.ac.uk> Holger Krekel writes: > Although probably 2/3 of the implementation of Python deal with the > type/object implementations, from a using-the-language point of view > the syntax probably contributes more obviously to the observed > "simplicity" of Python. OK, I disagree with you, too :-) > But the term "meta object protocol" seems to point much more into > the direction of types/objects as Michael suggests and here Python > has a lot to offer. Is there some free material on MOP somewhere? http://www.elwoodcorp.com/alu/mop/contents.html looks like being a version of AMOP online, you know that book I brought with me to one of the pypy sprints :-) (actually, it may have been the Gothenbourg sprint). I can bring it to the next sprint I come to, if you like. Cheers, mwh -- SCSI is not magic. There are fundamental technical reasons why it is necessary to sacrifice a young goat to your SCSI chain now and then. -- John Woods From robin at jessikat.fsnet.co.uk Tue Sep 9 03:59:24 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 9 Sep 2003 08:59:24 +0100 Subject: Jython class names Message-ID: I recently came across a problem with porting to Jython basically the following is prints 1 in CPython, but not in Jython. class C: pass red = C() print red.__class__.__name__ is 'C' it seems that Jython doesn't intern names in the same way or instances are not constructed in the same way. Is the above test robust or should I always be using == for testing class names? -- Robin Becker From adalke at mindspring.com Wed Sep 24 15:05:38 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 24 Sep 2003 19:05:38 GMT Subject: Bottleneck? More efficient regular expression? References: <3f7069db_4@corp.newsgroups.com> Message-ID: <6Wlcb.2095$RW4.416@newsread4.news.pas.earthlink.net> Me: > I get confused with the DOM API every time I try /F: > the DOM API is designed for consultants, not for humans or > computers. Here I thought I was making a living the last few years as a consultant. Now I find I was making a living being a human. I'm feeling much better now. :) Andrew dalke at dalkescientific.com From leonardbocock at yahoo.com Tue Sep 23 22:19:58 2003 From: leonardbocock at yahoo.com (lebo) Date: 23 Sep 2003 19:19:58 -0700 Subject: Python embedded in C & memory releasing Message-ID: <63701d2f.0309231819.31fdec85@posting.google.com> Hi I'm trying to understand how Python handles memory usage and dynamic object loading and unloading. Problem to solve? Build a very low memory footprint (non-GUI) Python application for Unix/Windows. Why use Python? End user flexibility. So far it seems that (on Windows): (1) memory increases when you import . Expected behaviour. (2) memory does not release when you del . Why not? Is Python not releasing the memory or is it the OS not releasing memory? So then I tried embedded Python in C: (1) c application base 1.6MBytes (a good number) (2) Call Python function from c application - memory up to 2.6MByte (OK number) (3) Python function exits but memory usage stays at 2.6MByte Why is memory not releasing? How can I tell if this Python behaviour or OS behaviour? C code snippet: #include int main(int argc, char *argv[]) { int y = 0; printf("Started...\n"); for (int count=0;count < 999999999;count++) { y += 1; } printf("Initing Py\n"); Py_Initialize(); PyRun_SimpleString("from time import sleep\n" "print 'I will sleep for a while'\n" "sleep(10)\n" "print 'Exiting Py'\n"); Py_Finalize(); for (int count=0;count < 999999999;count++) { y += 1; } return 0; } Thanks, Leonard From sag at hydrosphere.com Mon Sep 8 15:38:38 2003 From: sag at hydrosphere.com (sag at hydrosphere.com) Date: Mon, 08 Sep 2003 15:38:38 -0400 Subject: Deepcopy on XML node in python2.2 problem Message-ID: <3F5CA27E.17594.1EF341CE@localhost> Pythonistas, I have been using python 2.1 on a windows platform to develop some xml processing classes. The input xml can be such that I want to take out parts of its and convert it to a text representation and put the text back in as a single 'text' node. I am using _xmlplus.minidom. I am now moving the code to a Red Hat Linux machine with python 2.2, and I am getting an error that doesn't occur with the exact same code on the python 2.1 machine. See below for output from the two platforms. Basically, I locate the base of the subnode tree that I want to convert and I do a deep copy on the node tree and then I convert that copy to a new xml object and get the string version of it back. The problem seems to be in deepcopy. On windows, it returns a copy of the subnode tree that has a parent that is a DOM element and that has the children I would expect from the copy, while on the python2.2 the parent is a text node and the children are completely different. If I don't use deepcopy, parts of the original tree are removed when I do an appendChild call on the new subnode xml object. I am a very intermediate python programmer and I don't know enough to try to chase down what's going on in deepcopy. Does anyone who is a guru have any ideas on what might be causing this? Is it a difference between windows/linux or between python2.1 and 2.2? My goal is to convert a subnode tree to a single text node where the subnode tree is converted totally to xml text string. See below for a somewhat abbreviated case that shows the difference. If I run this code on python 2.1 on windows, it runs. If I run it on python 2.2 on linux, it fails. sue ++++++++++++++++++++++++++++++++++++ Code example: # test deepcopy using minidom xml # the point of all this is to carve out subsections of an xml # and convert it to text that can stand alone as xml # this is a small part of a set of classes for special xml handling from _xmlplus.dom.minidom import parseString from _xmlplus.dom import minidom import copy argName = 'arg' def _convert2Text(child): xmlText = "" temp = parseString(xmlText) root = temp.documentElement for subNode in child.childNodes: cp = copy.deepcopy(subNode) print 'copy', cp print 'parent of copy', cp.parentNode print 'parent children', cp.parentNode.childNodes root.appendChild(cp) subText = temp.toxml() subText = subText.encode("utf-8") return subText def _parseNode(node): results = {} if node.nodeType == node.ELEMENT_NODE: name = str(node.nodeName) attr = node.getAttribute('t') if not node.hasChildNodes(): results[name] = '' elif len(node.childNodes) == 1 and node.childNodes[0].nodeType == node.TEXT_NODE: value = str(node.childNodes[0].nodeValue) results[name] = value, attr else: for n in node.childNodes: results.update( _parseNode(n)) else: pass return results # convert it to modified version def getArgs(): root = _xmlDOM.documentElement argList = [] for child in root.childNodes: if child.nodeName == argName: nodeValues = _parseNode(child) if len(nodeValues) == 1: try: argList.append(nodeValues[argName]) except KeyError: subText = _convert2Text(child) argList.append(subText) else: subText = _convert2Text(child) argList.append(subText) return argList if __name__ == '__main__': print '+' * 20 fn = r"Aggregate" kwds = r'1' kwds = "" tfn = fn + kwds fn = r"TransformDS" args = r'%s' % tfn f = "" + fn + args + "" xmlText = "%s%s" % (r'', f) _xmlDOM = parseString(xmlText) print _xmlDOM.toxml() args = getArgs() print 'after convert' print args # end code ======================= Results: Ouput from python 2.1 on windows +++++++++++++++++++++++ TransformDSAggregate copy parent of copy parent children [] after convert ['\nAggregate'] ++++++++++++++++++++++++ Output from python 2.2 on red hat linux ++++++++++++++++++++++++ TransformDSAggregate copy parent of copy parent children [] Traceback (most recent call last): File "/home/sag/testBad.py", line 23, in _convert2Text root.appendChild(cp) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", line 171, in appendChild node.parentNode.removeChild(node) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", line 212, in removeChild self.childNodes.remove(oldChild) ValueError: list.remove(x): x not in list From tebeka at cs.bgu.ac.il Tue Sep 30 15:26:21 2003 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 30 Sep 2003 12:26:21 -0700 Subject: can i implement virtual functions in python ? References: Message-ID: <33803989.0309301126.5798a116@posting.google.com> Hello Prabu, > I'm new to python, so excuse me if i'm asking something dumb. > Does python provide a mechanism to implement virtual functions? > Can you please give a code snippet also...:) http://www.python.org/doc/current/tut/node11.html#SECTION0011500000000000000000 Miki From tonarn at localhost Sat Sep 6 10:38:53 2003 From: tonarn at localhost (Toni Arnold) Date: Sat, 06 Sep 2003 14:38:53 GMT Subject: win32api.GetShortPathName : nt4.0 != win2k Message-ID: <1103_1062859133@entarin> I am using Zope 2.6.1 on win32 with integrated Python 2.1.3 and just discovered that >>> win32api.GetShortPathName("C:/a long folder/a long file.txt") behaves equally on nt4.0 and win2k: On both systems this error is raised if the file does not exist: pywintypes.api_error: (2, 'GetShortPathName', 'Das System kann die angegebene Datei nicht finden.') BUT (!): >>> win32api.GetShortPathName("C:/a long folder/file.txt") behaves differently: On nt4.0 the file doesn't need to exist, probably because the name "file.txt" is already well formed according to the DOS 8+3 naming convention. On win2k, the same error as above is raised. This can break upwards compatibility of existing win32 Python/Zope applications using DOS helper applications, e.g. mine :-( From gordon at dragonsdawn.net Tue Sep 16 13:47:39 2003 From: gordon at dragonsdawn.net (Gordon Messmer) Date: Tue, 16 Sep 2003 10:47:39 -0700 Subject: problems with threaded socket app References: <3f656f76$0$20942$7a628cd7@news.club-internet.fr> Message-ID: On Mon, 15 Sep 2003 09:58:50 +0200, Anthony McDonald wrote: > > if rpipe not in ready_pipes[0]: > # Time to cancel this SMTP conversation > smtpi.close() > # The dialback thread will now write a failure message to > # its status pipe, and we'll need to clear that out. > os.read( rpipe, 1024 ) > continue > > The code creates a "race" condition. To work correctly it requires the > worker thread to raise and handle an exception, and to write that result > onto the pipe BEFORE your main thread attempts to read the pipe. > > If the worker thread loses the race, the next MX result you process will > recieve the last MX's results 400 error code, and your left with 1 thread at > the end of the sequence which can't terminate as it stays active until what > its written to the pipe is read from the pipe. > > Simple enough to fix, just add a select call between closing the SMTP > connection and reading the expected 400 error response. I can do that, but can you explain why, if the monitor thread loses the race, it wouldn't block until the worker thread writes its status to the pipe? The code below should have the same race condition, but it works properly. [root at deerhunter root]# python2 Python 2.2.2 (#1, Jan 30 2003, 21:26:22) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> import thread >>> import time >>> def write_stat( wpipe ): ... time.sleep(20) ... os.write( wpipe, 'my status' ) ... >>> (rpipe, wpipe) = os.pipe() >>> thread.start_new_thread( write_stat, (wpipe,) ) 1026 >>> test = os.read( rpipe, 1024) >>> print test my status >>> From BoteDesSchattens at web.de Thu Sep 11 14:54:31 2003 From: BoteDesSchattens at web.de (Tobias Pfeiffer) Date: 11 Sep 2003 18:54:31 GMT Subject: FIFO problems References: Message-ID: Hi! "Steve Holden" wrote in news:tJZ7b.67$o71.53 at news2.central.cox.net: >> while 1: >> line = serverIn.readline()[:-1] >> if line == "bla": >> do this >> else: >> print line >> > > The problem here is that you aren't testing correctly for and > end-of-file condition. So the end-of-file-thingy also ends a line for the readline-command, I suppose? OK, would make sense for normal file read-processes... *grin* > The slice notation you use to "remove the line terminator" > unfortunately gives the same result for an empty line (one > containing only a line terminator) and end-of-file (which returns a > line containing no characters at all). > > There are various ways around this. Since you are talking > interactive multi-process stuff here it's probably safest to do > somehting like the following (untested) code: > > while 1: > line = serverIn.readline() > if not line: > break as changed: line = line[:-1] > if line == "bla": > do something incredibly interesting > else: > print line In which case will the "if not line" condition be true? When there is an end-of-file? But I just don't want it to break, I want it to continue and wait for a somewhat useful line, e.g. if another client connects. Bye and thanks for your help Tobias From aleax at aleax.it Mon Sep 1 12:46:55 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 01 Sep 2003 16:46:55 GMT Subject: exception question References: Message-ID: <3KK4b.11097$nw1.366911@news1.tin.it> Aahz wrote: > In article , > Gon?alo Rodrigues wrote: >> >>For error processing I found convenient maintaining a dictionary where >>the keys are exception *classes* and the values are callables. Of >>course, for this to work, exception classes have to be hashable which >>I happily found that they were. So my question is, can I count on this >>behaviour? Or is this behaviour I should not count on? (I found >>nothing on the docs about it, thus the question). > > If it's not documented, you can't count on it. There's no intrinsic > reason exception classes would be made unhashable, *but* classes become > unhashable as soon as they implement __cmp__() or __eq__() *and* they > fail to implement __hash__(). So if someone ever asks to compare > exceptions, it could be an issue. A new-style class would NOT become unhashable by implementing __eq__ w/o __hash__, although its INSTANCES would (but Gon?alo is clearly indicating that he cares about classes, not instances). Unfortunately exception classes are old-style, so they'd be subject to the darned old confusion between class and instance. HOWEVER, one might hope that if ever standard exception classes ARE changed in a way that is not backwards compatible, by adding __eq__ &c, then at the same time they might be made new-style classes, which would in any case have much lesser potential for old-code breakage. > You may want to bring this issue up on python-dev. Good suggestion -- but I'd further suggest the class-vs-instance and old-vs-new classes distinctions be clearly kept in mind when so doing. Alex From ray at rays-web.com Fri Sep 19 09:14:58 2003 From: ray at rays-web.com (Ray Smith) Date: 19 Sep 2003 06:14:58 -0700 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> <6ee58e07.0309171548.314a046c@posting.google.com> <87r82e6yxg.fsf@pobox.com> <6ee58e07.0309181053.70facb64@posting.google.com> Message-ID: <5654fff9.0309190514.134790cb@posting.google.com> llothar at web.de (Lothar Scholz) wrote in message news:<6ee58e07.0309181053.70facb64 at posting.google.com>... > jjl at pobox.com (John J. Lee) wrote in message news:<87r82e6yxg.fsf at pobox.com>... > > > Ken Godee writes: > > > > John, is Ken right that buying the commercial BlackAdder license means > > you don't have to pay for the TT license too? Certainly a good deal > > if so. > > > > Yes, please answer about this topic. This is one thing that would be > great but there is also no clue on the website about it. The web page mentions a number of times that nothing else is required, Quotes from the BA web page: "BlackAdder gives the programmer, in a single package, all they need to develop sophisticated applications." " A complete cross-platform Integrated Development Environment for developing GUI applications in Python and Ruby. You don't need anything else." "Personal and Business Editions. The Business Edition includes optional support and the rights to distribute the run-time elements with your application at no extra charge." "Detailed Features... The Professional version of the Qt GUI toolkit (v3.x) including: * the Canvas module * the Table module * the Database module * Qsocket, QserverSocket, and Qhost Address classes from the Network module." "Business Edition Features... # Includes the rights to distribute the run-time elements (except mxODBC) with your application. " "Requirements BlackAdder requires Python version 2.2.x. " Although it doesn't explicity say .. "You are NOT required to buy QT or PyQT licenses..." it says a number of times .. that nothing else is required to make and distribute full blown applications, and it also lists the only requirement as Python 2.2.x. So with all that info one must "assume" QT and PyQT licenses are included with BA!!! Regards, Ray Smith From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Tue Sep 23 12:14:12 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Tue, 23 Sep 2003 17:14:12 +0100 Subject: Thoughts on PEP284 References: <5j4vmvgnr5v68f6lupbpgt0mop6l7ps2sn@4ax.com> <_9Vbb.105320$hE5.3711223@news1.tin.it> Message-ID: <0cp0nv8mao24iml4hjamv23fhfiv12e7jk@4ax.com> On Tue, 23 Sep 2003 10:22:50 GMT, Alex Martelli wrote: >> Adding operators to types is always problematic because it defeats >> Pythons's runtime checking. Assuming that integer slicing would be added >> to Python, methods that would expect a list of integers would suddenly >> also work with integers. In most cases, they would not work correctly, but >> you wouldn't get a meaningful exception. > >Careful: in Stephen's proposal, slicing would NOT work on *INTEGERS* -- >rather, it would work on the *INT TYPE ITSELF*, which is a very, very >different issue. Exactly - thanks for that. Actually, Sean Ross posted a prototype implementation which makes a good point - theres no reason why the sliceable object needs to be the standard 'int' type in Python as it is now. Maybe a library extended int type, imported only if used, makes sense. Maybe this is a recipe or library proposal rather than a language proposal. >>> Also, one extra feature is that the loop can be infinite (which range >>> and xrange cannot achieve)... >>> >>> for i in int [0:] : > >No way, Jose -- now THAT would break things (in admittedly rare >cases -- a method expecting a list and NOT providing an upper bound >in the slicing). I'd vote for this to be like int[0:sys.maxint+1] >(i.e., last item returned is sys.maxint). True - but boundless generators are already in use. An implicit sys.maxint(ish) upper bound seems wrong to me. I would either go with allowing the infinite loop or requiring an explicit upper bound. >What Stephen's proposal lacks is rigorous specs of what happens for all >possible slices -- e.g int[0:-3] isn't immediately intuitive, IMHO;-). You're right in that this was not intended as a full formal proposal. But lets see what I can do... To me, it should be possible to create slices for negative ranges as easily as positive ranges, so the convention of -1 giving the last item wouldn't apply. I already had to look at this issue when I wrapped some C++ container classes for Python recently (unreleased at present due to the need for further Pythonicising) - the whole point of doing so was that the containers allow some more power and flexibility compared with the Python ones. For instance, my set and (dictionary-like) map classes are conveniently and efficiently sliceable. But how should the slicing work? BTW - there is a price for flexibility - I was very surprised at the relative speed of a dictionary (at least an order of magnitude faster than my map) though to be fair I haven't done even trivial optimisation stuff yet. No, these aren't STL containers. Anyway, back to the point... I could have treated slices as specifying subscripts (while the data structure is *not* a sorted array, it does support reasonably efficient subscripting) but I felt the upper and lower bounds should be key values rather than subscripts. But when basing the bounds on keys, a bound of '-1' logically means a bound with the key value of -1 - not the highest subscript value. The 'step' value is slightly inconsistent in that it had to be a subscript-like step (stepping over a specific number of items rather than a specific key range) as the keys don't always have a sensible way to interpret these steps. But I'm drifting from the point again. As a 'set of integers' would IMO logically be sliced by key too, '-1' should just be a key like any other key, giving... >>> int [-5:0] [-5, -4, -3, -2, -1] >>> int [0:-5] [] >>> int [0:-5:-1] [0, -1, -2, -3, -4] So to me, the slice should be evaluated as follows... if step is None : default step to 1 if step == 0 : raise IndexError if start is None : either default to zero or raise IndexError, not sure if stop is None : either raise IndexError or... if step > 0 : default stop to +infinity else : default stop to -infinity Obviously that isn't a real implementation ;-) -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From mwilson at the-wire.com Wed Sep 17 08:14:11 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 17 Sep 2003 08:14:11 -0400 Subject: When passing functions as args, References: Message-ID: In article , python at sarcastic-horse.com wrote: >When I pass a function as an arg, like for map(...), how do I pass args to >use for that function? >If I have a function like this: > >def pretty_format(f, fmt='%0.3f'): > return fmt % f > >I want to use it with map() like this: > >formatted = map(pretty_format, unformatted_list) >#exept I want fmt='%4.5f' !!! > >I need to figure out how to pass a non-default value for fmt. How do I do >that? map (lambda x: pretty_format (x, '%4.5f'), unformatted_list) or [pretty_format (x, '%4.5f') for f in unformatted_list] should do the trick. Actually filling in the default argument is not simple, and probably isn't radically better than the above. Unless you're going to put more functionality into pretty_format, or you have some other reason to centralize your formatting, ['%4.5f' % x for x in unformatted_list] might be best of all. Regards. Mel. From emile at fenx.com Tue Sep 30 16:44:07 2003 From: emile at fenx.com (Emile van Sebille) Date: Tue, 30 Sep 2003 13:44:07 -0700 Subject: where are the "class variables"? References: <62e9c66e.0309301227.20505db6@posting.google.com> Message-ID: "Dominik Kaspar" wrote in message news:62e9c66e.0309301227.20505db6 at posting.google.com... > maybe my question was badly formulated. i give it a new try: > why does the following program give the output "0 0" and not "1 0"? > why does it loop forever? and how could that problem be fixed? As written, you have a local varaible running in method run that gets set and never changes. The class variable you're looking for is Server.running, like this: import time, threading class Server(threading.Thread): running = 0 def run(self): Server.running = 1 while Server.running: print "do something here..." time.sleep(5) def stop(self): Server.running = 0 server = Server() server.start() print server.running # should print "1" server.stop() -- Emile van Sebille emile at fenx.com From neil.padgen at mon.bbc.co.uk Thu Sep 25 09:36:40 2003 From: neil.padgen at mon.bbc.co.uk (Neil Padgen) Date: Thu, 25 Sep 2003 13:36:40 +0000 Subject: Thoughts on PEP315 References: <6bm1nvc7pfkqppndn0lcks0edqdqf02tra@4ax.com> <9ji3nv8l1l57t1ichle04hkd41s31i9fmf@4ax.com> Message-ID: <86ad8t7zx3.fsf@pc-nrp.dev.mon.bbc.co.uk> >>>>> "Stephen" == Stephen Horne <$$$$$$$$$$$$$$$$$@$$$$$$$$$$$$$$$$$$$$.co.uk> writes: Stephen> So a 'break if ... :' cannot accidentally metamorphose Stephen> into a 'break; if ... :'. It can if you press return at the wrong place: while True: blah ; blah ; blah break if condition: blah ; blah ; blah This would be perfectly legal if the new-style while loop were in another loop. -- Neil From jdhunter at ace.bsd.uchicago.edu Sat Sep 13 13:43:28 2003 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sat, 13 Sep 2003 12:43:28 -0500 Subject: gdmodule true type font size Message-ID: When using gdmodule to draw text using true type fonts im.string_ttf(font, fontsize, angle, (x,y), s, color) the docs say 'draw string s at (x,y) using the TrueType font at the given pointsize and angle.' It is not clear to me how gd handles point size. A fontsize of 12 should be 12/72 = 1/6 inches tall but how does gd decide what an inch is? 72 pixels? Is there some scale parameter or constant that allows gd to make the conversion from pixels to points? I want my text to scale with image resolution which is determined by a dpi parameter, and I tried doing scale = dpi/72.0 im.string_ttf(font, scale*fontsize, angle, (x,y), s, color) but the fonts are larger than they should be, at least according to my calculations. Thanks, John Hunter From ian_maurer at yahoo.com Wed Sep 17 16:19:41 2003 From: ian_maurer at yahoo.com (Ian Maurer) Date: Wed, 17 Sep 2003 13:19:41 -0700 (PDT) Subject: Money data type In-Reply-To: Message-ID: <20030917201941.41872.qmail@web20208.mail.yahoo.com> Check out this project: http://fixedpoint.sourceforge.net/ Good Luck! - Ian --- "Batista, Facundo" wrote: > Can't find it. > > I mean something like: > > >> m1 = Money(decimal=2) > >> m2 = Money(decimal=2) > >> m1.value = 3.20 > >> m2.value = 2.15 > >> print m1 + m2 > 5.35 > > 5.35! Not 5.3500000000000001 neither 5.34999999999999999999. > > I think this is not a rare thing, but I can't find it in the > standar library > neither the package index. > > Thanks! > > . Facundo > > -- > http://mail.python.org/mailman/listinfo/python-list ___________________________________________________ Yahoo! Messenger - Nueva versi?n GRATIS Super Webcam, voz, caritas animadas, y m?s... http://messenger.yahoo.es From adalke at mindspring.com Thu Sep 25 22:03:10 2003 From: adalke at mindspring.com (Andrew Dalke) Date: Fri, 26 Sep 2003 02:03:10 GMT Subject: When did Windows start accepting forward slash as a path separator? References: Message-ID: Stephen Ferg: > When did Windows start accepting the forward slash as a path separator > character? DOS 2. When directories were introduced. Many of the functions were based on unix, down to a NUL terminated filename and the name "creat". But DOS 1 was modelled on CP/M which used "/" as a command line option flag. You couldn't use a "/" in the DOS shell because it would be interpreted as the flag. You could change the flag using a DOS command, eg, to use "-" instead, but that was disabled in the 3.x days; for good reason. Hence, the low-level DOS commands (since 2.0) would take both / and \ as separators, but some codes did their own filename munging and would not. > At one time, it was accepted as a truism that Windows (like MS-DOS) > was different from Unix because Windows used the backslash as the path > separator character, whereas Unix used the forward slash. It was? My copy of Norton's Guide to the IBM PC makes the explicit statement that directories were directly influenced by unix. I actually regard this as a point of similarity. The character used is a minor issue. There are, of course, many ways in which they are different. Like drive names, which comes from CP/M, and the filesystem layout itself (FAT vs. inodes). And DOS had much better IDEs, like Turbo Pascal. ;) > I hypothesize that originally Windows accepted only the backslash, and > then at some time it changed to accept the forward slash as well. > Does anyone know when that change occurred? Was it with the > introduction of support for long filenames in NT and Win95? The original Windows was a shell on top of DOS. Programs under Windows could use the DOS layer directly, which took both separators. Even in Wn95 I could exit to DOS, meaning I could quite out of Win95 to the shell prompt then do 'win' to start it up again. Andrew dalke at dalkescientific.com From medved at fcc.net Fri Sep 12 08:28:59 2003 From: medved at fcc.net (Ted Holden) Date: Fri, 12 Sep 2003 08:28:59 -0400 Subject: pygtk clist usage References: Message-ID: David M. Cook wrote: > BTW, CList is deprecated (meaning it will go away in the next major gtk > release). ListStore/TreeView can be a bit hard to make the transition to, > though, as the documentation is rather scattered and fragmentary. Best > sources of info are... I've been trying to take a look at the TreeView/ListStore model. I mean, you've gotta be kidding. Who do you expect to want to try to figure that out in order to use a simple listbox? Other than that, I'm seeing a conceptual problem with the pygtk documentation is that it appears to all be oriented towards coding gtk objects by hand. In real life, most people are going to want to use glade to design gui's, and this is not laziness on the part of programmers. Having the gui sitting there in an XML file is a hell of a neat thing. The application I'm working on, which works at this point, used to look like about 3000 lines of code in a Tcl/Tk version, in which Tk code was wound in and around app code so thoroughly that it was difficult even for me to read. The glade/pygtk/swig version looks like about 400 lines of code which is very easy to read and work with; again, all the gui code is sitting there in an XML file. The idea of coding guis by hand is probably unacceptable to most people at this point. . . , , ____)/ \(____ _,--''''',-'/( )\`-.`````--._ ,-' ,' | \ _ _ / | `-. `-. ,' / | `._ /\\ //\ _,' | \ `. | | `. `-( ,\\_// )-' .' | | ,' _,----._ |_,----._\ ____`\o'_`o/'____ /_.----._ |_,----._ `. |/' \' `\( \(_)/ )/' `/ `\| ` ` V V ' ' Splifford the bat says: Don't throw the old stuff away, until the new stuff works.... From jetman516 at hotmail.com Sat Sep 27 19:20:06 2003 From: jetman516 at hotmail.com (The Jetman) Date: 27 Sep 2003 16:20:06 -0700 Subject: [2.2.1]How To Gracefully Shutdown an XML-RPC Server References: Message-ID: "Andrew Dalke" wrote in message news:... > The Jetman: > > I'm reading source code, but I haven't found any examples of > > how to simply shutdown my XML-RPC server. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114579 > > Or you can ungracefully use os._exit, like pulling the emergency > brake on a train. > > Andrew > dalke at dalkescientific.com Andrew: Thanx ! I *swear* I always spend at least a couple hours or so looking for stuf like this on my own ! That's the single most frustrating part about the Web (besides this idiotic W32.Swen virus/worm) ! No matter how you compose a query, there's always something that you miss.... BTW, I haven't tried it, but I bet os._exit will fail just like sys.exit(). Besides the reason for a graceful shutdown is more than cosmetic, since a forced shutdown (like a Ctrl-C) may occasionally leave the sockets allocated (which *has* happened.) Later....Jet From lists at webcrunchers.com Sun Sep 7 20:16:12 2003 From: lists at webcrunchers.com (John D.) Date: Sun, 7 Sep 2003 17:16:12 -0700 Subject: CSV Module questions Message-ID: I'm trying to understand how to use the "csv" module. I assume this means "comma seperated values" in files. I also posted this earlier, but didn't see it get posted to the list, so excuse the possible double posting. I quote from the docs... http://python.org/doc/current/lib/csv-fmt-params.html "When creating reader or writer objects, the programmer can specify a string or a subclass of the Dialect class as the dialect parameter" Ok, that's fine and dandy, but how do I specify it when I want to create a "writer" to write a simple dictionary to a file, and specify how it's to be written? Example (from the docs): # Just some stupid dictionary with key same as value. someiterable = {'john d': 'john d', 'fred': 'fred'} # make the writer. writer = csv.writer(file("some.csv", "w")) for row in someiterable: writer.writerow(row) Ok, so this made the file, but the file contents are thus... $ less some.csv j,o,h,n, ,d f,r,e,d which is NOT what I want. Obviously I have to probably make a "Dialect" or something like that. But how do I do that? Obviously, since Python severely lacks acceptable example code.... why didn't they just put in a few examples of how to do this? I certainly cannot figure this out. Here is what I want... "john d", "john d" "fred", "fred" How to I write to a file in this way? Is is possible? John From knightsofspamalot-factotum at gvdnet.dk Fri Sep 5 02:18:27 2003 From: knightsofspamalot-factotum at gvdnet.dk (Martin Christensen) Date: Fri, 05 Sep 2003 08:18:27 +0200 Subject: Selecting elements from a list References: <87y8x4w6ym.fsf@gvdnet.dk> Message-ID: <87brtzu5ak.fsf@gvdnet.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >>>>> "Duncan" == Duncan Smith writes: Duncan> Is this the sort of thing you mean? Duncan> >>> A = [0, 1, 2, 'four', 'five', 6.0] Duncan> >>> [x for x in A if isinstance(x, str)] Duncan> ['four', 'five'] Duncan> >>> Yes, that's exactly the sort of thing I meant. For some reason, I have built some intuition of list comprehensions as always being one to one. Now, the one place I should have looked that I didn't was the Python tutorial, which I thought I was done with by now. The clarity of hindsight is a bitch. :-) Thanks. Martin - -- Homepage: http://www.cs.auc.dk/~factotum/ GPG public key: http://www.cs.auc.dk/~factotum/gpgkey.txt -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.2 (GNU/Linux) Comment: Using Mailcrypt+GnuPG iEYEARECAAYFAj9YKrMACgkQYu1fMmOQldX6kACglqJBUiFL4gGrRmDgchZYEm53 vWQAnRxm7YzaGSlhIRtLd29zwlCmplDA =7NNS -----END PGP SIGNATURE----- From aahz at pythoncraft.com Sun Sep 7 15:16:54 2003 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2003 15:16:54 -0400 Subject: Comments on Python Redesign References: Message-ID: In article , Terry Reedy wrote: > >Perhaps Python needs two front pages or even two sites. One for the >IT manager types that you seem to be aiming at, who would be impressed >by the corporate look that tends to depress me, and one for >programmers just looking for info. The current site, perhaps with >more tweeks, is pretty good for the latter but not, I would agree, for >the former. I'm leaning toward vetoing any such plan. One problem with the Perl community is that it's not clear which web site to use for different purposes -- I think we should keep www.python.org as the universal URL. That said, there likely will be a subsection of python.org that is aimed at managers, with a more designed look and more graphics; someone trying to convince a specific manager could point zir into the subsection. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From medved at fcc.net Wed Sep 10 01:44:02 2003 From: medved at fcc.net (Ted Holden) Date: Wed, 10 Sep 2003 01:44:02 -0400 Subject: pygtk clist usage Message-ID: If anybody has any sort of a clue as to how to use a clist generated by glade as a list, the 'GtkList' changed to 'GtkClist' by hand, and add input strings using 'append' and end up seeing more than just the first character of each line, I'd appreciate hearing from them. From danielk at aracnet.com Tue Sep 2 08:45:57 2003 From: danielk at aracnet.com (Daniel Klein) Date: Tue, 02 Sep 2003 05:45:57 -0700 Subject: Polymorphism the Python way References: Message-ID: On Sun, 31 Aug 2003 09:37:00 +0200, "Michael Peuser" wrote: >I am not sure I understand your problem. What you do is fine (though it is >not exactly 'polymorphism'). I assume you mean: > instance.getthing() >because writing self.getthing() has unclear connotations. Yes, sorry...'instance' (or 'object') is what I meant. :-( It's not a problem really. I just thought there would be a better, more elegant way to achieve polymorphism without using getters. Daniel Klein From afriere at yahoo.co.uk Wed Sep 10 01:15:37 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 9 Sep 2003 22:15:37 -0700 Subject: OT: Americans love their guns References: Message-ID: <38ec68a6.0309092115.41dc6881@posting.google.com> "Al Kirke" wrote in message news:... > "Nick Vargish" wrote in message > news:m3k78j6v5e.fsf at tanelorn.bandersnatch.org... > > Steve Lamb writes: > > > > > Do this simple test. Get an egg timer (or any other timing device). > > > Now set it to 4, maybe 5 minutes. Now lock yourself in the closet. > > > > Counter-test: Imagine your seven-year-old son finding your gun and > > shooting and killing your five-year-old daughter while you're working > > in your study. > > Impossible. The son had been taught safe gun handling on > the pistol range w/ a .22 starting at aged five, and would > come and tell you that firearm had not been safely stored. > > Al Why is it impossible for someone who has been taught safe gun handling to shoot and kill someone else? Do they use aversion therapy or something? From wester at ilt.fraunhofer.de Mon Sep 22 05:01:20 2003 From: wester at ilt.fraunhofer.de (Rolf Wester) Date: Mon, 22 Sep 2003 11:01:20 +0200 Subject: thread question Message-ID: Hi, I have an application that starts a second thread, that receives messages via a socket-server and puts that messages into a queue. The main thread is polling that queue for new messages. My problem is that the main thread takes to much of the time polling the empty queue while the socket-server thread doesn't get enough time for receiving the messages. Is it possible to force the main threat to sleep for a certain amount of time or give the socket-server thread a higher priority? Thanks in advance. Kind regards Rolf Wester From newsgroups at jhrothjr.com Fri Sep 5 10:33:37 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 5 Sep 2003 10:33:37 -0400 Subject: Why the 'self' argument? References: Message-ID: "Grzegorz Staniak" wrote in message news:slrnblh5ru.nd5.gstaniak at inka.zagiel.pl... > Hello, > > I'm a newbie Python user, a systems administrator - I've been trying > to switch from Perl to Python for administrative tasks - and one thing > I cannot understand so far is why I need the special 'self' (or anything > esle) argument in class method definitions. I might have missed an > explanation in the docs, a quick Google search did not help. Is there > somewhere on the web you could direct me to? It's in the FAQ somewhere. Technically, it would be possible to make "self" a reserved word, and not have to put it in the method declaration. However, there are a lot of people who use something other than the word "self," so that would break existing code. John Roth > > Thanks, > > -- > Grzegorz Staniak From blunck at gst.com Wed Sep 10 22:03:32 2003 From: blunck at gst.com (Christopher Blunck) Date: Wed, 10 Sep 2003 22:03:32 -0400 Subject: ANNOUNCE: ZSI v1.4.1 RC1 Message-ID: I'm pleased to announce the first release candidate of ZSI v1.4.1. ZSI is the plumbing that allows Python modules to communicate via SOAP. New in this release is the capability to consume a WSDL, and invoke methods against the endpoint using the ServiceProxy class. This code was generously donated by Brian Lloyd and the Zope corporation. Also new in this release is the capability to convert the complex types and operations defined in a WSDL document into Python modules. This makes invocation of web services simple. Please take a look at our website for more information: http://pywebsvcs.sf.net/ From sketerpot at chase3000.com Wed Sep 3 12:22:48 2003 From: sketerpot at chase3000.com (Peter Scott) Date: 3 Sep 2003 09:22:48 -0700 Subject: what is the easiest way to parse a file References: Message-ID: <659f82ff.0309030822.383db80a@posting.google.com> > Is there a library in python which could be used for parsing file based upon > various sections I don't know what you're talking about, and I frankly doubt that anyone else does either, but I'll hazard some guesses of vaguely plausible things. The standard ConfigPareser module can parse windows-style INI files, which are arranged in sections. There is always the usual XML/SGML stuff; I'm not very enthusiastic about it, but you can see the documentation. If you need to brush up on your XML, there's a nice intro at . I say "nice" because it is the least buzzword-crazed XML page I could think of off the top of my head. You could also write something of your own. It shouldn't be too hard. Perhaps you could split the file into sections with a regular expression (try re.split(), or the split() method of a compiled regexp), and then parse the sections individually. If you're working with some odd format, that's probably the best solution if Google fails you. -Peter From rstevens at bennington.edu Sun Sep 21 18:09:42 2003 From: rstevens at bennington.edu (Rybread) Date: 21 Sep 2003 15:09:42 -0700 Subject: using poplib to retrieve messages sent from a certain address Message-ID: Real quick, I have account X and I want a python script that goes in and looks for emails sent from Y and then to save them. i'm trying to go off the swen killer I have listed below (which i took from someone on this NG): import poplib import time print 'Start at', time.asctime() host = 'X' port = 110 user = 'username' pasw = 'password' logfilename = 'sent_from_mobile_phone' minsize = 130000 maxsize = 180000 fromtag = 'From user at domain %s\n' ps = poplib.POP3(host, port) ps.user(user) ps.pass_(pasw) messages = ps.list() print '%d messages, %d bytes' % (len(messages[1]), messages[-1]) logfile = open(logfilename, 'a') for sms in messages[1]: sid, ssize = sms.split() if minsize <= int(ssize) < maxsize: message = ps.retr(sid) print 'retrieving and deleting msg#%s, %d bytes, %d lines' % ( sid, message[-1], len(message[1])) logfile.write(fromtag % time.asctime()) for line in message[1]: logfile.write(line) logfile.write("\n") logfile.write('\n') ps.dele(sid) ps.quit() print 'Done at', time.asctime() print From manuelbastioni at tin.it Mon Sep 8 13:04:23 2003 From: manuelbastioni at tin.it (Manuel Bastioni) Date: Mon, 08 Sep 2003 17:04:23 GMT Subject: Get the date of last modification of a file Message-ID: It's possible using only a built-in module? Thx, Manuel --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.515 / Virus Database: 313 - Release Date: 01/09/2003 From rudy.schockaert at pandora.be Wed Sep 17 14:27:54 2003 From: rudy.schockaert at pandora.be (Rudy Schockaert) Date: Wed, 17 Sep 2003 18:27:54 GMT Subject: SMTPlib Emailing Attachments In-Reply-To: <4fd6e92.0309170849.287e86b6@posting.google.com> References: <4fd6e92.0309170849.287e86b6@posting.google.com> Message-ID: Bill wrote: > I am trying to have the capability to email attachments. Specifically > I want to be able to email a specific attachment that I name that may > be a PDF document, text doc, etc. I already have a working piece of > code that emails jpg attachments but does not work with any other > types of attachments. Could someone tell me how to modify this code to > send other types of attachments like the one's stated above(especially > PDF's)? Also how do I determine the name of the attachment? Right now > it defaults to Attach0. Here is the current code I have below: > _________________________________________________ > import sys, smtplib, MimeWriter, base64, StringIO > > message = StringIO.StringIO() > writer = MimeWriter.MimeWriter(message) > writer.addheader('Subject', 'The Text test') > writer.startmultipartbody('mixed') > > # start off with a text/plain part > part = writer.nextpart() > body = part.startbody('text/plain') > body.write('This is a picture of chess, enjoy :)') > > # now add an image part > part = writer.nextpart() > part.addheader('Content-Transfer-Encoding', 'base64') > body = part.startbody('image/jpeg') > #body = part.startbody('text/plain') > base64.encode(open('c:\email\chess01.jpg', 'rb'), body) > > # finish off > writer.lastpart() > > # send the mail > smtp = smtplib.SMTP('fc.hbu.edu') > smtp.sendmail('bblancett at hbu.edu', 'bblancett at hbu.edu', > message.getvalue()) > smtp.quit() > __________________________________________________________________________ Wouldn't it be a lot easier to use the email module? This is a snippet of how I send attachments (simply replace TO,FROM,Subect, path (full pathname including filename) and filename with relevant data): import smtplib import mimetypes from email.Encoders import encode_base64 from email.MIMEAudio import MIMEAudio from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def getAttachment(path, filename): ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(path, 'rb') if maintype == 'text': attach = MIMEText(fp.read(),_subtype=subtype) elif maintype == 'message': attach = email.message_from_file(fp) elif maintype == 'image': attach = MIMEImage(fp.read(),_subtype=subtype) elif maintype == 'audio': attach = MIMEAudio(fp.read(),_subtype=subtype) else: print maintype, subtype attach = MIMEBase(maintype, subtype) attach.set_payload(fp.read()) encode_base64(attach) fp.close attach.add_header('Content-Disposition', 'attachment', filename=filename) return attach msg = MIMEMultipart() msg['From'] = FROM msg['To'] = TO msg['Subject'] = SUBJECT attach = getAttachment(path, filename) msg.attach(attach) server = smtplib.SMTP(MAILSERVER) server.sendmail(FROM, [TO], msg.as_string()) server.quit() From llafba_NOSPAM_ at gmx.net Tue Sep 23 10:47:19 2003 From: llafba_NOSPAM_ at gmx.net (Tom) Date: Tue, 23 Sep 2003 16:47:19 +0200 Subject: load changes of subclasses Message-ID: Hi, I have a main program that uses a lot of definitions in different classes. They are included like this: from subclass1 import * from subclass2 import * My problem is: whenever I make changes in one of the classes I have to close and reopen the main program for the changes to take effect. This is kind of annoying, because I always want to test if my changes are correct and that's why I have to run the main program. Is there some kind of a shortcut where I don't have to close and reopen the main program? I hope this question is not too stupid, but I am still quite new to Python. Thanks a lot. Regards, Tom From vald at valis.amber.eu.org Wed Sep 10 16:10:20 2003 From: vald at valis.amber.eu.org (vald) Date: Wed, 10 Sep 2003 22:10:20 +0200 Subject: TTF fonts rendered in Python Message-ID: <20030910201019.GA22261@bobas.nowytarg.pl> I wonder if there is any module for rendering True Type Fonts in Python ? I need to create a GIF files with nice antialiased text and I'm unable to find any module with such functionality. Sincerely, K. From python at sarcastic-horse.com Wed Sep 17 20:34:41 2003 From: python at sarcastic-horse.com (python) Date: Wed, 17 Sep 2003 20:34:41 -0400 Subject: Module to generate OpenOffice Writer documents In-Reply-To: <1093E8BAEB6AD411997300508BDF0A7C1571ECD0@USHEM204> References: <1093E8BAEB6AD411997300508BDF0A7C1571ECD0@USHEM204> Message-ID: <20030917203441.259609e5.python@sarcastic-horse.com> On Wed, 17 Sep 2003 19:53:15 -0400 "Ellinghaus, Lance" wrote: > Has anyone created a module to generate the XML formatted files for > OpenOffice? > Sorry, I can't help you there. What I'd be even more interested in is if it is possible to submit the xml to OpenOffice, and then use its rendering features to crank out pretty PDF files, all through scripts. From amk at amk.ca Tue Sep 9 13:34:45 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 09 Sep 2003 12:34:45 -0500 Subject: Redesign of Python site References: <3F5E0171.B68BDE2F@engcorp.com> Message-ID: <_WydnXPHCO6oksOiRTvUqA@speakeasy.net> On Tue, 09 Sep 2003 12:36:01 -0400, Peter Hansen wrote: > I think that's a distinct improvement, although I'd suggest putting > the Documentation section (in the sidebar) _first_ rather than second > after the Versions section. Really? I envision people wanting information on a specific version first, only later going to the more generic items under "documentation". Do other people think this would be a good idea? > I'd also move FAQ up to right under "What > is Python?". Done. > (You mention different top navbar links but they look the same to > me, if you're talking about the Home/Search/Download stuff at the top.) Oh, I'm an idiot and dropped an old version of the page on top of it. Updated now, at same URL as before. The navbar changes are: 1) dropping SIGs and Help, 2) adding a not-yet-written "Contact us" page and a link to the site map. --amk From harry.pehkonen at hotpop.com Tue Sep 16 12:27:00 2003 From: harry.pehkonen at hotpop.com (Harry Pehkonen) Date: 16 Sep 2003 09:27:00 -0700 Subject: Tkinter.Text can never be empty? Message-ID: <70df36e9.0309160826.596dd5ab@posting.google.com> While setting up some unit tests, I came to the conclusion that a Tkinter Text widget can never be empty, but will always (?) contain a \n. Here is a brief example: >>> import Tkinter >>> t = Tkinter.Text() >>> t.get(0.0, Tkinter.END) '\n' >>> t.delete(0.0, Tkinter.END) >>> t.get(0.0, Tkinter.END) '\n' >>> My apologies, but I have not checked whether or not this can be reproduced in Tcl/Tk (which I think might have been appropriate). My question is: Is there *always* a trailing \n, is this a bug, or am I doing something silly? Thanks! Harry. From logistix at cathoderaymission.net Sat Sep 20 18:18:54 2003 From: logistix at cathoderaymission.net (logistix at cathoderaymission.net) Date: 20 Sep 2003 15:18:54 -0700 Subject: Swen Detection code Message-ID: <3c91a864.0309201418.459f8bfc@posting.google.com> Writing pop3 filters in python seems to be a pretty popular activity today. ;) So far it looks like the actual executable attachment isn't mutating like subject lines, from and to fields are. I wrote some code that scans message bodies for content-types that shouldn't be executable (such as midis and wavs) and also scans content-types that should be executable for the virus signature. I just included the whole base64 encoded virus in the source file so it's too large to post to usenet. The code is available at: http://www.cathoderaymission.net/~logistix/python/detectSwen.py (I'll also email if anyone requests). This code does NOT interface with pop or hit your mailserver. It only provides a predicate function for virus signature detection. It also doesn't do anything with bad bounces where the attachment has been stripped. As usual, use care when automatically deleting emails. It'd also be a bad idea to do something like file("test.exe","wb").write(base64.decodestring(virusSig))) ;) From claird at lairds.com Thu Sep 4 04:53:13 2003 From: claird at lairds.com (Cameron Laird) Date: Thu, 04 Sep 2003 08:53:13 -0000 Subject: Writing solid code book References: <87wucqni5j.fsf@pobox.com> <1dk5tt7q6acwf$.rcboqaop39ha.dlg@40tude.net> <3f56de81.372851401@news.blueyonder.co.uk> Message-ID: In article <3f56de81.372851401 at news.blueyonder.co.uk>, Alan Gauld wrote: >On Wed, 3 Sep 2003 22:00:45 -0600, Jules Dubois > wrote: > >> (3), and Smalltalk (1); Thursday's vote will be between Java and Python. I >> get the opportunity to learn one or the other in a week. > >If you picked Jython you could all be happy! :-) . . . I'm not sure how seriously others take this sug- gestion. I think it's worth full consideration. Jython is a remarkable achievement, and often addresses requirements more fully than either Python or Java alone. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From gh at ghaering.de Mon Sep 15 03:08:17 2003 From: gh at ghaering.de (=?ISO-8859-15?Q?Gerhard_H=E4ring?=) Date: Mon, 15 Sep 2003 09:08:17 +0200 Subject: pyc2py In-Reply-To: References: Message-ID: <3F656561.6070701@ghaering.de> Thomas Guetttler wrote: > Hi! > > Is there a script which converts compiled python code > to human readable code? > > Google found no result for "pyc2py". Try this keyword: decompyle -- Gerhard From llothar at web.de Wed Sep 17 19:48:57 2003 From: llothar at web.de (Lothar Scholz) Date: 17 Sep 2003 16:48:57 -0700 Subject: ANN: The release of BlackAdder V1.0.0 - this time for real :) References: <3f65f7e6$0$10993$fa0fcedb@lovejoy.zen.co.uk> <6ee58e07.0309170543.354e65b0@posting.google.com> Message-ID: <6ee58e07.0309171548.314a046c@posting.google.com> Ken Godee wrote in message news:... > I downloaded the demo and as far as I can tell it's fully fuctional > Here's a quote from the opening screen...... and heres a quote from the web site. ------------ A demonstration version of BlackAdder can be downloaded at no charge. The demonstration version has the following limitations. You cannot save any changes to Python or Ruby scripts or GUI form designs. There is no HTML documentation. There is no Python Qt extension module. You can download this for yourself from the PyQt/PyKDE homepage. There is no ODBC connectivity. You can download this for yourself from http://www.lemburg.com/files/python/eGenix-mx-Extensions.html. ---- i hope that there support for the program is better then the support for their website. Everything in the last weeks doesn't look very promising. From tdelaney at avaya.com Wed Sep 24 22:24:52 2003 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 25 Sep 2003 12:24:52 +1000 Subject: send email Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DEBF99AB@au3010avexu1.global.avaya.com> > From: Alberto Vera [mailto:avera at coes.org.pe] > > Could you tell me How I can send an email using WIN2000? What do I need? Most people use an email client. Common ones are Outlook, Outlook Express and Eudora. For more information, look here: http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From christoph at mmc-startup.com Mon Sep 22 13:02:10 2003 From: christoph at mmc-startup.com (Christoph Becker-Freyseng) Date: Mon, 22 Sep 2003 19:02:10 +0200 Subject: thread question In-Reply-To: References: Message-ID: <3F6F2B12.8080106@mmc-startup.com> Hi, You can also use threading.Condition() This is useful for having some max. time and additionaly being able t start processing earlier again via cond.notify() Christoph Becker-Freyseng Rolf Wester wrote: > Hi, > > I have an application that starts a second thread, that receives > messages via a socket-server and puts that messages into a queue. The > main thread is polling that queue for new messages. My problem is that > the main thread takes to much of the time polling the empty queue while > the socket-server thread doesn't get enough time for receiving the > messages. Is it possible to force the main threat to sleep for a certain > amount of time or give the socket-server thread a higher priority? > Thanks in advance. > > Kind regards > > Rolf Wester > From kamikaze at kuoi.asui.uidaho.edu Mon Sep 29 08:12:33 2003 From: kamikaze at kuoi.asui.uidaho.edu (Mark 'Kamikaze' Hughes) Date: 29 Sep 2003 12:12:33 GMT Subject: compiling python program References: <3F700543.350E2074@alcyone.com> Message-ID: Erik Max Francis wrote on Tue, 23 Sep 2003 01:33:07 -0700: > Al wrote: >> I'd like to "hide" my code from being viewed (linux). Is there anyway >> for me >> to compile my program into .pyc and only have the .pyc files >> available, or >> do I always have to have the .py file? > You can just provide the .pyc file to clients. But it will only be > runnable by the same version of Python you used to compile it. I did that with the pre-open-source version of Umbra, and it worked fine until Python got a new version; even then, it was just a matter of recompiling it for 2.2 and replacing the zip, on the premise that anyone who was going to run it would have the latest Python. If you have to, you can bundle Python with your program, and even use py2exe to make a Windoze distribution. MacOS X and Linux normally have Python installed, so they don't need as much handholding as Windoze users. -- Mark Hughes "I believe in communication. If I communicate with you every so often, you'll be bothered by what I say enough that you won't ask me to, which means more sleep for me." -Something Positive, 2003Sep22 From joseph at ugcs.caltech.edu Tue Sep 23 19:47:40 2003 From: joseph at ugcs.caltech.edu (John Lin) Date: 23 Sep 2003 16:47:40 -0700 Subject: How to tell if a forked process is done? Message-ID: <879b6a51.0309231547.428214f7@posting.google.com> Howdy, I want to know how to tell if a forked process is done. Actually, my real question is that I want to run a shell script inside of a python script, and after the shell script has finished running, I want to do more stuff *condition* on the fact that the shell script has finished running, inside the same python script. The only way I can think of is to fork a process and then call the shell script, as in: pid = os.fork() if pid == 0: os.execl(shellscript_name.sh, "") but how can I know if the shell script is finished? In sum, my two questions are: 1. How can I know if a forked shell script is finished? 2. How can I run a shell script inside a python script without forking a new process, so that I can know the shell script is done from within the same python script? thanks in advance, John From max at alcyone.com Fri Sep 12 03:41:39 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 12 Sep 2003 00:41:39 -0700 Subject: Cool & Useful EmPy project, prior art? References: Message-ID: <3F6178B3.724ABC0D@alcyone.com> Ville Vainio wrote: > What I'm planning seems to be a pretty "obvious", universally > applicable application of empy (perhaps I should file for a patent if > the EU chooses to shoot itself in the foot? ;-), and am wondering > whether someone has already done such a beast? Perhaps with a GUI, > even... I wouldn't mind doing it myself, it seems like a fun project, > but time == money and something tried & true might already exist out > there... That seems quite reasonable, though I'm not familiar with any other project which does anything similar. (You can ask on the empy-list mailing list to be sure.) It does sound like something that could be generalized to the point of getting its own unique markup, and which would invoke behavior that can be overriden by the user -- i.e., a special markup that says, "This information is needed from the user, please retrieve it." It certainly sounds like a reasonable enhancement proposal that could be made and discussed on the mailing list. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes From __peter__ at web.de Mon Sep 29 11:10:44 2003 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Sep 2003 17:10:44 +0200 Subject: isNumber? check References: Message-ID: Rob Hunter wrote: > How do I check if a value is a number in Python? >>> isinstance(1+1j, (float,int,long,complex)) True Peter From teyc at cognoware.com Mon Sep 8 14:53:52 2003 From: teyc at cognoware.com (Chui Tey) Date: Tue, 9 Sep 2003 04:53:52 +1000 Subject: Great work Message-ID: <3f5cd005$0$6527$afc38c87@news.optusnet.com.au> Tim, Well done. We often have trouble trying to convince them that python is not a "left-field" tool and is suited for mainstream use. The design truely speaks to these people who feel they will not be fired for buying Microsoft or Java. It also speaks to potential developers who see wonderful things are being done with python. It doesn't do much for existing developers, and I don't think it is necessary. When I first started python, python was my browser's home page and then I pretty much moved away from that as the page is far too static. You could have a python developers blog aggregator similar to the one at mechanicalcat. The most disaffected lot in the newsgroups are 1) those who couldn't tell the difference between an image and html 2) people who replace E with 3 in their vocabulary Keep this up. Good things will come from it. Chui From tim.one at comcast.net Tue Sep 16 11:28:58 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 16 Sep 2003 11:28:58 -0400 Subject: Datetime utility functions In-Reply-To: Message-ID: [Paul Moore, finding the end of the month] >> The best solution I could find was >> >> def month_end(dt): >> # Get the next month >> y, m = dt.year, dt.month >> if m == 12: >> y += 1 >> m = 1 >> else: >> m += 1 >> >> # Use replace to cater for both datetime and date types. This >> # leaves the time component of a datetime unchanged - it's >> # arguable whether this is the right thing. >> >> return dt.replace(year=y, month=m, day=1) - datetime.timedelta(days=1) [Christos TZOTZIOY Georgiou] > I sent my own version without having seen your own --and mine might > seem obfuscated, compared to yours. Only a minor suggestion: don't > use dt.replace, use dt.__class__ instead, since you wouldn't want your > function to have side-effects (that is, don't destroy the actual > object that dt is bound to.) It's OK to use replace: datetime and date (also time and timedelta) objects are immutable -- their values can't be changed after initialization. In particular, x.replace() doesn't mutate x. >>> import datetime >>> t = datetime.datetime.today() >>> t datetime.datetime(2003, 9, 16, 11, 26, 16, 810000) >>> t.replace(year=1, month=1, microsecond=42) datetime.datetime(1, 1, 16, 11, 26, 16, 42) >>> t # unchanged datetime.datetime(2003, 9, 16, 11, 26, 16, 810000) >>> From br_y at yahoo.de Tue Sep 9 05:02:07 2003 From: br_y at yahoo.de (Birgit Rahm) Date: Tue, 9 Sep 2003 11:02:07 +0200 Subject: set built-in func_code? Message-ID: Hello newsgroup, I want to set the built-in func_code in my function, how can I does this in the correct way? My books dont tell me anything about this. TIA, Birgit From eppstein at ics.uci.edu Sun Sep 21 20:05:15 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Sun, 21 Sep 2003 17:05:15 -0700 Subject: math.exp(complex) References: Message-ID: In article , "Tim Peters" wrote: > [Tim] > >> Math libraries in general can return a better result for exp(x) than > >> e**x, though, since the latter form uses a machine approximation to e > >> as the base. > > [David Eppstein] > > Doesn't look especially different to me, for the numbers I'm currently > > interested in applying this to (small pure imaginary): > > > > >>> from cmath import * > > >>> exp(1j*pi) > > (-1+1.2246467991473532e-16j) > > >>> e**(1j*pi) > > (-1+1.2246467991473532e-16j) > > There are few shortcuts in numerical analysis. If you want to understand, > and estimate how bad it *might* get over various input ranges, you'll have > to do careful analysis of the implementations. You'll probably find that > very hard, because the Python implementations build on the platform C's > sin(), cos(), exp(), atan2(), pow() and hypot(), and few C vendors document > the accuracy of their implementations -- you don't have the raw material > then to estimate the accuracy and vulnerable areas of Python's > implementations. For that reason, I can't tell you anything that's > generally true across implementations. But you need only glance at c_exp in > cmathmodule.c, and c_pow in compleobject.c, to convince yourself that > c_exp() has far fewer places it can get into numerical trouble (it's a much > simpler algorithm). Ok, thanks for the advice. Looks like exp is the right choice unless there's some strong reason to use powering instead (which there isn't in my situation). -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From __peter__ at web.de Mon Sep 15 19:56:33 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Sep 2003 01:56:33 +0200 Subject: How to instatiate a class of which the name is only known at runtime? References: Message-ID: Tomasz Lisowski wrote: >> import sys >> >> def getClass(classname, modulename): >> try: >> module = sys.modules[modulename] >> except KeyError: >> module = __import__(modulename) >> return getattr(module, classname) > > Hmm... > > Why not write it directly: > > def getClass(classname, modulename): > try: > module = __import__(modulename) > except ImportError: > return None > else: > return getattr(module, classname) > > I have heard, that the __import__ function is smart enough to check the > sys.modules dictionary without actually re-importing the once imported > module. Is it true? > I think you are right with respect to __import__(). However, it's a bad idea to catch the import error. Your client code should have determined the module name beforehand, so that something has gone seriously wrong when you get an ImportError. Returning None instead of a class only confuses the issue (nobody wants to go back to the C habit of checking every function's return value for an errorr code). So: def getClass(classname, modulename): return getattr(__import__(modulename), classname) would be a shorter equivalent to my getClass(). It seems that a lookup in sys.modules is done implicitely by __import__(), as I tested it successfully with "__main__" as the module name. Note that all three versions will not work with submodules, e. g. "os.path", so let's change it one more (last?) time: def getClass(classname, modulename): return getattr(__import__(modulename, globals(), locals(), [classname]), classname) Peter From aleax at aleax.it Fri Sep 26 06:18:41 2003 From: aleax at aleax.it (Alex Martelli) Date: Fri, 26 Sep 2003 10:18:41 GMT Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: <3F71B857.2D1E3268@engcorp.com> <3F720759.34D7BD3E@engcorp.com> <3F720D28.83C3E99@engcorp.com> <3F731B17.61C17B3A@engcorp.com> Message-ID: <5oUcb.124256$hE5.4243917@news1.tin.it> Peter Hansen wrote: ... > I know this won't meet the standard, but what about a use case > involving "actually running (as opposed to debugging) possibly > buggy (non-terminating) code". This could come up in cases such as > our embedded Linux product, which is supposed to be a long-running > process. > > And yes, to make it clear, I am actually suggesting the possibility > that the product could ship with buggy code that could cause that > condition. It does happen in the real world... more often than > anybody normally cares to admit. More often with multi-threaded > applications than is good for anyone, of course. Sometimes, Yep. And even more often, the buggy code will involve race conditions -- unsynchronized access to variables from >1 thread -- which will make you wail long and loud. Which is just part of why using multiple processes, on a platform such as Linux (where forking a process isn't the end of the world in terms of performance), is so often preferable to using multiple threads within a single process: the operating system gives you far better support for isolating faults, ensuring communication between processed DOES go "through the channels", terminating errant processes, and so on, and so forth (as a cherry on top, if you're on a multi-CPU machine you'll also get to exploit all of your CPU's, while Python-coded threaded wouldn't do that:-). I try to limit my multithreaded architectures to VERY simple structures, based mostly on Queue's for inter-thread cooperation. Whenever hairy issues emerge -- I try to move to multi-process architectures instead, at least when I know I will be running on an OS with decent support for processes. Admittedly, that is not _always_ possible (sometimes one does have to run under Windows, for example, with excellent support for threads but rather heavy-weight processes); thus, it IS nice to be able to try and interrupt another thread (it IS just a "try": if the buggy code is looping forewher within a try/except that just keeps looping when you interrupt it, you're hosed anyway -- it still isn't anywhere as solid as a multi-process architecture). Remember, I was among the *paladins* of the new functionality;-). However, I do think it's crucial that it be used only as a very last resort, NOT in the 99.99% of cases which are best covered by other architectures... > Yes, I'm reaching somewhat. Although I actually would like that > feature, even if it were available it would be quite some time > before implementing it would be high enough on the list of priorities > to bother. And wait! It _is_ available, just not directly, so I > can hardly complain. :-) > > Point mostly taken... Sure, we did end up having the feature -- just a fingerbreadth away from the average programmer's reach;-). Anybody who truly really needs it IS doing stuff much more complicated than average, anyway;-). Alex From skip at pobox.com Tue Sep 2 12:00:58 2003 From: skip at pobox.com (Skip Montanaro) Date: Tue, 2 Sep 2003 11:00:58 -0500 Subject: MySQLdb -- any way to get "rows matched"? In-Reply-To: References: Message-ID: <16212.48826.261354.258950@montanaro.dyndns.org> Chris> When issuing updates in mysql (in the console window), mysql will Chris> tell you if any rows matched and how many rows were updated (see Chris> below). I know how to get number of rows udpated using MySQLdb, Chris> but is there any way to get the number of rows matched? I believe the return value of the cursor's execute() method gives you the number of rows which matched. Skip From rdsteph at earthlink.net Thu Sep 11 23:39:08 2003 From: rdsteph at earthlink.net (Ron Stephens) Date: 11 Sep 2003 20:39:08 -0700 Subject: Computer Programming for Everybody, a Newbie Project Message-ID: <8e6e8e5d.0309111939.4f1bf1d7@posting.google.com> As most of you know, the founder and creator of Python has stated an interest in bringing the joys of computer programming to a wider audience, and he has coined the phrase "Computer Programming for Everybody" to sort of sum up this concept. I fit in this category, for prior to about 3 yrs ago, my programming experience and knowledge was next-to-none. After 3 yrs of enjoying Python as a hobby in my limited spare time, I have created a program, which I call askMerlin, that is simple enough for a newbie to understand, yet interesting and different. Having greatly cleaned up the original code, the basic program is now a class Decision() that allows one to simply analyze any decision one needs to make. The other modules are subclasses of Decision() and are sort of ultra-mini expert systems on how to decide what to eat for lunch, who to vote for in an election, how to predict who will win a given basketball game, football game, and how to answer yes or no type questions. The last two modules apply the same technique but also utilize the internet to gather data used to analyze and make decisions. I think it is a fun little program. Newbies can not only understand it, but can add simple modules, in any area of their expertise, by simply subclassing Decision(), or by simply creating an instance of Decision and over-riding a few key methods, or perhaps more simply by imitating the functional logic. OK, that's my spiel. The program can be found at my web site at http://www.awaretek.com/plf.html Ron Stephens, humbly-yet-fearlessly-treading-where-he-ought-not-ly-yours P.S. of course I am still adding to this program, especially the internet-enabled part, and welcome ideas / contributions from any and all, especially relative newbies who need a place to start. P.S.S. to Newbies, the best way to understand this program is just to run it a few times. It is a command line program, and although I have cleaned up the code, I also removed for the time being the documentation and comments, that were becoming unwieldy after three years of fiddling. I think the code speaks for itself, especially after you run it a few times and see how it works. And yes, I do intend to add some simple comments back into the code ;-))) eventually. Also, I apologize in advance for any indentation errors anyone has after downloading or cutting and pasting the code; just run the program and let the Python error messages help you sort out any formatting or indentation errors you may encounter. The basic idea is to choose between a few options or alternatives, by basing your choice on a few good criteria, with each criteria having a weight, or relative-importance-factor, and then, by various means, determining a score for each option on each criteria. There, that's the documentation for now ;-))) And lastly, yes, I do realize it isn't much to show for three years of part time work, but hey, I give me A's for persistence. Ron Stephens From robin at jessikat.fsnet.co.uk Tue Sep 23 02:08:21 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 23 Sep 2003 07:08:21 +0100 Subject: working png output from graphing modules References: <983dac9b.0309221905.1960cf02@posting.google.com> Message-ID: In article <983dac9b.0309221905.1960cf02 at posting.google.com>, john writes >Are there any charting or graphing modules for python that can write >PNG, JPEG, or GIF graphics? I have found a couple of nice looking >packages that can make beautiful postscript, PDF, or SVGs (PyChart and >ReportLab) but they can't make PNGs, GIFs, or JPEGs. (On my Solaris >machine with Python 2.2 they don't.) Or are there any simple UNIX >filters to convert SVG, PDF, or ps files to PNG? ReportLab certainly makes png/gif/jpeg, but only if you build the _renderPM extension and also PIL. I know that's possible with solaris 8 as I have done it myself, but haven't done much with later versions. There's also a requirement to get appropriate T1 font files. -- Robin Becker From giles_brown at hotmail.com Mon Sep 15 17:07:22 2003 From: giles_brown at hotmail.com (Giles Brown) Date: 15 Sep 2003 14:07:22 -0700 Subject: Win32 Com + ADO: How to compare the result of a recordset to 'nothing' References: Message-ID: <57de9986.0309151307.2801b554@posting.google.com> "Felix McAllister" wrote in message news:... > Hi, > When using win32com.client, how do you test for a 'nothing' com object as you can in VB? I have an example here when using ADO to loop over multiple recordsets returned from a query. I get the following error: > > Traceback (most recent call last): > File "C:\dev\python\MySamples\dbtest.py", line 14, in ? > rs.MoveFirst() > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", line 460, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: .MoveFirst > > I'm assuming that after the result of rs.NextRecordSet is invalid somehow (it shouldn't be, BTW, as a similar loop runs fine in VB). > > In Perl, I'd just use : if (defined($rs).... > > Any help appreciated, This is just a guess, but is it anything to do with NextRecordset returning a tuple (recordset, records affected)? (Don't think that should end up being wrapped in a win32com.client.dynamic wrapper though?) You could try putting some print statements into win32com.client.dynamic to see exactly what you're getting back. Good luck, Giles Brown From FBatista at uniFON.com.ar Mon Sep 1 09:55:05 2003 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 1 Sep 2003 10:55:05 -0300 Subject: Overloading objects Message-ID: In others languages I can do (using sintaxis of Python): def myMethod (self, name): self.name = name def myMethod (self, name, age): self.name = name self.age = age If I'm not wrong, this is "Method Overloading". I thought using defaults: def myMethod (self, name, age=None): self.name = name if age not None: self.age = age but I'm concerned about the scalability of this. What's the most pythonic way to do this? Using something like *args or **args? Thank you! . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lars_news at larsshack.org Mon Sep 8 08:40:39 2003 From: lars_news at larsshack.org (Lars Kellogg-Stedman) Date: 8 Sep 2003 05:40:39 -0700 Subject: MacOS/NeXTStep propert list parsing? Message-ID: <57f2d810.0309080440.21eae97a@posting.google.com> Howdy, I've been trying to find a Python module for parsing the non-XML PropertList format used in MacOS X (this is what Apple's docs refer to as "ASCII format" property lists). I've sound one or two parsers for the XML format, but nothing that parses the legacy format. I was hoping someone here had written (or was aware of) a parser for the older style. Thanks, -- Lars From domma at procoders.net Mon Sep 22 08:38:57 2003 From: domma at procoders.net (Achim Domma) Date: Mon, 22 Sep 2003 14:38:57 +0200 Subject: How to catch socket timeout? References: Message-ID: "Bob Halley" wrote in message news:mailman.1064178330.17024.python-list at python.org... > So, all you need to do is put the socket.timeout except clause before > any socket.error clause: > > try: > self.data = self.page.read() > except socket.timeout: ... > except socket.error,e: ... Thanks, that works fine, but I don't understand why the exception was not catched in my case. If I write it like this try: self.data = self.page.read() except socket.error,e: ... except socket.timeout: ... the exception should be catched by the socket.error handler. Or am I wrong? In my case it was not catched at all. Very mysterious from my point of view, but it works now. Achim From mpeuser at web.de Sat Sep 6 03:26:44 2003 From: mpeuser at web.de (Michael Peuser) Date: Sat, 6 Sep 2003 09:26:44 +0200 Subject: I need a little help with Tkinter Entry widget References: <221e7b06.0309051235.2d5b4868@posting.google.com> <221e7b06.0309051816.4b514614@posting.google.com> Message-ID: "Phil Schmidt" schrieb im Newsbeitrag news:221e7b06.0309051816.4b514614 at posting.google.com... > Oh! Seems obvious when you say it! I've been using the Fredrik Lundh > documentation, and saw nothing about those. Perhaps I should follow > the recommendations of other posters and get that book about > Tkinter... > Have alook at New Mexico Tech http://www.nmt.edu/tcc/help/pubs/lang.html There are two very concise as well as comprehensive documents. Kndly Michael P a.. Python 2.2 programming language quick reference, 46 pp. [HTML] [PostScript] [PDF] b.. Tkinter reference: a GUI for Python, 84 pp. [PostScript] [PDF] From wtrenker at shaw.ca Fri Sep 5 16:30:58 2003 From: wtrenker at shaw.ca (William Trenker) Date: Fri, 05 Sep 2003 20:30:58 +0000 Subject: in Ram database? In-Reply-To: References: Message-ID: <20030905203058.179d9630.wtrenker@shaw.ca> On Thu, 04 Sep 2003 19:14:05 -0700 "John D." wrote regarding in Ram database?: > Does anyone know if there is an "in-ram" dictionary based database > for Python. This may not be quite what you want, but the SQLite embedded SQL engine has an in-memory option. You would access SQLite using the PySQLite wrapper which is DB-API-2 compliant. Here are the links: http://sqlite.org (download the latest version 2.8.6) http://pysqlite.sourceforge.net Cheers, Bill Here is a simple example: import sqlite #module name exposed by the PySQLite wrapper conn = sqlite.connect(db=':memory:') #special connect string to open an in-memory db cursor = conn.cursor() #standard DB-API-2 from this point cursor.execute('create table test (a varchar, b int);') cursor.execute('commit;') #end PySQLite implicit transaction cursor.execute('begin transaction;') #wrap the inserts in an explicit transaction for speed for i in range(0,10000): cursor.execute('insert into test (a,b) values (%s,%i);'%(str(i),i)) cursor.execute('commit;') cursor.execute('select sum(b) from test;') print cursor.fetchall()[0][0] From usenet_spam at janc.invalid Tue Sep 16 20:17:42 2003 From: usenet_spam at janc.invalid (JanC) Date: Wed, 17 Sep 2003 00:17:42 GMT Subject: RAD with Python References: <17d520f6.0309120509.491e4d7c@posting.google.com> <17d520f6.0309130701.222d09fe@posting.google.com> <17d520f6.0309152035.7e65635b@posting.google.com> Message-ID: ubaidullahnubar at hotmail.com (Ubaidullah Nubar) schreef: > I have been working through some wxPython examples. When external > resources like icons or images are used on a control, is there a way > to embed it into the freezed executable? Look at img2py.py in the wxPython/tools directory. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From oblivious at web.de Fri Sep 26 05:17:25 2003 From: oblivious at web.de (Dominic) Date: Fri, 26 Sep 2003 11:17:25 +0200 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) In-Reply-To: <3F7347A9.216B8EE@engcorp.com> References: <3F71B857.2D1E3268@engcorp.com> <3F720759.34D7BD3E@engcorp.com> <3F720D28.83C3E99@engcorp.com> <3F731B17.61C17B3A@engcorp.com> <3F7347A9.216B8EE@engcorp.com> Message-ID: Peter Hansen wrote: > Dominic wrote: > >>Besides with Pyrex it's 2-4 lines to access >>PyThreadState_SetAsyncExc from Python :-) > > > Posting those 2-4 lines would be helpful to those searching the archives > at a later date. ;-) Sure, here they are: cdef extern int PyThreadState_SetAsyncExc(long id, obj) def interrupt(id, obj): PyThreadState_SetAsyncExc(id, obj) > > -Peter From __peter__ at web.de Tue Sep 23 06:25:28 2003 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Sep 2003 12:25:28 +0200 Subject: import pickle succeeds only after two tries?? References: <1064307542.783575@blaat.sara.nl> Message-ID: Bram Stolk wrote: > I am using python-2.2.2 on linux-ARM. > Python itself works OK. > However, importing pickle gives me *very* strange results: > > The first 'import pickle' fails with "ImportError: No module named > StringIO" If I immediately do a second 'import pickle', it works???? The first import puts the module into sys.modules, then executes it. I execution succeds, the module object is assigned to a variable in the current global namespace, if it fails, no such assignment is performed. The second import tries to find the module in sys.modules, finds it and therefore does not execute it again. The effects are strange, for example: --- test.py --- def alpha(): pass print unknown def beta(): pass --- end test.py --- >>> import test Traceback (most recent call last): File "", line 1, in ? File "test.py", line 5, in ? print unknown NameError: name 'unknown' is not defined >>> import test >>> dir(test) ['__builtins__', '__doc__', '__file__', '__name__', 'alpha'] >>> Note that beta() is missing while alpha() is there. I doubt that this behaviour is intentional. Peter From ulysses_dm at yahoo.com.cn Thu Sep 11 05:16:28 2003 From: ulysses_dm at yahoo.com.cn (ulysses) Date: 11 Sep 2003 02:16:28 -0700 Subject: ANN: PyQt v3.8 Released References: Message-ID: <43e3984e.0309110116.18b9d065@posting.google.com> Phil Thompson wrote in message news:... > On Monday 18 August 2003 2:59 am, John Taylor wrote: > > Phil, > > > > Does PyQT support the ability to minimize an app to the lower right > > tray, next to the clock? If so, could you please post some example > > code? > > What platform? > > If you mean Windows then QApplication.winEventFilter() and QWidget.winEvent() > were added to PyQt v3.4 at the specific request of somebody who wanted to do > this. Sorry, but I don't have example code. > > Phil I find QT have a trayicon example in C++, I study it. But I can't convert it to python . Can you give some advice. Thanks. From gerrit at nl.linux.org Tue Sep 30 15:19:04 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 30 Sep 2003 21:19:04 +0200 Subject: where are the "class variables"? In-Reply-To: <62e9c66e.0309301057.65f24a3b@posting.google.com> References: <62e9c66e.0309301057.65f24a3b@posting.google.com> Message-ID: <20030930191904.GA6988@nl.linux.org> Dominik Kaspar wrote: > i'm used to java and its strict way of defining variables. so how is > it possible to reach something like a class variable in python? > with the following code i didn't have much succes... > > class Server(threading.Thread): > running = 0 (??) > > def run(self): > running = 1 > while running: > print "do something here..." > > def exit(self): > running = 0 This is where self is for: self.running refers to the class variable 'running'. Gerrit. -- 249. If any one hire an ox, and God strike it that it die, the man who hired it shall swear by God and be considered guiltless. -- 1780 BC, Hammurabi, Code of Law -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From skip at pobox.com Mon Sep 8 16:38:34 2003 From: skip at pobox.com (Skip Montanaro) Date: Mon, 8 Sep 2003 15:38:34 -0500 Subject: Eureka! (Re: Comments on Python Redesign) In-Reply-To: <200309072018.05589.dave@pythonapocrypha.com> References: <3F5CD10B.2020709@teksavvy.com> <200309072018.05589.dave@pythonapocrypha.com> Message-ID: <16220.59594.270770.188253@montanaro.dyndns.org> Dave> I don't know of any problem with tinyurls - *any* server can Dave> provide a "bad" redirect; as with any URL whether or not you Dave> follow it depends on the context and on how much you trust the Dave> sender. The only other reasons I could think of to object to tiny urls are: * Perhaps the tinyurl folks are not trustworthy (are they keeping track of your browsing habits and selling that info?). That seems unlikely, since they don't appear to be storing cookies in my browser. * The tinyurl website can become a bottleneck, preventing people from getting where they want to go. The tinyurl.com website seems to be fairly unreachable for me at the moment, though this is the first time I've seen this, and it appears to be a problem more with Northwestern's connection to the net than tinyurl.com's. * There's no guarantee tiny urls will remain unique or even available for long periods of time. Their current practice of using four lower-case letters suggests they have space for about 450,000 unique URLs before extending to a fifth letter. Skip From fuerte at sci.fi Mon Sep 8 15:39:20 2003 From: fuerte at sci.fi (Harri Pesonen) Date: Mon, 08 Sep 2003 22:39:20 +0300 Subject: Why the 'self' argument? In-Reply-To: References: <3f58a2bd$0$156$a1866201@newsreader.visi.com> <3f58b1f6$0$155$a1866201@newsreader.visi.com> <3f5a2260$0$166$a1866201@newsreader.visi.com> Message-ID: <7T47b.4753$ZB4.113@reader1.news.jippii.net> John Roth wrote: > "Harri Pesonen" wrote in message > news:TRr6b.4056$ZB4.1410 at reader1.news.jippii.net... > >>Grant Edwards wrote: >> >>>In article , Harri Pesonen > >>>>I agree, it's not logical. I'm learning Python at the moment, and like >>>>it very much. This "self" thing seems to be the only odd feature, >>> >>>It seemed quite natural to me, but perhaps that's because I'd >>>used other languages that worked the same way. Coming from >>>Modula-3 and Smalltalk, the way classes worked in Python seemed >>>quite intuitive. >>> >>>OTOH, C++ seems like a real non-intuitive mess to me. >>> >>>>it feels like the whole class feature was added later. >>> >>>Why? >> >>Because everything else in Python seems to be very compact, there are no >>variable type declarations, or variable declarations, or anything else >>unnecessary that can be omitted. I would like to have self omitted, it >>would make the class syntax more beautiful and compact. On the other >>hand, I would like to have real private methods. >> >>Also I think that the class members should be explicitly declared. In >>general, it would be nice to have an option (like Option Explicit in >>Visual Basic) so that you can't assign to variables that have not been >>declared. It would probably make Python less error prone. > > I believe that is what __slots__ is for. That's run time rather than > compile time, but at least it gives you the error on the statement > that attempts to do an invalid assignment. Thanks guys, I hadn't heard of __slots__ before. Perhaps I am reading a too old book. Of course, a compile time check would be better... >>Also if >>variable declarations could have the type, again some errors could be >>detected at compile time. > > It's quite possible to add run time type checking to Python, at a > significant cost in performance. See the descriptors material. I think that Python already has run time type checking. It does not allow "a" + 1, for example. > There's been quite a bit of work on a compile time type checking > system over the years, but it has never resulted in a proposal that could > be agreed on. It would be quite simple to have "option explicit" like in Visual Basic, I believe. Like the following: option explicit var a = "asdf" b = 1 # error at compile time a = 123 (var b, var c, var d) = (1, 2, 3) e = "asdf" # error at compile time Always have "var" keyword before first assignment. Just a proposal. You don't need __slots__ (which sounds like a hack): class A(object): var a, var b, var c # instead of __slots__ = ['a', 'b', 'c'] foo = A() foo.a = 1 foo.b = 2 foo.c = 3 foo.d = 4 # error at compile time > My own personal opinion is that I like the type check system in > the ML family of languages: it stays out of your way unless you need it. > How that would fit in Python is another question, though. > At this time, it looks like an issue for Python 3.0, which seems to > keep receeding into the distance. I think that the type checking is not so important, but you could have it as well: var a as str = "asdf" var b as int = 123 var c as float = 123.4 a = 123 # error at compile time # also at run time if not detected earlier var d = "asdf" d = 123 # ok, because no type was defined Harri From peter at engcorp.com Wed Sep 24 17:31:20 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 24 Sep 2003 17:31:20 -0400 Subject: sending thread exceptions (was Re: RELEASED Python 2.3.1) References: <3F71B857.2D1E3268@engcorp.com> <3F720759.34D7BD3E@engcorp.com> Message-ID: <3F720D28.83C3E99@engcorp.com> Peter Hansen wrote: > > > Peter Hansen wrote re: > > > PyThreadState_SetAsyncEnc > Is this function available in a DLL somewhere? I can't find even > a single reference to that name anywhere in the Python23 directory > tree on Win32 after a fresh install. Skip that question....of course, python23.dll goes into c:\windows\system so it wasn't where I was searching... I'd still be very interested in examples of use through ctypes (with which I'm not yet familiar). Alex' slides were interesting, but I think they might reflect a subtle trend away from Python's traditional treatment of programmers as consenting adults, with all the concern about newbies and the hints that such a dangerous feature will be abused to no end. The slides also suggest that there are almost no use cases whatsoever for such a feature, though admitting there might, just barely, be enough to merit adding it as a non-newbie C-only API which one has to jump through hoops (or use ctypes :-) to access. I can think of several use cases right off the top of my head, one of them being while running automated unit and acceptance tests, to ensure that a test involving threads will complete (generally with a failure in this case) even if the code is broken and the thread cannot be terminated. -Peter From stephan.diehl at gmx.net Thu Sep 4 12:53:08 2003 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Thu, 04 Sep 2003 18:53:08 +0200 Subject: basic language question References: Message-ID: Daniel Dittmar wrote: > Stephan Diehl wrote: >> Once in a while, I get bitten by the fact, that mutating list methods >> such as 'append' or 'extend' return None instead of the (mutated) >> list itself. Is there a compelling reason for that? I googled around, >> but didn't find anything about this. >> Thanks >> >> Stephan > > The reasons described for sort () > -sorted-list> also apply to append and extend. Thanks for the link. I don't find the given reason really compelling, though. (but that's mine, not your problem) > > Daniel Stephan From dave at 3dex.com Wed Sep 10 15:02:24 2003 From: dave at 3dex.com (Dave Benjamin) Date: Wed, 10 Sep 2003 19:02:24 GMT Subject: Problems with setting up mod_python and Apache References: <3f5f6b41$0$239$fa0fcedb@lovejoy.zen.co.uk> Message-ID: <4zK7b.11532$NW3.6643@news1.central.cox.net> "John Dean" wrote in message news:3f5f6b41$0$239$fa0fcedb at lovejoy.zen.co.uk... > I have set up httpd.conf according to installation and configuration > instructions in the mod_python documentation. Yet when I enter the following > URL http://localhost/test.py all I get is an Apache view of my htdocs > directory. They if I click on test.py and open file dialog pops up. If I > give the file a cgi extension and enter the following URL > http://locathost/test.cgi it runs fine. I just can't figure out what I am > doing wrong. Sounds like a configuration problem. Can you post the relevant lines from your httpd.conf file? Are you trying to write handlers or are you using the publisher module? Dave From skip at pobox.com Fri Sep 12 15:50:21 2003 From: skip at pobox.com (Skip Montanaro) Date: Fri, 12 Sep 2003 14:50:21 -0500 Subject: why is this failing? In-Reply-To: <87ad9am70z.fsf@pobox.com> References: <9x58b.139$u07.2@newsread1.news.atl.earthlink.net> <3F60E645.2501B9EE@engcorp.com> <3f60ea13$0$42053$a1866201@newsreader.visi.com> <87llsu6hij.fsf@pobox.com> <3F611490.23E27E1B@alcyone.com> <87ad9am70z.fsf@pobox.com> Message-ID: <16226.9085.306930.156474@montanaro.dyndns.org> John> Just to check (I'm using a patched version, so it's a bit of a John> pain to switch): the latest versions from the python-mode SF John> project highlight builtins like "len" and "list", not just John> keywords like "print"? I'm running 4.38. Here are the keywords it knows about: "and" "assert" "break" "class" "continue" "def" "del" "elif" "else" "except" "exec" "for" "from" "global" "if" "import" "in" "is" "lambda" "not" "or" "pass" "print" "raise" "return" "while" "yield" So, no, the builtins are not colored, just the keywords. You could easily extend the list though. Skip From bgailer at alum.rpi.edu Mon Sep 8 08:43:05 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 08 Sep 2003 06:43:05 -0600 Subject: Read file that starts with '\xff\xfe' In-Reply-To: <3F5C7270.1020001@ghaering.de> References: <3F5BD4DD.57D90AF5@alcyone.com> <3F5BFC19.D098115B@alcyone.com> <6.0.0.22.0.20030908054530.03c42dd8@66.28.54.253> <3F5C7270.1020001@ghaering.de> Message-ID: <6.0.0.22.0.20030908063849.03c99d78@66.28.54.253> At 06:13 AM 9/8/2003, Gerhard H?ring wrote: >Bob Gailer wrote: >>On Win 2K the Task Scheduler writes a log file that appears to be >>encoded. The first line is: >>'\xff\xfe"\x00T\x00a\x00s\x00k\x00 >>\x00S\x00c\x00h\x00e\x00d\x00u\x00l\x00e\x00r\x00 >>\x00S\x00e\x00r\x00v\x00i\x00c\x00e\x00"\x00\r\x00\n' > >I wrote that into a file, and used the 'file' utility from Cygwin, which >tells me: > >$ file t >t: Little-endian UTF-16 Unicode character data, with CR line terminators That's a good start. I presume I need to use codecs.open(filename, mode[, encoding[, errors[, buffering]]]) to read the file. What is the actual value of the "encoding[" parameter for "Little-endian UTF-16 Unicode character data, with CR line terminators" Bob Gailer bgailer at alum.rpi.edu 303 442 2625 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003 From rhunter007 at yahoo.com Tue Sep 16 16:24:30 2003 From: rhunter007 at yahoo.com (Rob Hunter) Date: Tue, 16 Sep 2003 13:24:30 -0700 (PDT) Subject: Is there "let binding" in Python? In-Reply-To: <8D8126DA-E882-11D7-973E-003065F081D2@zephyrfalcon.org> Message-ID: <20030916202430.56387.qmail@web40909.mail.yahoo.com> > > > Well, yeah. And that's a good thing, right? > I > > mean, perhaps not in general, but certainly > in > > this case I think everyone can agree that it > is > > *assignment* which creates the confusing > issue of > > all buttons being named 10. > > Depends on how you look at it: > > [Jeff's example code] > def make_stupid_gui(): > t = Tk() > for i in range(10): > b = Button(t, text="Button #%d" % i, > command=lambda: button_func(i)) > b.pack() > make_stupid_gui() > > The reason that you get surprising results, is > that the i in > button_func(i) isn't evaluated until that piece > of code is actually > called. When it's called, it looks at the > value that i has *at that > moment*. The value it had when the button and > the lambda were created, > is not stored anywhere, so it cannot be used. I don't *think* that's correct (though I could be wrong). What you're describing is "dynamic scoping". That's where the body of a function (or code block in this case) isn't evaluated until it is used. And thus, free variables in the body assume whatever values their calling environment has. Dynamic scoping is a bad thing. So bad, in fact, that lisp added (at least the option of, I think) static scoping, Scheme exclusively uses static scoping, and that Python corrected their mistake (it used to be dynamically scoped). But anyway, from my tests, and from what I've read, Python has static scoping, but what assignment allows you to do is violate, in a way, this static scoping, which is what we see here. Rob __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From jjl at pobox.com Mon Sep 29 10:56:03 2003 From: jjl at pobox.com (John J. Lee) Date: 29 Sep 2003 15:56:03 +0100 Subject: [ANN] pylint-0.2 References: Message-ID: <87lls73apo.fsf@pobox.com> "Peter Milliken" writes: [...] > One nice thing that has happened is it has led me to the Optik package [...] Optik is now in 2.3 standard library, renamed as the optparse module. John From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Sat Sep 27 16:20:58 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Sat, 27 Sep 2003 21:20:58 +0100 Subject: Slice inconsistency? References: <10c662fe.0309261245.1f35f43a@posting.google.com> <10c662fe.0309270545.1fd5d839@posting.google.com> <7tidnd_LS5ElWOiiU-KYvQ@comcast.com> Message-ID: On Sat, 27 Sep 2003 16:00:39 -0400, "John Roth" wrote: >So you're basically passing something to __getitem__() >that nobody thought about, and expecting it to work. >It sounds like something I might like to use some day >myself, but it's not going to suddenly appear by magic. > >Submit a PEP. For what? - new style classes already do what I (and apparently Roberto) would expect. I don't care if old style classes act in a backward-compatible rather than idealistic way - that is what old style classes are for. All Roberto needs to do is make his class a subclass of object and it will do exactly what he needs - somebody did think about it and that PEP has apparently already been submitted and implemented a long time ago. -- Steve Horne steve at ninereeds dot fsnet dot co dot uk From rparnes at megalink.net Thu Sep 11 22:02:37 2003 From: rparnes at megalink.net (Bob Parnes) Date: Fri, 12 Sep 2003 02:02:37 -0000 Subject: Trouble Learning Zope References: <3F5FCD3A.ACB83234@engcorp.com> Message-ID: On Wed, 10 Sep 2003 21:17:46 -0400, Peter Hansen wrote: > Bob Parnes wrote: >> >> I just installed zope, version 2.6.1-10 on a debian distribution, but I >> cannot get to second base. When I try to add the tutorial to a folder, I >> get an error message stating that an emergency user cannot own an >> object. So I clicked onto the help page and found the tutorial there. >> But I got the same error when I tried to follow it. Then I created a new >> user account and restarted zope. But it would not accept a login as the >> new user, only as the original, 'emergency' user. As things stand, I can >> bring up zope on my browser but cannot do anything in it. >> >> What can I do to straighten things out. Thanks for any help. > > 1. When you create the new user, make sure you've set it up for "manager" > privileges. > > 2. Subscribe to the zope mailing list, as this newsgroup does relatively > little support for Zope while the mailing list is the place to be... > (see the Zope web site to subscribe). > > -Peter Thanks, I'll do that. -- Bob Parnes rparnes at megalink.net From kern at taliesen.caltech.edu Mon Sep 1 01:50:21 2003 From: kern at taliesen.caltech.edu (Robert Kern) Date: Mon, 1 Sep 2003 05:50:21 +0000 (UTC) Subject: Python Documentation? References: Message-ID: In article , "Daniel R. Smorey Jr." writes: > I'm looking for a good place for Python documentation. I'm really lost > on why it's so hard to find anything when it comes to me looking up a > particular function in Python. My example would be the split() function > of the string module. Why can't I just go to www.python.org and click > on Search and then type in split and it bring me to the split() function > of the string module? Well, since you know which module the function is in, you can go to the documentation page, look up string in the Global Module Index and find split(). Only a few more clicks. Or, even easier, you can fire up the interpreter, and do the following: >>> import string >>> help(string.split) Or, on the commandline, type pydoc string.split > Why does it have to be so hard? This is what I > get when I search for split on www.python.org... > > http://search.python.org/query.html?qt=split&col=ftp&col=python&col=peps&col=starship > > Most of those hits are for the re module, not the string module (which > in my opinion should be part of python and not a module, but I digress). Most of them are since 2.0. Check out string methods. http://python.org/doc/current/lib/string-methods.html > Why would it not bring up the split function of the string module > first and foremost? Because no one has asked for it to do so before? Because the unpaid volunteers with limited time who run the site don't need the feature themselves and never realized that others might want it? Because the string method and re function split() are equally good or better options to return first? Although I agree that there should be a checkbox option to search only the current docs. -- Robert Kern kern at caltech.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mack at incise.org Tue Sep 23 19:57:03 2003 From: mack at incise.org (Nick Welch) Date: Tue, 23 Sep 2003 18:57:03 -0500 Subject: How to tell if a forked process is done? In-Reply-To: <879b6a51.0309231547.428214f7@posting.google.com> References: <879b6a51.0309231547.428214f7@posting.google.com> Message-ID: <20030923235703.GB5048@incise.org> You can just do os.system("some command"), it will block until the shell command is done, and return the exit code. If you need more control, perhaps look into the popen2 module and the Popen3/4 classes inside it. -- Nick Welch aka mackstann | mack @ incise.org | http://incise.org Help stamp out and abolish redundancy. From simonb at webone.com.au Mon Sep 29 20:15:24 2003 From: simonb at webone.com.au (Simon Burton) Date: Tue, 30 Sep 2003 10:15:24 +1000 Subject: Wavelet package available? References: <2ceb70f8.0309290136.118a856d@posting.google.com> Message-ID: On Mon, 29 Sep 2003 23:03:44 +0200, gez wrote: > Why this stupid answer? I tried to find python in combination with wavelets, > both in the normal Google search engine and the Google groups search. Also > jpython/jython, etc. but non of the results was what I wanted to use. So, > that is why I posted it here. Think this is exacly the place to be... > Yeah. I remember the last wavelets post on c.l.py, not that long ago, and no one had any thing to say. I am interested in python as a matlab (maple, gap etc.) killer - more math stuff anyway.. Anyway, if you know of a nice C wavelet lib, it should only take a few days to wrap - maybe i can help. I'm also keen to try pyrex on something. Simon Burton. From $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk Wed Sep 10 14:04:40 2003 From: $$$$$$$$$$$$$$$$$ at $$$$$$$$$$$$$$$$$$$$.co.uk (Stephen Horne) Date: Wed, 10 Sep 2003 19:04:40 +0100 Subject: Pass-by-reference : Could a C#-like approach work in Python? References: <4l7ulv4h3ik4bt3rj5kohgm7gfq5pruo1t@4ax.com> <3f5f3667$1@news.highway1.com.au> Message-ID: On Wed, 10 Sep 2003 22:39:23 +0800, Tim Hoffman wrote: >Hi Stephen > >The bit I can't fathom is why you would want to do this ? >At least in the case of the simple example you give. It wasn't intended as a real world example - it was only intended to illustrate what I want to be able to do. >When you call inc function you are taking an immutable object 1 and >creating a new object which is the result of adding 1 to 1. And what you >are then asking it to rebind the variable x to point to the new int >object 2 inside the function. Yes - that is exactly it. To rebind the callers variable/whatever that supplied the parameter from within the function. >Why you would want to do this is unclear. Secondly if it where a more >abstract object it would have an increment method which you could call >on the object which was passed to the function. No, you are taking the noddy example too literally. For a more realistic (but still simplified) example, see my reply to Peter Ottens post. From achrist at easystreet.com Fri Sep 5 18:16:31 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 05 Sep 2003 15:16:31 -0700 Subject: newbie question on which win32 GUI to choose References: Message-ID: <3F590B3F.35A7B5E6@easystreet.com> John Hunter wrote: > > Cameron> experience inclines me to the former. I've found pyGTK > Cameron> too immature under Win*. The people who claim success > Cameron> with it are, from what I can tell, those who benefit from > Cameron> consider- able prior GTK+ work. -- > > I haven't found this. I've written two applications in pygtk2 ... Are there any downloadable pygtk2 apps that are a good demo, ie non-esoteric showoff apps that I can download and run under Windows to see how it runs on my machine? Al From Dick.Zantow at lexisnexis.com Tue Sep 9 14:28:19 2003 From: Dick.Zantow at lexisnexis.com (rzed) Date: Tue, 9 Sep 2003 14:28:19 -0400 Subject: Comments on Python Redesign References: Message-ID: Graham Fawcett wrote: > Nick Vargish wrote in message > news:... >> I really like the idea of the PSF selling boxed python distros for >> around $300. People who make the business decisions _like_ spending >> money on a product -- it's somehow comforting to them. Include >> bound copies of the Tutorial and Library Reference, to give the >> box some weight and make it clear that they are paying for >> something more than a CD of "free software". (Spiral bound >> documents, please!) >> >> I'm hoping that my boss will be shelling out for some Komodo Pro >> licenses, partly for the above reason. The other part of the >> reason is that once money is spent on something, it becomes more >> entrenched in an organization. This will serve to counter the PHB >> attitude that "if it costs nothing to bring in, it will cost >> nothing to throw out." > > We bought Komodo licences for the same reason. ActiveState has been > a great friend to us, though we've never been introduced; they > certainly deserve a few bucks. And yes, I'd get our dept. to > purchase PSF distros as well for the same reason. > > Lulu, if you're reading this: if you manage to sell any Gnosis boxed > sets, would you mind sending me a little share, in thanks for coming > up with the idea? I need a new canoe myself. ;-) > > -- Graham Speaking of actual value-added products, one thing I'd pay for would be packaged CDs containing not only the base Python distro, but also other packages (like pygame, wxPython, Boa Constructor, etc.) -- all of the *right* version to work with that version of Python. It would make initially loading a clean machine simpler (especially for those of us with slow modems) than downloading the many packages individually and trying to assure version compatibility. The result would be a useful set of CDs that would be worth hanging onto. Over time, after many upgrades, it might seem pointless to keep old versions, until that one package shows up that requires an environment from three releases back. I have no idea how the licensing would work on such a thing, but it would seem worthwhile for the Python community to figure out how to make it work. -- rzed From aahz at pythoncraft.com Thu Sep 4 09:19:05 2003 From: aahz at pythoncraft.com (Aahz) Date: 4 Sep 2003 09:19:05 -0400 Subject: Threading and Sockets Problem References: Message-ID: In article , Chris wrote: > >For some reason, I can only connect to my server once. After that, I >keep getting 'connection refused 111' messages). http://mail.python.org/pipermail/python-list/2001-August/062410.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz From cliechti at gmx.net Tue Sep 16 15:40:29 2003 From: cliechti at gmx.net (Chris Liechti) Date: 16 Sep 2003 21:40:29 +0200 Subject: distutils on win32 with link.exe -- use dlls? References: Message-ID: David Bolen wrote in news:u65jssiml.fsf at fitlinxx.com: > John Hunter writes: > >> Is there a macro or compile flag or other setting to inform distutils >> to look for the DLLS of the required libraries rather than the *.lib >> files? > > Under Windows, even if your resultant binary is going to use DLLs, you > need to link against the export libraries provided for those DLLs. > The export libraries only contain the external entry points into the > DLLs and a reference to the DLL, but they are still separate .lib > files that are necessary to build code to run against the DLLs. Thus, > anyone who provides DLLs for other source to use should also be > providing the matching .libs (or if you are building the DLLs from > source, the build process should also create matching .lib files). the current gcc in cygwin/mingw can link directly against DLLs (it creates the imp lib on the fly) one reason more to use free software ;-) chris -- Chris From peter at engcorp.com Mon Sep 15 14:00:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 15 Sep 2003 14:00:56 -0400 Subject: Finally found a use for lambda! References: <840592e1.0309150557.37661282@posting.google.com> Message-ID: <3F65FE58.AEF95A13@engcorp.com> Hannu Kankaanp?? wrote: > > follower at iname.com (Follower) wrote in message news:... > > > Of course, now that I think about it, I could have also written: > > > self.assertEqual (foo.has_key ('bar')), 0) > > > > ObMinimalism attempt: > > > > self.failIf(foo.has_key('bar')) > > That's not really minimalism (ObMinimalism=Obfuscation Minimalism? > That even less!). That is actually The way to do it. You can just > read it out loud and it makes sense immediately. Some folks prefer to stick with the positive logic (assert X) always, rather than risk confusion by mixing and matching in an arbitrary manner. Personally, I couldn't keep the negative logic of the "fail X" style straight and had to give it up. -Peter From gh at ghaering.de Mon Sep 1 10:42:41 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 01 Sep 2003 16:42:41 +0200 Subject: Python Documentation? In-Reply-To: <3f5357a0$0$32519$edfadb0f@dread16.news.tele.dk> References: <3f533f3d$0$32467$edfadb0f@dread16.news.tele.dk> <3f5357a0$0$32519$edfadb0f@dread16.news.tele.dk> Message-ID: <3F535AE1.9010403@ghaering.de> Dan Thrue wrote: > No i wont judge anything a failure in this community :) To say it > shortly, the wiki doesnt actually fill my requirements. I actually find the PHP approach of being able to attach user comments to doc pages useful. I try to stay clear from PHP ;-), but I do use it in the PostgreSQL interactive documentation: Here's an example: http://www.postgresql.org/docs/7.3/interactive/ddl-alter.html#AEN1984 I find it's a good way to add notes about what's not clear and what information is wrong or lacking to the docs. Certainly an easier approach than to file a bug report or a doc patch for the Python docs at Sourceforge. The PostgreSQL docs are created from SGML, while the Python docs are created from a LaTeX subset, so I don't know if there's any solution that could easily be set up for the Python documentation. I'd like to see it implemented, though. [1] -- Gerhard [1] If nothing else, I could then add "does anybody actually directly use this cra^wmodule?" to the page for ftplib <0.1 wink> From jack at performancedrivers.com Tue Sep 2 18:10:02 2003 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 2 Sep 2003 18:10:02 -0400 Subject: Python REST framework? In-Reply-To: ; from hwlgw@hotmail.com on Tue, Sep 02, 2003 at 02:52:05PM -0700 References: Message-ID: <20030902181002.B9745@localhost.localdomain> On Tue, Sep 02, 2003 at 02:52:05PM -0700, Will Stuyvesant wrote: > > [Jeremy Jones] > > Does anyone know if there exists a Python REST (web services) framework? > > I've googled and come up short. I don't think it should be that hard to > > do ... > > I'm interested. But I have been looking at the discussion on the rest > mailing list at http://groups.yahoo.com/group/rest-discuss/ and it > seems they haven't found a solution for the user:password thing yet. > Using SSL is a must, but then what? Create some unguessable URI? > That is not safe enough for banking applications etc. And using > lowlevel http stuff is also being frowned upon. > > Consider creating a multiuser web-based game in a RESTful way, where > players can use a password to get access to their avatar. I haven't > figured out yet how to do such a thing according to REST, using Python > Standard Library modules. Practicality beats purity, if the only piece of state you keep is "this guy is logged in and he authenticated as 'Bob'" then you still get 99.99% of the cleanliness of REST. If the workarounds to make it 100% REST-ful actually make the solution harder to use and implement then I'll gladly be [a little bit] non REST-ty. The point of REST is to make things easier to do and cleaner to understand, not just so you can name drop "REST", right? -jackdied From peter at engcorp.com Mon Sep 8 13:22:00 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 08 Sep 2003 13:22:00 -0400 Subject: Get the date of last modification of a file References: Message-ID: <3F5CBAB8.F8888E3@engcorp.com> Manuel Bastioni wrote: > > It's possible using only a built-in module? os.path.getmtime() From ta-meyer at ihug.co.nz Fri Sep 26 00:34:44 2003 From: ta-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 26 Sep 2003 16:34:44 +1200 Subject: When did Windows start accepting forward slash as a path separator? In-Reply-To: <1ED4ECF91CDED24C8D012BCF2B034F130364ACE8@its-xchg4.massey.ac.nz> Message-ID: <1ED4ECF91CDED24C8D012BCF2B034F130212AF65@its-xchg4.massey.ac.nz> > * None of the standard command shells (CMD or COMMAND) will > accept forward slashes. Even the "cd ./tmp" example given in > a previous post fails. Not true: """ Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\>cd /spambayes C:\spambayes>cd ./spambayes C:\spambayes\spambayes> """ This is with cmd.exe in XP (as above). command.exe does try and use it as a switch. I have no idea about older versions, nor do I care . =Tony Meyer From nav+posts at bandersnatch.org Fri Sep 5 22:52:54 2003 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 05 Sep 2003 22:52:54 -0400 Subject: OT: Americans love their guns References: Message-ID: Lulu of the Lotus-Eaters writes: > And should you be mugged on the street by a stranger, your chance of > walking away dead (rather than just with less money), are MANY times > higher if you pull a gun on your assailant. Just to contribute to the topic drift... I was mugged at gunpoint in the early 90's. I complied with my nervous-seeming assailant and even helped him get my watchband unbuckled. The police officer I talked to later said, "Good thing, or I might be filing my report from the morgue." Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From mwh at python.net Wed Sep 3 07:24:26 2003 From: mwh at python.net (Michael Hudson) Date: Wed, 3 Sep 2003 11:24:26 GMT Subject: Compiler C or Python? References: <20030826213316.GA7285@unpythonic.net> <7h3vfsbh1bg.fsf@pc150.maths.bris.ac.uk> Message-ID: <7h38yp6glt2.fsf@pc150.maths.bris.ac.uk> jhf at hex.no (J?rgen Hermanrud Fjeld) writes: > On Tue, Sep 02, 2003 at 11:37:03AM +0000, Michael Hudson wrote: > > jhf at hex.no (J?rgen Hermanrud Fjeld) writes: > > > And in general, if should want to alter the Python compiler, should > > > I start with the Python or C version? > > > > Whichever's easiest :-) This is usually the Python one. > > > Then I shall start with that one. Are there any other arguments/reasons to > choose one or the other? That is technicalities one should consider. I don't think so. The code they produce is essentially identical, AFAIK (the only difference I'm aware of is the ordering of the constants in co_consts -- hardly critical). Oh, Raymond Hettinger added some bytecode rewriting steps to the C compiler in 2.3. I don't think Lib/compiler does these. For *very* simple tweaks I sometimes find Python/compile.c easier to work with, but that's probably because Python/compile.c is a hunk of procedural C code I've worked with a fair bit and Lib/compiler is an OOP-y framework-y hunk of code I don't quite understand. Someone starting from scratch is unlikely to find this. Obviously, Python/compile.c gets more testing, and probably has fewer bugs. > > > As far as I can see from your email the Python version is easier to > > > modify, but why two compilers? Isn't that a lot to maintain? > > > > The Lib/compiler/ package is pretty slow. Also, making that the only > > compiler might lead to irritating bootstrapping problems (which I now > > see Jeff talked about...). > Yes, but the code it generates will be fast enough for my purposes. Oh yes, the compiled code runs at the same speed. > Do you happen to know how consistency between the compilers is > maintained? Blood and toil :-/ Cheers, mwh -- I have long since given up dealing with people who hold idiotic opinions as if they had arrived at them through thinking about them. -- Erik Naggum, comp.lang.lisp From tjreedy at udel.edu Thu Sep 11 16:00:23 2003 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Sep 2003 16:00:23 -0400 Subject: os.listdir References: Message-ID: "Duncan Booth" wrote in message > In C Python, all dictionaries have an initial size of 8 elements. There is > no way to override this (except recompiling!) In you initialize a dict from a list of, say, 1000 (key,value) pairs, does it really disregard list size? at least after first 2/3rds fillup? Terry From max at alcyone.com Sat Sep 27 18:15:02 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 27 Sep 2003 15:15:02 -0700 Subject: ANN: fauxident 1.2 -- A simple, faked ident daemon Message-ID: <3F760BE6.54AC64B2@alcyone.com> Summary A simple, faked ident daemon. Overview fauxident is a small Python script that will act as an extremely naive ident server, answering all ident requests with a consistent response -- either an ERROR or a USERID response. This can be advantageous on systems where running a true identd is unavailable, where it would be a security risk, or when masquerading firewalls are in use, where multiple machines are involved behind the firewall and running a proper ident system is not an option. Getting the software The current version of fauxident is 1.2. The latest version of the software is available in a tarball here: http://www.alcyone.com/software/fauxident/fauxident-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/software/fauxident/. Requirements fauxident requires Python 2.x or greater and a Unix or Unix-like operating system. License This code is released under the GPL. ... Release history [since 1.1] - 1.2; 2003 Sep 27. Add -m option to permute user names in responses. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE / \ We're here to preserve democracy, not to practice it. \__/ Capt. Frank Rasmey From newsgroups at jhrothjr.com Tue Sep 23 12:32:27 2003 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 23 Sep 2003 12:32:27 -0400 Subject: Executing a python script from an HTML link? References: Message-ID: "Andrew Chalk" wrote in message news:tMYbb.382$zy3.566196578 at newssvr11.news.prodigy.com... > Is this possible? In my CGI app. I display a web page with a link (anchor). > When the link is clicked I want to exectute a python script rather than go > to an HTML page. Do you want to run the script on the server or the client? If you want to run it on the client, you can use Python instead of Javascript (or in addition to Javascript) in the web page. Look at the